2017-04-14 91 views
-2

這裏是我的代碼:爲什麼input()總是返回一個字符串?

age = input("How old are you?: ") 
print (age) 
print (type(age)) 

結果:

How old are you?: 35
35
class 'str' <<--- This is problem!

但是,如果我用..

age = int(input("How old are you?: ")) 
print (age) 
print (type(age)) 

,進入 「亞歷克斯」

How old are you?: alex
Traceback (most recent call last):
File "/Users/kanapatgreenigorn/Desktop/test.py", line 1, in age = int(input("How old are you?: ")) ValueError: invalid literal for int() with base 10: 'alex'

+0

這是驗證的用武之地,如果你問一個年齡,你*希望*一個數字。不要投入輸入,或將其放入try/expect塊,並在類型不是預期的時候返回錯誤。 –

+2

這不是一個有用的東西,而不是一個問題?你想考慮「alex」這個問題的有效答案:「你多大了?」 – trincot

+2

可能要檢出http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – ToothlessRebel

回答

1

如果你想讓它迴歸嚴格g然後我認爲它默認是這樣做的,但如果你希望它像數字或整數一樣返回,那麼你可以把int(在輸入前面)。你把'亞歷克斯'和它之所以出現錯誤是因爲'亞歷克斯'是一個字符串。不是整數(即int)

1

該字符串是輸入的默認值。有兩個選項可以改變它。

sample = input("Sample") 
sample = int(sample) 

sample = int(input("Sample") 
相關問題