Butters Butters - 2 months ago 16
Python Question

if-if-else and if-elif-else statement

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"


Output for any correct choice I pick:

"You are done picking up a flavor, pay now

wrong choice"

Answer

You have two conditions not one.

  1. The first condition checks ans against 'y'.

    If ans is 'y' the user gets to input an integer 1-8 and the appropriate string will be printed to the console. Processing then moves to the second condition (#2).

    If ans is not 'y' then the user dose not give any input and processing moves to the second condition (#2).

  2. The second condition checks ans against 'n'.

    If ans is 'n' then "Good, you can go!" is printed to the console and processing continues skipping the else block.

    If ans is not 'n' (which would be the case that user entered 'y') then the else block is executed printing "wrong choice" to the console.

What is happening is you have your logic setup that any input other than 'n' will print "wrong choice" eventually. You want a single decision from the users initial input. Currently your logic makes two.

Use the if elif else construct.