8

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.

3
  • 2
    You probably want to say how_much = int(float(...)) or how_much = int(round(float(...))). Commented Aug 18, 2012 at 17:53
  • 2
    small side note: next is not a good choice for a var name, as there is a build in function next() since 2.6 in python Commented Nov 6, 2013 at 11:59
  • 1
    you are here because of this. learnpythonthehardway.org/book/ex35.html Commented May 4, 2015 at 16:01

5 Answers 5

12

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?
Sign up to request clarification or add additional context in comments.

7 Comments

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
Because you are comparing strings then: "49.8" < 50
I had a typo and forgot to put the None in that second one. Just fixed.
Bare except is evil. except ValueError would probably be a better idea.
@jdi: Anything can raise KeyboardInterrupt. The user can hit Ctrl+C at any time.
|
5

int() only works for strings that look like integers; it will fail for strings that look like floats. Use float() instead.

2 Comments

Why doesent int() converts the input into integer?
Because it can't be interpreted as an integer.
2

Integers (int for short) are the numbers you count with 0, 1, 2, 3 ... and their negative counterparts ... -3, -2, -1 the ones without the decimal part.

So once you introduce a decimal point, your not really dealing with integers. You're dealing with rational numbers. The Python float or decimal types are what you want to represent or approximate these numbers.

You may be used to a language that automatically does this for you(Php). Python, though, has an explicit preference for forcing code to be explicit instead implicit.

2 Comments

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
Well thats because how_much then becomes a string. I wouldn't expect that to even work.
2
import random
import time
import sys
while True:
    x=random.randint(1,100)
    print('''Guess my number--it's from 1 to 100.''')
    z=0
    while True:
        z=z+1
        xx=int(str(sys.stdin.readline()))
        if xx > x:
            print("Too High!")
        elif xx < x:
            print("Too Low!")
        elif xx==x:
            print("You Win!! You used %s guesses!"%(z))
            print()
            break
        else:
            break

in this, I first string the number str(), which converts it into an inoperable number. Then, I int() integerize it, to make it an operable number. I just tested your problem on my IDLE GUI, and it said that 49.8 < 50.

1 Comment

your code produce the right result but its way too long for that task.
1

Use float() in place of int() so that your program can handle decimal points. Also, don't use next as it's a built-in Python function, next().

Also you code as posted is missing import sys and the definition for dead

4 Comments

Why doesent int() converts the input into integer?
@ShubhamAgrawal It can't convert something with a decimal point to an int, it needs to get a string that looks like an int.
@ShubhamAgrawal Can you tell us your goal and why float() would not be an acceptable solution?
float() is an acceptable solution. If i font use either float() or int() then why doesent python recognise the input's type and check if its lesser or greater than 50?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.