2017-06-30 17 views
-1

我想在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。我評論'返回'路線,改變價值觀等,但沒有任何作用。有人知道我的代碼有什麼問題嗎?

回答

0

的問題是變量NUMACCOUNTS個的範圍,你定義了功能的createAccount(客戶,NUMACCOUNTS個),這意味着,NUMACCOUNTS個變量你增加由一個只在功能內存活。當您將numAccounts變量定義爲全局變量時,您可以像createAccount(customers,currentnumAccounts)一樣定義函數,並且當您調用numAccounts + = numAccounts時,您將增加全局變量。

+0

謝謝你回答,Genaro。我詳細瞭解了函數中變量的行爲,並且我已經解決了在'createAccount'函數中添加'global'關鍵字的問題,所以通過這種方式我可以在值增加時保存該值。謝謝你的時間。 –

0

因爲您不存儲createAccount返回的內容。

儘管您已經在全局級別創建了所有變量,但您正在接收具有相同名稱的變量,因此函數將生成該變量的本地副本,並且它不會更改全局變量的值。

while循環應該是如下

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': 
     customers,numAccounts = createAccount(customers, numAccounts) 
    os.system("CLS") 
print("End of the program") 
相關問題