Reputation: 1
print("Pizza price program\n")
size=input("\nWhich size pizza you want? S,L,M\n")
add_pepperoni=input("\nDo you want to add pepperoni to your pizza? Y/N\n ")
extra_cheese=input("\nDo you want to add extra chees on your pizza? Y/N\n")
prize=0
if((size=="S") or (size=="s")):
prize+=15
elif((size=="M") or (size=="m")):
prize+=20
elif((size=="L") or (size=="l")):
prize+=30
else:
print("\nWrong choice")
if((add_pepperoni=="Y") or (add_pepperoni=="y")):
if((size=="S") or (size=="s")):
prize+=2
elif((size=="M") or (size=="m") or (size=="L") or (size=="l")):
prize+=3
if((extra_cheese=="Y") or (extra_cheese=="y")):
prize+=1
print(f"\nAmount to be paid for your pizza is {prize}.Rs")
in the first if else block if I provide other than S,L,M the code is proceeding to next if block but I want it to print "Wrong choice" if input is other than S,L,M.
Upvotes: 0
Views: 146
Reputation: 1218
You should use a while loop to continually ask the user until they give a valid choice:
print("Pizza price program\n")
# Initialize the size variable to None
size = None
while size is None:
# Get user input and make it uppercase so we only have to check for uppercase characters
user_input = input("Which size pizza you want? S,L,M").upper()
# If input is in the valid options return it
if user_input in ['S', 'M', 'L']:
# If the size is a valid input, set the value
size = user_input
else:
# Otherwise leave the value of size as None and of invalid input
print("\nWrong choice")
# We now know the size must be one of 'S', 'M' or 'L' so:
prize=0
if size == "S":
prize+=15
elif size == "M":
prize+=20
else: # size must be "L" if it reaches this point so elif is not required
prize+=30
We can then apply this to the other inputs in your program, wrapping our repeated code in a well-named function:
def get_option(msg, valid_options):
while True:
# Get user input, make it uppercase and strip off any whitespace
user_input = input(msg).upper().strip()
# If input is in the valid options return it
if user_input in valid_options:
return user_input
else:
# Otherwise continue to prompt user and warn of invalid input
print("\nWrong choice")
you can then use this in your code to request the options:
print("Pizza price program\n")
size = get_option("\nWhich size pizza you want? S,L,M\n", ['S', 'M', 'L'])
add_pepperoni = get_option("\nDo you want to add pepperoni to your pizza? Y/N\n ", ['Y', 'N'])
extra_cheese = get_option("\nDo you want to add extra chees on your pizza? Y/N\n", ['Y', 'N'])
# ...
Upvotes: 1