我想要做的是当它到达else并打印错误时我希望它循环回到choice1。
choice1 = input("Were would " + name + " like to go?\nThe Kitchen\nThe Couch\nOutside")
if choice1 == "The Kitchen":
choices.append("The Kitchen")
print(name + " walked towards The Kitchen.")
elif choice1 == "The Couch":
choices.append("The Couch")
print(name + " went and had sat on The Couch.")
elif choice1 == "Outside":
choices.append("Outside")
print(name + " put on their pack and went out the door.")
else:
print("error")
如果有错误/它到达其他地方我希望它循环回到choice1。
我会尽力回答pythonic的方式(即使我不认为自己是Python专家):Python非常适合列表和词典,你可以避免像switch / case这样的东西。这是你对Python方式的比较:
name = "Olivier"
possible_choices = {
"The Kitchen": lambda name: "{} walked towards The Kitchen.".format(name),
"The Couch": lambda name: "{} went and had sat on The Couch.".format(name),
"Outside": lambda name: "{} put on their pack and went out the door.".format(name),
}
while True:
choice = input("Were would {} like to go?\n{}\n>".format(
name, '\n'.join(possible_choices)))
if choice in possible_choices:
print(possible_choices[choice](name))
break; # break the loop
print("error") # loops
接着就,随即:
学习如何使用在每种现代语言中使用的lambdas(=匿名函数),这个“if choice in possible_choices
”非常清晰,几乎可以说是英语!
while True:
choice1 = raw_input("Were would " + name + " like to go?\nThe Kitchen\nThe Couch\nOutside")
if choice1 == "The Kitchen":
choices.append("The Kitchen")
print(name + " walked towards The Kitchen.")
break
elif choice1 == "The Couch":
choices.append("The Couch")
print(name + " went and had sat on The Couch.")
break
elif choice1 == "Outside":
choices.append("Outside")
print(name + " put on their pack and went out the door.")
break
else:
print("error")
continue
您可以使用while循环并使if / elif语句使其转义循环。像这样:
a = True
while a:
choice1 = input("Were would " + name + " like to go?\nThe Kitchen\nThe Couch\nOutside")
if choice1 == "The Kitchen":
choices.append("The Kitchen")
print(name + " walked towards The Kitchen.")
a = False
elif choice1 == "The Couch":
choices.append("The Couch")
print(name + " went and had sat on The Couch.")
a = False
elif choice1 == "Outside":
choices.append("Outside")
print(name + " put on their pack and went out the door.")
a = False
else:
print("error")
a是一个设置为true的布尔语句。该脚本进入while循环,该循环在== True时运行。所有if / elif语句都为false,导致循环结束。