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

守給你的承諾、 提交于 2019-12-02 14:10:19

问题


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 statement doesn't work. The comparison is always False.

Start = input()
if Start == 3:
     print ("successful")

回答1:


Python 3 input function returns string.

Try like this

start = input("-->: ")
if start == "3":
    print("successful")



回答2:


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 <class 'str'>
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



回答3:


You can also try this as an alternative:

Adding int will convert the variable to int data type.

input = int(raw_input("Enter a num: "))
if input == 3:
   print "Successful"



回答4:


you should check your tabs (I recomend you to use four spaces, not regular tabs and not to mix them)

start = 0
start = input("-->:")
if start == "3":
    print("Success")


来源:https://stackoverflow.com/questions/32926559/numeric-comparison-with-user-input-always-produces-not-equal-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!