2017-10-11 50 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")