Pro525
Pro525

Reputation: 7

Why does python write code from else in if?

I have this python source code:

while True:
    answer = input("\nApple or Nokia?")
    if answer == 'Apple':
        print("Nice, you have Apple!")

    if answer == 'Nokia':
        print("Nice, you have Nokia!")

    else:
        print("I do not understand.")

But when I run it and write Apple, the python says:

Apple or Nokia?Apple
Nice, you have Apple!
I do not understand.

Apple or Nokia?

I don't know why python writes "I do not understand."

Upvotes: 0

Views: 28

Answers (1)

Daweo
Daweo

Reputation: 36828

You have typo:

if answer == 'Nokia':

should be

elif answer == 'Nokia':

your original code is equivalent to

while True:
    answer = input("\nApple or Nokia?")
    if answer == 'Apple':
        print("Nice, you have Apple!")
    else:
        pass  # do nothing

    if answer == 'Nokia':
        print("Nice, you have Nokia!")

    else:
        print("I do not understand.")

Upvotes: 1

Related Questions