2010-12-10 53 views
0

我使用Python 2.6.6蟒蛇給選項,如果用戶輸入字符串

我有這樣的代碼:

height = 20 
width = 10 
x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ') 
while x < (width + 1) or x > 20: 
    print 'That option is not valid' 
    x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ') 

如果用戶只輸入數字時,一切工作正常,但如果用戶進行錯誤和類型,例如q,它提供了:

NameError: name 'q' is not defined

我想,如果用戶插入一個字符串,while循環踢,給用戶:該選項無效.... 如何CA ñ我解決這個問題,而不使用raw_input,因爲寬度和高度我想將tham視爲數字?

問候,

Favolas

編輯 繼丹尼爾的建議,我修改我的代碼如下:

height = 20 
width = 10 
x = raw_input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ') 
x = int(x) 
while x < (width + 1) or x > 20: 
    print 'That option is not valid' 
    x = raw_input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ') 
    x = int(x) 

如果用戶只輸入INT代碼按計劃工作,但它從用戶錯誤不安全。如果用戶犯了錯誤類型的「Q」它給了這個錯誤:

ValueError: invalid literal for int() with base 10: 'q' 

我明白爲什麼,但我該如何解決這個問題?

問候,

Favolas

回答

5

必須使用raw_input代替input在Python 2.x版本input假定用戶正在輸入要評估的有效Python。你最好的選擇是採取字符串輸入,然後根據需要進行轉換。在這種情況下,您需要嘗試使用int進行轉換。

正如一個提醒,from the documentation

input([prompt])

Equivalent to eval(raw_input(prompt)) .

Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.)

+0

嗨丹尼爾。感謝您的回答。遵循你的建議,但仍有一些問題。我編輯了我的原始問題,請看看它。 Favolas – Favolas 2010-12-11 11:09:34

+0

@Favolas,從代碼中移除'x = int(x)'。然後它將與'raw_input'完美配合。 – systemovich 2010-12-11 11:34:34

+0

嗨傑弗裏。謝謝,但如果我刪除這兩個x = int(x)如果我運行這個插入12(它的有效)它進入while循環。它解決了用戶插入字符串但在另一個字符串上的問題,並停止使用int – Favolas 2010-12-11 12:06:27