python int( ) function

前端 未结 5 1787
逝去的感伤
逝去的感伤 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:36

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

    0 讨论(0)
  • 2021-02-15 13:38
    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.

    0 讨论(0)
  • 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?
    
    0 讨论(0)
  • 2021-02-15 13:47

    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

    0 讨论(0)
  • 2021-02-15 13:59

    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.

    0 讨论(0)
提交回复
热议问题