Samrath
Samrath

Reputation: 39

If statement is not working in python in python 3.6

    a = input('10+1: ')
if a == 11:
    print("correct")
else:
    print('wrong')

The code above is not working in my program.

Its giving me an output of something like this:

10+1: 11
wrong

Process finished with exit code 0

Upvotes: 0

Views: 79

Answers (3)

Elephant
Elephant

Reputation: 456

An alternative solution to those in the previous answers would be to convert the input to an integer (whole number 1, 2, 3, etc.) before you compare it this can be done with the int() keyword:

a = int(input("10+1="))

if a == 11:
    print("Correct")
else:
    print("Incorrect")

This method will make your code more readable and will also raise a ValueError should the user attempt to enter something which is not a number. This is will be usful later on when you wish to make sure only specific inputs are allowed. Input validation in your example would be:

while True:
    try:
        a = int(input("10+1="))
        break
    except ValueError:
        print("Sorry that isn't a valid input!")
        pass

if a == 11:
    print("Correct")
else:
    print("Incorrect")

I may have gone a bit beyond scope with my answer but I hope this helps

Upvotes: 1

Sudhanshu Joshi
Sudhanshu Joshi

Reputation: 13

You are comparing a string '11' with an integer 11 and hence getting the output as wrong. Try comparing a == '11' and it should give your desired output.

Upvotes: 0

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

Comparision like a == 11 is between a (input string) and 11 (number).

To notate number as string add quotes around it like that: '11'.

Change to a == '11': a (input string) and '11' (string).

And it shall work like magic:

a = input('10+1: ')
# Compare to string '11'
if a == '11':
    print("correct")
else:
    print('wrong')

Example Run:

10+1: 11
correct

Upvotes: 1

Related Questions