2017-10-11 26 views
-2

任何人都知道如何验证这一点?我只是在试验如何让我的代码更加简洁。只是一些验证

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]() 

感谢您的任何答复提前

+2

如何验证究竟是什么? – glibdud

+0

另外,格式化您的代码。此缩进无效。 –

+2

为什么这个标记为python2.7 *和* python3.x ...?这是什么?你是否运行两个版本? –

回答

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如果该键不存在。您可以在循环中检查此信息,并在用户提供无效答案时再次提示用户。

0
if user_input in (0,1,4,9): 
    pass 
else: 
    Restart 

这是不是你要找的?

0

你的问题比验证更多。

首先,需要你的函数身体缩进 - 记住,Python是压痕敏感:

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看起来并不正确。这是一个字典,其中第一项的关键是00是一个整数,所以没问题),但什么是hardhard()是对函数的引用,但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" 

全部放在一起:

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 ")) 

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: 
    print("invalid") 
相关问题