2014-11-06 37 views
-1

例如在這個程序中,我使用tryexcept來嘗試驗證它,但它不起作用;有任何想法嗎?我想確保輸入不是一個字符串。如何驗證輸入是否只有Python中的數字?

userGuess = int(input("%s %s %s = ?\n" % (num1, op, num2))) 
try: 
    validation = int(userGuess) 
except ValueError: 
    print("You have not entered a number!") 
+0

放用戶猜測...刪除驗證線......把它們都放在一個while循環 – 2014-11-06 17:11:54

+0

你怎麼說不起作用?你期望它做什麼? – Kasramvd 2014-11-06 17:13:41

+0

爲什麼不使用'isdigit()' – Beginner 2014-11-06 17:16:10

回答

0

現在它應該工作

你越來越異常的嘗試之前,你已經嘗試興田輸入轉換成int類型。

userGuess = input("%s %s %s = ?\n" % (num1, op, num2)) 
try: 
    validation = int(userGuess) 
except ValueError: 
    print("You have not entered a number!") 

但通常的做法更像是這樣的:

在try
try: 
    userGuess = int(input('%s %s %s = ?\n' % (num1, op, num2))) 
except ValueError: 
    raise Exception('You have not entered a number!') 
+2

我不明白你的慣例。沒有必要導入'Exception',並且由於'input'返回一個字符串,我不確定什麼會觸發'ValueError'。 – DSM 2014-11-06 17:19:17

+0

讓我再試一次。你的'from exception import Exception'行不做任何事情。你原來的代碼缺少'int',所以它不可能引發異常,這是我所困惑的。 OP很可能使用Python 3,因爲這是OP如何標記問題。 – DSM 2014-11-06 17:30:05

+0

我不是那個低估了你的人,並且'從異常import異常'是通常的做法當然是不正確的。 – DSM 2014-11-06 17:42:28