Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python int( ) function

Tags:

python

int

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 integer?

next=raw_input("> ")
how_much = int(next)
if how_much < 50:
    print"Nice, you're not greedy, you win"
    exit(0)
else:
    dead("You greedy bastard!")

If I dont use int() or float() and just use:

how_much=next

then it moves to "else" even if I give the input as 49.8.

like image 906
Shubham Agrawal Avatar asked Aug 18 '12 17:08

Shubham Agrawal


1 Answers

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?
like image 105
jdi Avatar answered Nov 04 '22 03:11

jdi