例如,假設我正在嘗試在 python 中創建一個錢包系統,可以在其中添加和取出錢。我在這里嘗試這段代碼:
balance = 0
def addmoney(x):
x = balance
addmoney(10000)
print(balance)
但它只給了我 0。所以我嘗試了這個:
def addmoney(x):
balance = 0
balance = x
而且我意識到,每次用戶添加資金時,這都會將資金設定回 0,這是我不想要的。有針對這個的解決方法嗎?
uj5u.com熱心網友回復:
您可以在函式內將balance變數宣告為全域變數。
balance = 0
def addmoney(x):
global balance
balance = x
addmoney(10000)
print(balance)
uj5u.com熱心網友回復:
這通常與 OOP 相關:
class BankAccount:
def __init__(self, owner, balance, currency):
self.owner = owner
self.balance = balance
self.currency = currency
def print_balance(self):
print("Your current balance is:")
print(self.balance)
def make_deposit(self, amount):
if amount > 0:
self.balance = amount
else:
print("Please enter a valid amount.")
def make_withdrawal(self, amount):
if self.balance - amount >= 0:
self.balance -= amount
else:
print("You don't have enough funds to make this withdrawal.")
呼叫函式:
my_savings_account = BankAccount("Pepita Perez", 45600, "USD")
my_savings_account.print_balance()
my_savings_account.make_deposit(5000)
my_savings_account.make_withdrawal(200)
my_savings_account.print_balance()
uj5u.com熱心網友回復:
在 Python 中,從函式內訪問全域變數時必須使用global關鍵字。見這里。
跟蹤更改的一種方法是將以前的值存盤在函式外部的串列中。再次,使用global關鍵字
你的平衡邏輯也是倒退的。您應該將 x 添加到余額中。
balance = 0
historyLst = []
def addmoney(x):
global balance
global historyLst
historyLst.append(balance)
balance = x
addmoney(10000)
print(balance)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507869.html
下一篇:Python-線性到對數比例轉換