对
python来说很新,并且作为练习,已经做了一个基于文本的棋盘游戏版本(我是一个狂热的棋盘游戏玩家).
显然有很多地方供用户输入内容,当然我需要评估这些输入并确保它们有效.
我学会了使用True / False检查和来自这个网站的循环(谢谢!),现在我已经做了很多,我想知道是否有更好的方法 – 如果它们是嵌套的,它们会变得有点疯狂我想尽我所能坚持那些像Zen一样的Python规则.
这就是我的意思,在一个简单的例子中,使用通用代码使它有意义(并非所有人都知道这个棋盘游戏的规则!)
目标是确保代码循环,直到给出颜色或“无”.我知道这完成了,我只是想知道是否还有一种我尚未学习的更简化的方法.
colors = ["red", "green", "white", "blue", "yellow"]
for color in colors:
print(f"You can choose {color}.")
choice = input("Which color would you choose? (input a color or 'none' : ")
checker = False
while not checker:
if choice not in colors:
choice = input("That's not one of your options. Choose again: ")
elif choice == "none":
print("You don't want a color. That's fine.")
checker = True
else:
print("You chose {color}! Have fun!")
checker = True
最佳答案 如果你发现自己重复相同的事情,你可以定义一个泛型函数
def prompt_for_valid_input(options):
while True:
print(f"You can choose one of {options}.")
choice = input("Which would you choose? (or 'none' : ")
if choice == "none" and "none" not in options:
print("You didn't pick anything. That's fine.")
return None
elif choice in options:
return choice
else:
print("That's not one of your options. Choose again. ")
colors = ["red", "green", "white", "blue", "yellow"]
color = prompt_for_valid_input(colors)
if color is not None:
print(f"You chose {color}! Have fun!")
numbers = [1, 10, 100]
num = prompt_for_valid_input(numbers)
if num is not None:
print(f"You chose {num}! Have fun!")
所以“没有一会儿/ for循环”,不是真的.没有sentinel变量,是的,如果条件足够简单.