正如@paidhima 所说,input 函数将始终在 python 3.x 中返回一个字符串。
示例:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> var = input("var: ")
var: 12
>>> var
'12'
>>>type(var)
<class 'str'>
>>>
如果我执行以下操作:
>>> var = input("var: ")
var: aa
>>> var
'aa'
>>> type(var)
<class 'str'>
>>>
它们都是字符串,因为让程序决定它是否会给我们一个字符串或整数不是一个好主意,我们希望我们在程序中构建的逻辑来处理它。
在 python3.x 中,你的例子是行不通的,但你可以试试这个:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
var = input('var: ')
# we try to conver the string that we got
# in to an intiger
try:
# if we can convert it we store it in the same
# variable
var = int(var)
except ValueError:
# if we can't convert we will get 'ValueError'
# and we just pass it
pass
# now we can use your code
if isinstance(var, str):
print("var = word")
else:
print("var = number")
# notice the use of 'print()', in python3 the 'print is no longer
# a statement, it's a function
现在回到使用 python2.x 的脚本。
正如我上面所说,使用函数input 不是一个好习惯,您可以使用raw_input,它在python2.x 中的工作方式与python3.x 中的input 相同。
我要再说一遍,因为我不想让你感到困惑:
Python2.x:
input
# evaluates the expression(the input ) and returns what
# can make from it, if it can make an integer it will make one
# if not it will keep it as a string
raw_input
# it will always return the expression(the input ) as a string for
# security reasons and compatibility reasons
Python3.x
input
# it will always return the expression(the input ) as a string for
# security reasons and compatibility reasons
注意,在python3.x中没有raw_input。
您的代码应该可以正常工作,在 python2.x 中,确保您使用正确的 python,我希望这对您有所帮助。