[英]Importing Variables from other functions
我嘗試過搜索並嘗試人們為別人提出的建議,但它不適合我,這是我的代碼:
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,如果有人可以幫助那將是偉大的。
使用解包操作符* :
DisplayAccountInfo(*CreateAccount())
這樣做是為了獲取CreateAccount
返回的四個字符串的元組,並將它們轉換為四個參數,作為單獨的參數傳遞給DisplayAccountInfo
。 如果省略了*
運算符並且只調用了DisplayAccountInfo(CreateAccount())
,那么會將單個元組參數傳遞給DisplayAccountInfo
,從而導致出現TypeError
異常(因為DisplayAccountInfo
需要四個參數,而不是一個參數)。
當然,如果您還需要保存從CreateAccount
返回的字符串以供以后使用,則需要在調用CreateAccount
和DisplayAccountInfo
之間執行此操作。
您在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.