Reputation: 459
I am trying to enter numbers with input statement, everything is fine, the only problem is when i start the numbers with '0'. It gives wrong result. Can someone explain me what exactly happens and why it gives wrong result.
Here is a small example:
>>> a = input("> ")
> 12345
>>> a
12345
>>> a = input("> ")
> 012345
>>> a
5349
>>> print a
5349
>>> if a == 012345: print "matched"
matched
I am not understanding this. Thanks for any help! (Windows XP, Python 2.7.3)
Upvotes: 2
Views: 148
Reputation: 32300
In Python, a number that starts with 0
is recognised as in base 8 (octal). You will notice that a number starting with 0
that has an 8
or 9
will raise an exception.
As a side note, you shouldn't use input()
in Python 2, as it evaluates the input. Use raw_input()
instead, and then convert that to an int
. If you want to get rid of the base 8 problem, then pass 10
as the second argument to int()
(the base):
a = raw_input('> ')
try:
a = int(a, 10)
except ValueError:
#do something
print a
Upvotes: 2
Reputation: 12174
In python 2, starting a number with 0
marks it as octal (base 8).
12345 oct = 5349 dec
Upvotes: 5
Reputation: 2958
input
evaluates whatever is read from the stream - so it is read an a number and returned as an integer.
It sounds like you are looking for raw_input
, which gives whatever was read off the stream as a string
(so input('> ')
is the same as eval(raw_input('> '))
)
As @Tim said, the integer value seems unexpected because python is interpreting the value as an octal.
Upvotes: 0