我需要让我的程序中断循环并在用户拒绝时结束。中断不起作用,因为它只会出现“中断未正确循环”的错误。
import random
import time
motiv_list = ["aaaaaaaaaaa", "frick"]
while True:
UserFeeling_str=raw_input("How are you feeling today?")
if UserFeeling_str == "happy":
print(random.choice(motiv_list))
time.sleep(1.50)
QuoteReplay_str=raw_input("Would you like to hear another quote?")
if QuoteReplay_str == "yes":
print()
elif QuoteReplay_str == "no":
# (need to know what goes here)
答案 0 :(得分:1)
您似乎有缩进问题。
import random
import time
motiv_list = ["aaaaaaaaaaa", "frick"]
while True:
UserFeeling_str=raw_input("How are you feeling today?")
if UserFeeling_str == "happy":
print(random.choice(motiv_list))
time.sleep(1.50)
QuoteReplay_str=raw_input("Would you like to hear another quote?")
if QuoteReplay_str == "yes":
print()
elif QuoteReplay_str == "no":
break
但是这里有一些未指定行为的警告:
if UserFeeling_str != "happy":
QuoteReplay_str
既不是yes
也不是no
,该怎么办?
if QuoteReplay_str == "yes"
,然后再拥有else
而不是elif QuoteReplay_str == "no"
答案 1 :(得分:0)
示例中的缩进位于while循环之外。
import random
import time
motiv_list = ["aaaaaaaaaaa", "frick"]
while True:
UserFeeling_str=raw_input("How are you feeling today?")
if UserFeeling_str == "happy":
print(random.choice(motiv_list))
time.sleep(1.50)
QuoteReplay_str=raw_input("Would you like to hear another quote?")
if QuoteReplay_str.lower() == "yes":
print()
elif QuoteReplay_str.lower() == "no":
break
应该工作。添加.lower()还可以使您接受“否”和“是”作为有效答复。
或者,您可以将其包含在while循环条件中,因为它位于循环活动的结尾:
QuoteReplay_str = ""
while QuoteReplay_str.lower() != "no":
#rest of stuff