1
ab=0
while ab==0:
    ab=input("enter here:")
    if ab==1:
        print("print this ab==1")
    elif ab==2:
        print("print this ab==2")
    elif ab==3:
        print("print this ab==3")
    elif ab==4:
        print("print this ab==4")
    else:
        print("try again")

result:

enter here:2

try again

When I take input as a 1,2,3,4 or anything, it returns else condition (prints "try again") And loop ends here

output:

enter here:4

try again

and loop is terminated

when my input is 1/2/3/4, I expect corresponding elif condition, but the actual output is else condition and after the result loop is terminated

4 Answers 4

1

Python treats the input as a string. So either compare those numbers as a string or convert your input into integer. You can try this

ab = int(input("enter here"))
Sign up to request clarification or add additional context in comments.

Comments

0

Option 1: You need to cast the value returned by your input() call. Do that using: int(input())

Option 2: You can compare strings instead of integers: if ab=="1"

But don't do both, choose one option or the other. The first one is good if you expect to get values that can actually be cast into integers. Therefore, if you choose that option you should check your input value before casting.

Comments

0

you can also compare the input to a string instead of converting it to int.

Eg.

...
elif ab=="1":
    print("print this ab==1")
...

Comments

0

By default Python's input() method returns a string. You have to treat it this way by either converting your input to int as:

ab = int(input(“enter int here”))

Or perform all comparisons in str format which works if you want to test it for inputs other than just numbers:

ab=input("enter string here:")
if ab=='1':
    print("print this ab==1")
elif ab=='2':
    print("print this ab==2")
elif ab=='3':
    print("print this ab==3")
elif ab=='4':
    print("print this ab==4")
else:
    print("try again")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.