[Tutor] Else and If

Peter Otten __peter__ at web.de
Tue Sep 9 10:52:34 CEST 2014


Mimi Ou Yang wrote:

> print ("Quiz TIME!!!")
> ready = input("Are you ready?")

> if (ready in ("yes","YES","Yes")):
>     print ("Alrighty")

> if (ready in ("no","NO","No")):
>     print ("Too bad so sad. You're obligated to do it.")
> else:
>     print ("OK (sarcasm)")

> When I write yes or YES or Yes or no or No or NO in the ready input it
> always print out Alrighty and OK (sarcasm) can you tell me what is the
> mistake in my code?

Assuming ready is "Yes" the following expression evaluates to True, the if-
suite is executed and "Alrighty" is printed

> if (ready in ("yes","YES","Yes")):
>     print ("Alrighty")


Then the following expression evaluates to False, thus the if-suite is not 
executed, but the else-suite is executed and thus prints "OK (sarcasm)"

> if (ready in ("no","NO","No")):

The first 

if condition1:
    suite1

and the second

if condition2:
   suite2
else:
   suite3

are completely separate. You can change by nesting them:

if condition1:
    suite1
else:
    if condition2:
        suite2
    else:
        suite3

That way the second condition is only evaluated when the first condition is 
False. 

While this works there is a better option: put all conditions into a single 
if ... elif... else:

if condition1:
    suite1
elif condition2:
    suite2
else: # neither cond1 nor cond2 are met
    suite3

Taking your example:

if (ready in ("yes","YES","Yes")):
    print("Alrighty")
elif (ready in ("no","NO","No")):
    print("Too bad so sad. You're obligated to do it.")
else:
    print("OK (sarcasm)")

By the way, the parens around the condition are superfluous, and you may 
want to allow all spellings of "yes" (like "YEs" and "yEs") and "no", so

ready = ready.lower() # or ready.casefold()
if ready == "yes":
    print("Alrighty")
elif ready == "no":
    print("Too bad so sad. You're obligated to do it.")
else:
    print("OK (sarcasm)")

The number of `elif`s is not limited -- if you like you can insert a

elif ready == "maybe tomorrow":
    ...





More information about the Tutor mailing list