gpt4 book ai didi

python - 在Python中的两个函数之间传递字符串变量

转载 作者:行者123 更新时间:2023-12-01 02:23:38 25 4
gpt4 key购买 nike

我在将变量从一个函数传递到另一个函数时遇到问题:

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 surname() 中输入的姓氏

我总是收到first_name未定义的错误,并且我不知道如何从第一个函数导入它。我得到的错误是:

    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 - 在Python中的两个函数之间传递字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47676972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com