从其他函数导入变量

2024-09-30 16:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过搜索和尝试人们为他人提出的建议,但对我无效,以下是我的代码:

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'以外的任何键时,我得到变量是未定义的

如果我在“DisplayAccountInfo()”中手动设置它,那么它不会抛出任何错误

这只是我在胡闹和试图理解python,如果有人能帮忙的话那就太好了


Tags: nameyouinputageyourisdeffirstname
2条回答

使用unpacking operator, *

DisplayAccountInfo(*CreateAccount())

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

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

您在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)

相关问题 更多 >