我制作了这个简单的代码,试图说明我遇到的Python问题。这是代码:
def Main():
print("In Main.")
while(True):
TheInput1 = input("Go To Sub?:")
if(TheInput1.lower() == "y"):
Sub()
break
elif(TheInput1.lower() == "n"):
print("bye")
quit()
else:
print("what?")
Main()
def Sub():
print("In Sub");
while(True):
TheInput2 = input("Go To Main?:")
if(TheInput2.lower() == "y"):
Main()
break
elif(TheInput2.lower() == "n"):
print("bye")
quit()
else:
print("what?")
Sub()
每当我输入y时,它会给我一个错误,而不是去Sub。这是错误:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 6, in Main
NameError: name 'Sub' is not defined
我确定解决方案非常简单,但我不知道如何实现这一目标。
答案 0 :(得分:4)
在Sub定义之前,您正在调用main,将主要调用移到sub。
之下def Main():
print("In Main.")
while(True):
TheInput1 = input("Go To Sub?:")
if(TheInput1.lower() == "y"):
Sub()
break
elif(TheInput1.lower() == "n"):
print("bye")
quit()
else:
print("what?")
def Sub():
print("In Sub");
while(True):
TheInput2 = input("Go To Main?:")
if(TheInput2.lower() == "y"):
Main()
break
elif(TheInput2.lower() == "n"):
print("bye")
quit()
else:
print("what?")
Main()
Sub()