我想让程序在没有用户输入的情况下启动,所以我将start设置为true,并在启动时启动它。但是,如果用户输入true以运行主程序,则会出现错误,并表示未定义main()。
start = True
while start:
print("Hello world!")
name=input("Please enter your name: ")
print("Hi {0}".format(name))
run=input("type | True | to run the program: ").capitalize()
if run== "True":
print("Program is starting..")
main()
start = False
else:
print("You need to enter | True | to run the program")
start = True
def main():
print("1 = Add")
print("2 = Subtract")
print("3 = Times")
print("4 = Divide")
print("5 = Quit program")
calc=int(input("enter number of choise: "))
继承人的错误:
Hello world!
Please enter your name: pls no
Hi pls no
type | True | to run the program: true
Program is starting..
Traceback (most recent call last):
File "C:\Users\chemg\Documents\calculator.py", line 11, in <module>
main()
NameError: name 'main' is not defined
答案 0 :(得分:2)
在main
之前移动while start
。你指的是一个尚未定义的函数。
答案 1 :(得分:1)
您在第一次通话后定义main。通常,您首先定义所有函数,然后使用它们。
def main():
print("1 = Add")
print("2 = Subtract")
print("3 = Times")
print("4 = Divide")
print("5 = Quit program")
calc=int(input("enter number of choise: "))
start = True
while start:
print("Hello world!")
name=input("Please enter your name: ")
print("Hi {0}".format(name))
run=input("type | True | to run the program: ").capitalize()
if run== "True":
print("Program is starting..")
main()
start = False
else:
print("You need to enter | True | to run the program")
start = True
应该有效
答案 2 :(得分:1)
Python脚本从上到下执行。进入主循环时,未定义主函数。交换它们的顺序。
答案 3 :(得分:1)
Python解释器按顺序读取和执行脚本。当你的代码到达它调用函数main的点时,它还没有被读取,因此在那时解释器不知道。
要解决此问题,请将功能置于您调用它的位置之上(在您的情况下,在&#39; start = True&#39;。
之前)答案 4 :(得分:0)
看起来你需要移动功能块。程序无法识别main(),因为在你的while循环内部调用它时,它还没有被定义。
试试这个:
def main():
print("1 = Add")
print("2 = Subtract")
print("3 = Times")
print("4 = Divide")
print("5 = Quit program")
calc=int(input("enter number of choise: "))
start = True
while start:
print("Hello world!")
name=input("Please enter your name: ")
print("Hi {0}".format(name))
run=input("type | True | to run the program: ").capitalize()
if run== "True":
print("Program is starting..")
main()
start = False
else:
print("You need to enter | True | to run the program")
start = True