如何在一个函数中将变量获取到python中的另一个函数?

时间:2017-05-21 06:43:31

标签: python python-3.x sqlite python-3.6

代码:

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()函数。

2 个答案:

答案 0 :(得分:0)

您可以将其作为参数传递,也可以将其全局访问。看看有关范围概念的一些阅读。

https://www.smallsurething.com/how-variable-scope-works-in-python/

答案 1 :(得分:0)

您正在从user_Id_Input返回authentication(),但未在user_balance()中捕获返回的值。这就是返回值丢失的原因。使用 -

user_Id_Input = authentication() 
user_balance()中的

。这样你就可以捕获返回的值。

如果您想避免返回但仍希望从其他功能访问user_Id_Input,则可以将user_Id_Input设为全局。然后你可以通过适当的方法访问它。

现在我想指出您可能希望改进的代码的其他一些方面。首先,您应该在conn.commit() return语句之前移动authentication()。在data_insert()中,您还希望在函数结束时执行commit。还有一件事,您可能需要考虑为表customer添加主键。在data_insert()中,如果用户提供了存款的负值或0值,则表示您警告用户有关无效余额但不会阻止您的代码插入相同值。