Butters Butters - 1 year ago 66
Python Question

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

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

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

Output for any correct choice I pick:

"You are done picking up a flavor, pay now

wrong choice"

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download