对于python来说是新手,并且作为练习,它正在做基于文本的棋盘游戏(我是一个狂热的棋盘游戏玩家)。
用户输入的内容显然有很多地方,自然地,我需要评估这些输入并确保它们有效。
我从该站点了解了关于使用True / False检查和for循环的信息(谢谢!),而现在我已经做了很多,所以我想知道是否有更好的方法-如果他们是嵌套,我想尽最大努力遵守那些类似于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
答案 0 :(得分:1)
如果发现自己重复相同的内容,则可以定义通用函数
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!")
所以“没有while / for循环”,不是真的。如果条件足够简单,则没有哨兵变量,可以。
答案 1 :(得分:0)
您可以将其抽象为经过验证的通用输入法
def validated_input(prompt,validation_method,error_message):
while True:
result = input(prompt)
if validation_method(result):
return result
print(error_message)
choices = ['red','green','blue','none']
validator = lambda test:test.lower().strip() in choices
prompt = "Enter A Color(one of Red, Green, Blue, or None):"
error_message = "Please enter a valid color or None!"
print(validated_input(prompt,validator,error_message))
这是否“更好”有争议
答案 2 :(得分:0)
通常,您编写代码的方式被认为是“正常”的,而且直截了当,这很好。问题是,您希望代码的循环部分重复执行,直到达到预期为止。因此,有条件的循环事件是必要的。如果您真的想要,可以通过以下中断语句将其简化:
named export
这将创建一个无限循环,直到满足您要查找的条件,然后它将脱离循环。但是请确保您有逃生条件。