【问题标题】:Importing Variables from other functions从其他函数导入变量
【发布时间】:2017-10-15 04:02:07
【问题描述】:

我已经尝试搜索和尝试人们为他人提出的建议,但它对我不起作用,这是我的代码:

def CreateAccount():
    FirstName = input('What is your first name?: ')
    SecondName = input('What is your second name?: ')
    Age = input('How old are you?: ')
    AreaLive = input("What area do you live in?: ")
    return FirstName, SecondName, Age, AreaLive

def DisplayAccountInfo(FirstName,SecondName,Age,AreaLive):
    print("Your Firstname is",FirstName)
    print("Your Secondname is",SecondName)
    print("You are",Age," years old")
    print("You live in the",AreaLive," area")
    return




def ConfirmAccountF():
    ConfirmAccount = input("Do you have an account? y,n; ")
    if  ConfirmAccount == "n":
        CreateAccount()

    else: #ConfirmAccount -- 'y'
        DisplayAccountInfo()

while True:

    ConfirmAccountF()

所以它现在应该无限期地运行,但我想要它做的是将变量从“CreateAccount”传递到“DisplayAccountInfo”。

当我为 'ConfirmAccount' 按 n 以外的任何内容时,我发现变量未定义。

如果我在 'DisplayAccountInfo()' 中手动设置它,它不会引发任何错误。

这只是我在搞砸并试图理解 python,如果有人可以提供帮助,那就太好了。

【问题讨论】:

  • createAccount 正在返回变量,但您没有将它们分配给任何东西。改为执行data = CreateAccount() 之类的操作,然后在DisplayAccountInfo() 函数中传递*data
  • 您想在DisplayAccountInfo() 中显示哪些帐户信息?如果用户输入y,你怎么知道要显示哪个帐户的信息?

标签: python function variables


【解决方案1】:

使用unpacking operator, *:

DisplayAccountInfo(*CreateAccount())

它的作用是获取CreateAccount 返回的四个字符串的元组,并将它们转换为四个参数,作为单独的参数传递给DisplayAccountInfo。而如果您省略了* 运算符而只调用了DisplayAccountInfo(CreateAccount()),则会将一个元组参数传递给DisplayAccountInfo,从而导致TypeError 异常(因为DisplayAccountInfo 需要四个参数,而不是一个)。

当然,如果您还需要保存从CreateAccount 返回的字符串以供以后使用,则需要在调用CreateAccount 和DisplayAccountInfo 之间执行此操作。

【讨论】:

    【解决方案2】:

    您在CreateAccount() 上声明的变量无法通过其名称从外部访问。要将信息传递给另一个函数,您需要先存储其值:

    first_name, second_name, age, area = "", "", "", ""
    
    def ConfirmAccountF():
        ConfirmAccount = input("Do you have an account? y,n; ")
        if  ConfirmAccount == "n":
            first_name, second_name, age, area = CreateAccount()
    
        else: #ConfirmAccount -- 'y'
            DisplayAccountInfo(first_name, second_name, age, area)
    

    【讨论】:

    • 另外,我的代码不是最好的,但我认为不需要进一步了解python就很容易理解
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多