我无法将变量从一个函数传递到另一个函数:
def name():
first_name=input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
return surname()
def surname():
last_name=input("\nCan you tell my your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
return surname()
else:
print("Nice to meet you %s %s." % (first_name,last_name))
我希望最后一个命令从def name()
打印输入的first_name,从def surname()
打印姓氏
我总是得到first_name未定义的错误,我不知道如何从第一个函数导入它。我得到的错误是:
print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
我做错了什么?
答案 0 :(得分:2)
您需要在函数调用中传递信息:
def name():
first_name = input("What is your name? ")
if len(first_name) == 0:
print("\nYou did not enter a name!")
return name()
else:
print("\nHello %s." % first_name)
surname(first_name) # pass first_name on to the surname function
def surname(first_name): #first_name arrives here ready to be used in this function
last_name = input("\nCan you tell my your last name please?")
if len(last_name) == 0:
print("\nYou did not enter a last name!")
surname(first_name)
else:
print("Nice to meet you %s %s." % (first_name,last_name))
name()
答案 1 :(得分:0)
def functionname(untypedparametername):
# do smth with untypedparametername which holds "Jim" for this example
name = "Jim"
functionname(name) # this will provide "Jim" to the function
如果查看文档中的示例,可以看到它们的用法。在这里:https://docs.python.org/3/library/functions.html
也许你应该阅读一些基础教程,你可以在python主页上找到很多这些教程:https://wiki.python.org/moin/BeginnersGuide
答案 2 :(得分:0)
您还可以使用while循环不断询问名称,直到有效输入为止。
def name_find():
while True:
first_name=raw_input("What is your name? ")
if len(first_name)==0:
print("\nYou did not enter a name!")
return name_find()
else:
print("\nHello %s." % first_name)
return surname(first_name)
def surname(first_name):
while True:
last_name=raw_input("\nCan you tell me your last name please?")
if len(last_name)==0:
print("\nYou did not enter a last name!")
else:
print "Nice to meet you %s %s." % (first_name, last_name)
break