Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between python2 and python3 - int() and input()

I wrote below python code. And I found that python2 and python3 has totally difference running result for input of 1.1. Why is there such difference between python2 and python3? For me, int(1.1) should be 1, then position is valid index 1 within range 0,1,2. So can you please explain why python3 has such result?

s=[1,2,3]
while True:
  value=input()
  print('value:',value)
  try:
    position=int(value)
    print('position',position)
    print('result',s[position])
  except IndexError as err:
    print('out of index')
  except Exception as other:
    print('sth else broke',other)


$ python temp.py
1.1
('value:', 1.1)
('position', 1)
('result', 2)


$ python3 temp.py
1.1
value: 1.1
sth else broke invalid literal for int() with base 10: '1.1'
like image 679
Zii Avatar asked Jun 10 '16 04:06

Zii


2 Answers

The issue is intput() converts the value to an number for python2 and a string for python 3.

int() of a non int string returns an error, while int() of a float does not.

Convert the input value to a float using either:

value=float(input())

or, better (safer) yet

position=int(float(value))

EDIT: And best of all, avoid using input since it uses an eval and is unsafe. As Tadhg suggested, the best solution is:

#At the top:
try:
    #in python 2 raw_input exists, so use that
    input = raw_input
except NameError:
    #in python 3 we hit this case and input is already raw_input
    pass

...
    try:
        #then inside your try block, convert the string input to an number(float) before going to an int
        position = int(float(value))

From the Python Docs:

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

like image 166
Charles L. Avatar answered Oct 04 '22 03:10

Charles L.


Please check the Python 3 release notes. In particular, the input() function (which is considered dangerous) was removed. In its stead, the safer raw_input() function was renamed to input().

In order to write code for both versions, only rely on raw_input(). Add the following to the top of your file:

try:
    # replace unsafe input() function
    input = raw_input
except NameError:
    # raw_input doesn't exist, the code is probably
    # running on Python 3 where input() is safe
    pass

BTW: Your example code isn't minimal. If you had further reduced the code, you would have found that in one case int() operates on a float and in the other on a str which would then have brought you to the different things that input() returns. A look at the docs would then have given you the final hint.

like image 36
Ulrich Eckhardt Avatar answered Oct 04 '22 03:10

Ulrich Eckhardt