command=input("> ").lower()
while command!="quit":
if command=="start":
print("go")
elif command=="stop":
print("stop")
elif command=="help":
print("quit,start,stop")
else:
print("I can't understand")
command=input("> ").lower
#第一种情况:输入“quit”,直接不进入循环,程序结束
#第二种情况:输入除“quit”外任意字符,再输入“quit”却不退出循环,而执行else
问题就是,我第一次输入“quit”以外的字符后,再输入“quit”程序不应该执行循环的判断语句,此时判断语句不成立,却不退出循环,这是为什么呢
你循环里的lower没打括号,嗯我也是小白
command=input("> ").lower()
while command!="quit":
if command=="start":
print("go")
elif command=="stop":
print("stop")
elif command=="help":
print("quit,start,stop")
else:
print("I can't understand")
command=input("> ").lower()
这个程序出bug的原因有些奇怪,可能是两个input语句所造成的。(具体原因我也不太清楚)
我按你的思路对程序进行了一些修改,以下是代码:
while True:
command=input("> ").lower()
if command=="start":
print("go")
elif command=="stop":
print("stop")
elif command=="help":
print("quit,start,stop")
elif command=="quit":
break
else:
print("I can't understand")
注:当while需要无限循环时,最好使用while True: 这样的写法,等到需要退出循环时可以使用break语句来退出
text='>' # 首先你不能把input放在while循环的外边,这样会死循环的,你可以把文本先放在一个变量里
active=True # 设立一个变量让它等于True,这样它等于False时就能退出循环了
while active:
command=input(text) # input直接打印文本text
if command=="start":
print("go")
elif command=="stop":
print("stop")
elif command=="help":
print("quit,start,stop")
elif command=='quit': # 设定elif如果等于quit,active就是False,退出while循环
active=False
else:
print('I can not understand')