在Python中的两个函数之间传递字符串变量
我无法将变量从一个函数传递到另一个函数:在Python中的两个函数之间传递字符串变量,python,string,variables,Python,String,Variables,我无法将变量从一个函数传递到另一个函数: 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)
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()
中输入的名字和def姓氏()
我总是得到一个错误,第一个_名称没有定义,我不知道如何从第一个函数导入它。我得到的错误是:
print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
我做错了什么?您需要在函数调用中传递信息:
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()
如果查看文档中的示例,您可以看到它们是如何使用的,例如:
也许您应该阅读一些基础教程,您可以在python主页上找到许多教程:您还可以使用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
更改
姓氏
函数为姓氏(名字)
并使用返回姓氏(名字)
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