我想在Python中運行這段代碼。 (我省略了「listAccounts」功能的身體,因爲我有沒有問題)Python不保存一個簡單變量的值
import os
customers = []
numAccounts = 0
option = 0
def listAccounts(customers):
(...)
def createAccount(customers, numAccounts):
name = input('Enter a name: ')
lastname = input('Enter a lastname: ')
account = {'name':name, 'lastname':lastname, 'account':{'balance':0, 'accountNumber':numAccounts}}
customers.append(account)
numAccounts += 1
print("Account created")
input("Press Intro to continue...")
return customers, numAccounts
while ('3' != option):
option = input('''Please select an option:
1.- List Accounts
2.- Create Account
3.- Exit
''')
if option == '1':
listAccounts(customers)
elif opcion == '2':
createAccount(customers, numAccounts)
os.system("CLS")
print("End of the program")
問題是,當我創建一個「的createAccount」功能的新帳戶。當我輸入值並保存時,一切正常。我顯示帳戶和第一個帳號是0.一切都很順利,但是當我再次創建一個新帳戶並列出它們時,我意識到兩個帳戶都有數字0,即使我創建了第三個帳戶, 0.如果'numAccounts'變量不增加。
我放棄了我的程序,我注意到'numAccounts'的值真的增加到1,但是當進入'return'行時,它再次將值設爲0。我評論'返回'路線,改變價值觀等,但沒有任何作用。有人知道我的代碼有什麼問題嗎?
謝謝你回答,Genaro。我詳細瞭解了函數中變量的行爲,並且我已經解決了在'createAccount'函數中添加'global'關鍵字的問題,所以通過這種方式我可以在值增加時保存該值。謝謝你的時間。 –