2017-04-14 90 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") 
相关问题