Home > Software design >  This relates to Multiple if statements in python
This relates to Multiple if statements in python

Time:10-29

I am a beginner level python student. This is a code challenge in a udemy program related to Multiple if statements

add_pepperoni ="Y"
extra_cheese="Y"

pizza_price =15
if add_pepperoni =="Y":
    pizza_price  =2
    if extra_cheese =="Y":
        pizza_price  =1 
    else:
        print(f"final price is{pizza_price}")         
else:
    print(pizza_price)

this code doesn't work.I cant figure out why. here the normal pizza price is $15. but if pepperoni is added final price should become $17.if extra cheese is added final price should be 18.

CodePudding user response:

I assume you want to be able to print the correct price, regardless of the combinations chosen by the customer: pepperoni, no extra cheese; no pepperoni, extra cheese, etc. The snag in your code (and mxthng's) is that the 'extra_cheese' 'if' statement has been nested in the 'add_pepperoni' 'if' statement. When nesting statements like this, if the first 'if' statement evaluates to False (in this case, anything other than "Y"), nothing else in that code block executes, including 'if extra_cheese ...'. Remember that 'if' statements can be used to test conditions without the addition of an 'else' statement. This should give you the desired result (again, assuming my first assumption above is correct). Cheers!

add_pepperoni  = "Y"
extra_cheese = "Y"

pizza_price = 15
if add_pepperoni == "Y":
    pizza_price  = 2
if extra_cheese == "Y":
    pizza_price  = 1

print(f"final price is {pizza_price}")   

CodePudding user response:

Well actually it worked. Here it go inside the first if and the pizza_price was 17$, then it go to the second if and it become 18$. So it doesn't go to 2 'else'. If u mean to print the final pizza_price just remove the second else or remove both 2 else. It will look likes this:

add_pepperoni ="Y"
extra_cheese="Y"

pizza_price =15
if add_pepperoni =="Y":
    pizza_price  = 2
    if extra_cheese =="Y":
        pizza_price  = 1
print(f"final price is{pizza_price}")         
  • Related