2014-10-11 98 views
0

對不起,我是初學者。但是,像如果我有:測試輸入是字符串而不是數字嗎?

x = eval(input('Enter a value for x: ')) 

怎樣讓這個如果人輸入一個字符串,而不是數字,將打印"Enter a number"而不是讓錯誤的。某些類型的if語句,其中:

if x == str(): 
    print('Please enter a number') 

else: 
    print('blah blah blah') 
+0

更好地貼近目標將是:我如何檢查是否一個字符串是Python中的號碼是多少?(http://stackoverflow.com/questions/354038/how-do-i - 檢查,如果一個字符串是一個數字在python)或 [你如何檢查一個字符串是否只包含數字 - 蟒蛇](http://stackoverflow.com/questions/21388541/how- DO-您檢查-IF-A-字符串包含專用號碼的Python) – bummi 2014-10-11 22:30:16

回答

0

這聽起來像你正在尋找str.isdigit

>>> x = input(':') 
:abcd 
>>> x.isdigit() # Returns False because x contains non-digit characters 
False 
>>> x= input(':') 
:123 
>>> x.isdigit() # Returns True because x contains only digits 
True 
>>> 

在你的代碼,這將是:

if not x.isdigit(): 
    print('Please enter a number') 
else: 
    print('blah blah blah') 

在一個注意,你應該避免使用eval(input(...)),因爲它可以用來執行任意表達式。換句話說,它通常是一個安全漏洞,因此被大多數Python程序員認爲是不好的做法。參考:

Is using eval in Python a bad practice?

相關問題