2017-05-21 20 views
0

代碼:如何獲取一個函數中的變量到python中的另一個函數?

def create_Table(): 
    c.execute('CREATE TABLE IF NOT EXISTS customer(name TEXT NOT NULL, accountNo INTEGER NOT NULL, balance INTEGER NOT NULL)') 
    conn.commit() 

def data_insert(): 
    name = str(input("Enter your name: ")) 
    accountNo = random.randrange(2016000,2025000) 
    balance = int(input("Enter your initial deposit: $")) 
    if balance>0: 
     print("You have successfully opened an account, your account number is: ",accountNo) 
    else: 
     print("Incorrect initial deposit, Please deposit $1 or more") 
    c.execute("INSERT INTO customer VALUES(?, ?, ?)",(name, accountNo, balance)) 


def authentication(): 
    user_Id_Input = int(input("Enter your account number: ")) 
    c.execute("SELECT * FROM customer WHERE accountNo = ?",(user_Id_Input,)) 
    return user_Id_Input 
    conn.commit() 

def user_balance(): 
    authentication() 
    if c.fetchall() is not None: 
     c.execute("SELECT balance FROM customer WHERE accountNo = ? "(user_Id_Input,)) 
     data = c.fetchone() 
     print("Your balance is: $",data) 
    else: 
     print("You have entered an incorrect account number.") 
    conn.commit() 

我想要得到的變量user_Id_Inputdef authentication():def user_balance():。即使我編碼authentication()def user_balance():我仍然無法獲得該變量的balance()函數。

+0

您正在從'authentication()'返回'user_Id_Input',但未捕獲'user_balance()'中返回的值。在'user_balance()'中使用'user_Id_Input = authentication()'。你也應該在'authenticate()'''return'語句之前移動'conn.commit()' – kuro

回答

0

您在返回從authentication()user_Id_Inputuser_balance()沒有捕捉返回值。這就是爲什麼返回的值會丟失。使用 -

user_Id_Input = authentication() 

in user_balance()。這樣你可以捕獲返回的值。

如果您想避免返回,但仍想從其他函數訪問user_Id_Input,則可以使user_Id_Input爲全局。然後你可以通過適當的方法訪問它。

現在我想指出一些您可能想要改進的其他代碼區域。首先,您應該在authentication()之前的return聲明之前移動conn.commit()。在data_insert()中,您還希望在該函數結束時執行commit。還有一件事,你可能想考慮爲你的表customer添加一個主鍵。在data_insert()中,如果用戶提供了負值或0值作爲存款,則會警告用戶有關無效餘額的信息,但不會阻止您的代碼插入相同的值。

+0

我這樣做了,但是我得到一個錯誤:'c.execute(「select balance FROM customer WHERE accountNo =?」(user_Id_Input ,)) TypeError:'str'對象不可調用' –

+0

因爲您錯過了逗號。它應該是'c.execute(「選擇餘額從客戶WHERE accountNo =?」,(user_Id_Input,))' – kuro

+0

@enochronchi,這是否解決您的問題? – kuro

相關問題