Grayson Ho
Grayson Ho

Reputation: 45

User input is not matched by if statements

I have the following code, the logic is that the program will prompt the user to input a digit, and the program will do something dependent on the user's choice. However, the following code doesn't return the desired result. I wonder why and how should I modify it.

while True:
    selection = input("Input")
    if selection == 1:
        print(1)
    elif selection == 2:
        print(2)
    else:
        print("NO")

Upvotes: 0

Views: 39

Answers (1)

Ursus
Ursus

Reputation: 30056

You're almost there. The issue is that what you take from standard input is always a string. Let's make it an integer

while True:
    selection = int(input("Input")) # this line
    if selection == 1:
        print(1)
    elif selection == 2:
        print(2)
    else:
        print("NO")

Upvotes: 3

Related Questions