2012-02-15 75 views
0

我正在使用Python的Hangman遊戲,我需要用戶驗證輸入,我曾嘗試過,但我不知道爲什麼它不工作。Hang子手用戶輸入驗證

我的任務是讓「錯誤」消息爲1.空輸入,2.非整數,非空輸入,3.索引超出範圍輸入。通過索引超出範圍,我的意思是我要求用戶輸入一個從0到9的整數,以從程序中的列表中選擇一個單詞。

def getLetterFromUser(totalGuesses): 

    while True: 
     userInput = input("\nPlease enter the letter you guess:") 
     if userInput == '' or userInput == ' ': 
      print("Empty input.") 
     elif userInput in totalGuesses: 
      print("You have already guessed that letter. Try again.") 
     elif userInput not in 'abcdefghijklmnopqrstuvwxyz': 
      print("You must enter an alphabetic character.") 
     else: 
      return userInput 

爲了清楚起見,隨後對getLetterFromUser的調用位於while循環中,以便它重複檢查這些條件。

編輯:我拿出什麼不屬於。謝謝。然而,我的問題是,它仍然告訴我輸入不是在字母表中,當它是。輸入的長度(單個字符)是2,除非它計算空字符,否則這是沒有意義的。

+1

您遇到什麼問題或錯誤? – YXD 2012-02-15 00:44:10

+0

爲什麼你要讓用戶選擇這個詞,爲什麼在「猜字母」提示循環中有這個選項? – Edwin 2012-02-15 00:46:41

+0

@Edwin我很抱歉,如果在不知不覺中粘貼在那裏。無視它,因爲它在別處。 對其他人:我收到的錯誤是,不管我輸入什麼,它都是不對的。它通常會說「你必須輸入一個字母字符」,我會這樣做。另外,我很好奇,所以我檢查了輸入的長度(單個字符)及其總是2.我不知道爲什麼。 – trainreq 2012-02-15 00:48:57

回答

1

你的問題是一些驗證規則應該優先於其他驗證規則。例如,如果userInput是空字符串,那麼您希望userInput < 0返回什麼?如果它不是空的,但也不是一個數字呢?

想想應該先檢查哪些條件。

"123".isdigit() # checks if a string represents an integer number 
" 123 ".strip() # removes whitespaces at the beginning and end. 
len("") # returns the length of a string 
int("123") # converts a string to an int 
0

這裏有兩件事情入手:

什麼是線

userInput = userInput.lower() 

的目的,如果你假設 你可能想了解和使用的一些功能userInput是一個整數.. 你應該嘗試userInput = int(userInput)。整數沒有.lower()方法。

下一行

if 0 > userInput or userInput > 9 

這個假設userInput是一個整數(你是比較爲0和9,而不是 「0」 和 「9」)

以下看起來更好:

if not 0<=userInput<=9 
0

你說你想要整數的答案,但你不是把輸入轉換爲一個整型,但是你說如果輸入不在字母表中,它應該返回一個錯誤信息。你要求兩件不同的事情。

你想讓用戶輸入一個整數或字符嗎?

0

這可能會幫助您:

>>> int(" 33 \n") 
33 
>>> int(" 33a asfd") 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
ValueError: invalid literal for int() with base 10: '33a asfd' 
>>> try: 
...  int("adsf") 
... except ValueError: 
...  print "invalid input is not a number" 
...  
invalid input is not a number 
+0

我必須問,你如何在CLI中輸入多行命令? – trainreq 2012-02-15 01:00:33

+0

我在pyscripter裏面是一個python的IDE。您只需按Enter即可轉到下一行。 http://stackoverflow.com/questions/81584/what-ide-to-use-for-python – 2012-02-15 01:17:16