python int( ) function

前端 未结 5 1791
逝去的感伤
逝去的感伤 2021-02-15 13:06

The code below shows error if a decimal (eg. 49.9) is sent to next variable. Can you please tell me why? Why does int() converts it into an in

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-15 13:43

    As the other answers have mentioned, the int operation will crash if the string input is not convertible to an int (such as a float or characters). What you can do is use a little helper method to try and interpret the string for you:

    def interpret_string(s):
        if not isinstance(s, basestring):
            return str(s)
        if s.isdigit():
            return int(s)
        try:
            return float(s)
        except ValueError:
            return s
    

    So it will take a string and try to convert it to int, then float, and otherwise return string. This is more just a general example of looking at the convertible types. It would be an error for your value to come back out of that function still being a string, which you would then want to report to the user and ask for new input.

    Maybe a variation that returns None if its neither float nor int:

    def interpret_string(s):
        if not isinstance(s, basestring):
            return None
        if s.isdigit():
            return int(s)
        try:
            return float(s)
        except ValueError:
            return None
    
    val=raw_input("> ")
    how_much=interpret_string(val)
    if how_much is None:
        # ask for more input? Error?
    

提交回复
热议问题