就像我在上一个问题中所说的那样,我是一个蟒蛇业余爱好者。我犯了几个愚蠢的错误。我尝试使用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()
我很感激任何帮助和建议!请注意我对这个东西真的很新。我也不太确定在函数内部有一个函数,但我认为这将是一个修复,以便' firstName'输入' lastName'时可用。
提前致谢! :)
答案 0 :(得分:2)
在通话前将lastNameFunction
移至某处。理想情况下,您可以将其置于main
函数之上。
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...
答案 1 :(得分:2)
在使用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)
...
答案 2 :(得分:0)
问题是你在while循环中定义它之前调用了lastNameFunction()。尝试在while循环之外定义函数。
答案 3 :(得分:0)
整个计划的组织似乎有点偏离。
main()
内的来电main()
之类的递归来电是错误的。当你采用那种控制流而不是循环时,你最终会遇到递归调用的限制(→RuntimeError)。您已经拥有必要的循环,因此只需省略elif
分支就会再次要求用户输入名字。running
未在任何地方使用,因此您可以将其删除,只需使用while True:
。我会向用户询问“任何事情”+问题输入是否正确进入其自己的功能:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()