简体   繁体   中英

Python INPUT gives wrong result

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)

In python 2, starting a number with 0 marks it as octal (base 8).

12345 oct = 5349 dec

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM