2014-09-29 53 views
-3

我有這樣的代碼:的Python:輸入驗證不工作

#counting the number down to zero. 
x = int(x) 
while x>=0: 
    print x 
    x -= 1 

#if the user asks for a number below zero print this: 
if x<0: 
    print "You cant countdown number below zero." 

#if the user asks for something else than a number print this: 
else: 
    print "only insert numbers." 

代碼本身是很基本的,只是算一個隨機數下來,直到爲零。 唯一的問題是,我的其他塊不工作,我做了別人塊,當有人寫一個字/字母而不是數字。任何人都可以解決這個問題嗎? :)

編輯: 錯誤,我得到的是:

ValueError: invalid literal for int() with base 10: 'ha' 
+0

你應該在你的問題中說明它是如何工作的。出了什麼問題?你得到什麼樣的輸出?你想得到什麼樣的輸出? – 2014-09-29 15:12:15

+0

您確定您使用的是正確的表格嗎? – castarco 2014-09-29 15:12:30

+3

'else'部分將永遠不會執行,因爲代碼會將數字減去直到變爲負數。 – falsetru 2014-09-29 15:12:45

回答

2

你應該使用不同的方法。首先驗證輸入:

try: 
    x = int(x) 
except ValueError: 
    print "only insert numbers" 
    #return from function, or exit the program, or whatever you want 

while x >= 0: 
    print x 
    x -= 1 

if x < 0: 
    print "You cant countdown number below zero." 
+0

Python註釋是'#',而不是''''。 – SethMMorton 2014-09-29 15:49:17

+0

@SethMMorton對,謝謝:) – BartoszKP 2014-09-29 16:03:01