Butters Butters - 3 months ago 25
Python Question

if-if-else and if-elif-else statements

Why is the 'else' statement getting printed even if a correct choice is picked?

ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
print"Chocolate"
if ch=='3':
print"Strawberry"
if ch=='4':
print"Kiwi"
if ch=='5':
print"orange"
if ch=='6':
print"mango"
if ch=='7':
print"pineapple"
if ch=='8':
print"grapes"
print"You are done picking up a flavor, pay now"
if ans=='n':
print"Good, you can go!"
else:
print"wrong choice"


I am getting for any correct choice I pick:

"You are done picking up a flavor, pay now

wrong choice"

Answer

Because the if-statement checking "y" and the second if-statement checking "n" are two different. The else is only connected to the second if-statement with the "n"-check. You want to have the outermost statements like

if "y":
    ....
elif "n":
    ....
else:
    ....