gpt4 book ai didi

Python 业余爱好者 - 'Greeting program' - 'Referenced before assignment error'

转载 作者:行者123 更新时间:2023-11-28 22:48:49 24 4
gpt4 key购买 nike

正如我在上一个问题中所说,我是一名 Python 业余爱好者。我犯了几个愚蠢的错误。我正在尝试使用 Python 3.4 制作一个非常简单的问候语程序,但是我遇到了一个错误。我的错误是:

UnboundLocalError:赋值前引用局部变量“lastNameFunction”

这是我的代码(我知道我可能不需要全部发布,但代码不多):

def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()

def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()

我将不胜感激任何帮助和建议!请考虑到我对这些东西真的很陌生。我也不太确定在函数内部有一个函数,但我认为这将是一个修复,以便在输入“lastName”时可以使用“firstName”。

提前致谢! :)

最佳答案

在使用 lastNameFunction() 调用它之前,您需要将 lastNameFunction 声明移动到某处,例如:

def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)

time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")

def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()

if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()

if __name__ == '__main__':
main()

您也可以将它移到 main 函数之外,但是您需要在使用函数参数时传递 firstName:

def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()

def main():
...
lastNameFunction(firstName)
...

关于Python 业余爱好者 - 'Greeting program' - 'Referenced before assignment error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24723525/

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