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

前端 未结 2 2081
别那么骄傲
别那么骄傲 2021-01-18 10:23

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 pyth

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 10:59

    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()).

提交回复
热议问题