As @paidhima said the input
function will always return a string in python 3.x.
Example:
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'>
>>>
If i do the following:
>>> var = input("var: ")
var: aa
>>> var
'aa'
>>> type(var)
<class 'str'>
>>>
They are both string because it is not a good idea to have the program decide if it's gonna give us a string or and integer, we want the logic that we build in the program to handle that.
In python3.x you example is not gonna work, but you can try this this:
#!/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
Now back to your script using python2.x.
As i said above it's not a good practice to use the function input
, you can use raw_input
that works the same in python2.x like input
in python3.x .
I'm gonna say it again because i don't want to confuse you :
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
Attention, in python3.x there is no raw_input
.
Your code should work just fine, in python2.x, make sure you use the right python, and i hope this helped you in a way or another.