【问题标题】:Use values from another function python3使用来自另一个函数 python3 的值
【发布时间】:2021-01-23 17:26:09
【问题描述】:

我有这段代码,但我不知道如何在另一个函数中使用用户的“年龄”,知道我有什么问题吗?

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)


【问题讨论】:

    标签: python python-3.x function


    【解决方案1】:

    作为参数传递

    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)
    

    【讨论】:

      【解决方案2】:

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

      You can read about python scopes here

      我会修改xxApp() 函数以接受一个变量作为这样的参数

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

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

      【讨论】:

        猜你喜欢
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        • 2020-08-11
        相关资源
        最近更新 更多