Sometimes get a ValueError from passing a float to int() method, but not always

流过昼夜 提交于 2019-12-11 05:36:03

问题


Python newbie here. I've been messing around with flow control and have come across a situation I don't quite understand related to exceptions.

In the following code I want the user to enter an integer in a given range and, in the case of non-compliance, keep asking them until they give a valid value:

while True:
    try:
        x = int(raw_input("Pick an integer between 2 and 9. "))
    except ValueError:
        print "Please enter an integer!"
        continue
    else:
        if 2 <= x <= 9:
            print("Your number is {0}.").format(x)
            break
        else:
            print "That's not between 2 and 9!"
            continue

As far as I can tell, this code works exactly as I want it to. I've thrown every other type of input I can think of at it and it only lets you exit the loop when an integer from 2-9 is entered. Not even floats are accepted.

My question is, given that int() can be successfully called on floats,

>>> int(2.1)
2

why does this try/except construct raise the exception when the input is a float? If I run the code without the try/except statements and enter anything other than an integer, it throws an error and exits.

I'm running python 2.7 from windows powershell.


回答1:


This is because raw_input returns a string.

Under the hood, when you call int, it actually calls an objects object.__int__() method. This is different from object to object.
For a float, this truncates a value (Rounds towards 0).
On a string, it tries to parse an int according to https://docs.python.org/3/reference/lexical_analysis.html#integer-literals (Which can't have a .).




回答2:


The issue here is that you are calling int() on a string that could potentially contain a period. To fix this I would recommend you change the int() to float(). This should fix your problem

x = float(raw_input("Pick an integer between 2 and 9. "))



回答3:


Not sure what version of Python you are using but if it is Python 3.0 or above you might want to carefully check the print statements in the following clips

except ValueError:
    print "Please enter an integer!"

else:
    print "That's not between 2 and 9!"

they are not formatted for 3.0 but will probably work ok if you use version 2.x I think the other answers covered your original problem adequately so I will defer to them.. they know that area better than I. Good Luck,
Poe



来源:https://stackoverflow.com/questions/40640780/sometimes-get-a-valueerror-from-passing-a-float-to-int-method-but-not-always

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!