任何人都知道如何验证这个?我只是在尝试如何使我的代码更简洁。
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
choose_mode = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
choose_mode[user_input]()
感谢您提前回复
答案 0 :(得分:2)
choice = None
while choice is None:
user_input = int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
choice = choose_mode.get(user_input)
如果密钥不存在,字典上的get
方法将返回None
。您可以循环检查这一点,如果用户给出无效答案,则再次提示用户。
答案 1 :(得分:0)
if user_input in (0,1,4,9):
pass
else:
Restart
这是你要找的东西吗?
答案 2 :(得分:0)
除了验证之外,您还有更多问题。
首先,函数的主体需要缩进 - 请记住Python是缩进敏感的:
SELECT RegionId, 'Price1' AS PriceList, Price1 AS [Current], Price1New AS NewPrice, Efx1Date AS EfxDate
UNION ALL
SELECT RegionId, 'Price2' AS PriceList, Price2 AS [Current], Price2New AS NewPrice, Efx2Date AS EfxDate
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
看起来不正确。这是一个字典,其中第一个条目的键是choose_mode
(0
是一个整数,所以没问题),但是什么是0
? hard
是对函数的引用,但hard()
不是那么清楚。
我假设您想让用户输入数字以便于访问,但您不希望在整个应用程序逻辑中使用语义无意义的数字(这是一种很好的做法!)。如果是这种情况,hard
可以重新用于将任意数字映射到语义上有意义的字符串:
choose_mode
现在,您可以使用choose_mode = {
0: "hard",
1: "medium",
4: "lazy",
9: "easy"
}
user_input = int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
条件验证用户输入。字典值可通过字典的if/else
方法访问:
.get()
全部放在一起:
if choose_mode.get(user_input) == "hard":
hard()
elif choose_mode.get(user_input) == "medium":
medium()
elif choose_mode.get(user_input) == "easy":
easy()
elif choose_mode.get(user_input) == "lazy":
lazy()
else:
# the user's input was neither 0, nor 1, nor 4, nor 9
print "invalid"