繁体   English   中英

使用来自另一个 function python3 的值

[英]Use values from another function python3

我有这个代码,但我不知道如何在另一个 function 中使用用户的“年龄”,有什么线索我错了吗?

def accounts():
    yourCode = input("Please enter your user code. \nIf you already have an account, type your account user code. \nOtherwise, enter a new one to create an account: ")

   
    with open("users.txt", "r") as rf:
        users = rf.readlines() 
        for each_user in [user.split(",") for user in users]: 
            if each_user[0] == yourCode: 
                print(f"Welcome {each_user[1]}") 
                age = each_user[2]
                xxApp() 
                return None 
    with open("users.txt", "a") as af:
        name = input("Please enter your name: ")
        age = input("Enter your age: ")
        af.write(f"{yourCode},{name},{age}\n") 
        print(f"Thank you {name}, your information has been added.")
        xxApp()


def xxApp():
    age = each_user[2]
    print(age)


将其作为参数传递

def accounts():
    yourCode = input("Please enter your user code. \nIf you already have an account, type your account user code. \nOtherwise, enter a new one to create an account: ")

   
    with open("users.txt", "r") as rf:
        users = rf.readlines() 
        for each_user in [user.split(",") for user in users]: 
            if each_user[0] == yourCode: 
                print(f"Welcome {each_user[1]}") 
                xxApp(each_user) 
                return None 
    ...


def xxApp(user):
    age = user[2]
    print(age)

您正在定义age = each_user[2] ,但each_user变量仅在accounts()的 scope 中可用。

您可以在此处阅读有关 python 范围的信息

我会修改xxApp() function 以将变量作为这样的参数

def xxApp(each_user):
    age = each_user[2]
    print(age)

然后你调用xxApp()并将each_user作为参数传递,所以它在xxApp()的 scope 中可用,就像这样xxApp(each_user)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM