Numeric comparison with user input always produces “not equal” result

后端 未结 4 1677
感情败类
感情败类 2021-01-24 17:25

I want to get a number input by the user via input() and compare it with a specific value, i.e., 3.

However, I have the impression my if statem

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-24 17:44

    Some things you could do on your own to get to the root of the problem:

    Ways to get to know the type of the object:

    print(type(start)) # prints 
    print(repr(start)) # prints '3'
    

    Unlike Python 2.x, the function input() returns a string object (and does not blindly evaluate the expression provided by the user):

    input([prompt]):

    If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. [...]

    This should give an idea how to fix it (compare numbers to numbers).

    For further reading:

    • https://docs.python.org/3/library/functions.html#input
    • https://docs.python.org/3/library/functions.html#type
    • https://docs.python.org/3/library/functions.html#repr
    • How does Python compare string and int?
    • Asking the user for input until they give a valid response

提交回复
热议问题