How do I get around this annoying error message? (Python 3.6.1)

This question already has an answer here:

  • How do I parse a string to a float or int in Python? 22 answers

  • Change your first line to

    usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
    

    As you had it, usernum is a string value, since input() always returns strings in Python 3.x, and you were trying to compare it to integers. So convert it to an integer first. I did this by surrounding the input call with an int() typecast.

    Note that this will raise an error if the user types in something other than an integer. This can be dealt with by exception handling, which is probably beyond you right now.


    Try:

    usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
    if usernum < 0:
        print("Your number is negative.")
    if usernum > 0:
        print("Your number is positive.")
    if usernum == 0:
        print("Your number is zero.")
    

    input(...) creates strings, so you need to make that string an integer by making it go through int(...) . In addition I'd suggest switching you're ifs into if, elif and else:

    usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
    if usernum < 0:
        print("Your number is negative.")
    elif usernum > 0:
        print("Your number is positive.")
    else:
        print("Your number is zero.")
    

    It's not a big deal, but this way you're only executing code you actually need. So, if usernum is less than 0 then the next clauses aren't evaluated. Finally, you could consider adding user input error correction:

    usernum = None
    while usernum is None:
        try:
            usernum = int(input('Enter a number, Ill determine if its pos, neg, OR Zero.'))
        except ValueError as ex:
            print("You didn't enter an integer. Please try again.")
    if usernum < 0:
        print("Your number is negative.")
    if usernum > 0:
        print("Your number is positive.")
    if usernum == 0:
        print("Your number is zero.")
    
    链接地址: http://www.djcxy.com/p/48436.html

    上一篇: 转换为浮动分割,然后转换回来

    下一篇: 我如何解决这个恼人的错误信息? (Python 3.6.1)