Python int () function

The code below shows an error if a decimal (e.g. 49.9) is sent to the next variable. Could you tell me why? Why int() convert it to 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 do not use int() or float() and just use:

 how_much=next 

then it moves to "else" even if I enter it as 49.8 .

+7
source share
5 answers

As mentioned in other answers, an int operation will fail if a string input is not converted to an int (e.g. float or characters). What you can do is use a small helper method to try and interpret the line 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, this will take a string and try to convert it to int, then float and otherwise return the string. This is a more general example of considering convertible types. It would be a mistake for your value to be returned from this function, which is still the string that you would like to tell the user and request a new input.

There may be an option 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? 
+11
source

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

+4
source

Integers ( int for short) are numbers that you count with 0, 1, 2, 3 ... and their negative copies ... -3, -2, -1 those that don't have a decimal part.

So, once you enter a decimal point, you are not dealing with integers. You are dealing with rational numbers. A Python float or decimal is what you want to represent or approximate these numbers.

You can use a language that will automatically do this for you (Php). However, Python has an explicit preference for making code explicit and implicit .

+2
source
 import random import time import sys while True: x=random.randint(1,100) print('''Guess my number--it 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 build the str() , which converts it to an inoperable number. Then I int() an integer to make it a working number. I just tested your problem on my IDLE GUI and it said 49.8 <50.

+2
source

Use float () instead of int () so your program can handle decimal points. Also, do not use next , as this is a built-in Python function, next () .

Nor do you indicate how the import sys message was sent, and the definition for dead

+1
source

All Articles