这里是我的代码:为什么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'
这是验证的用武之地,如果你问一个年龄,你*希望*一个数字。不要投入输入,或将其放入try/expect块,并在类型不是预期的时候返回错误。 –
这不是一个有用的东西,而不是一个问题?你想考虑“alex”这个问题的有效答案:“你多大了?” – trincot
可能要检出http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – ToothlessRebel