Ending a loop properly - python

I'm stuck on this code I'm trying to complete. I want it to print "there's no more recipes left", but it prints "lets choose a different meal" twice.
my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
"recipe2":[["a","b","c"], "g", "h", "i"],
"recipe3":[["a","b","c"], "j", "k", "l"],
"recipe4":["x", "y", "z"]}
for k,v in bank.items():
if my_choice in v:
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if choice == "y":
print("Enjoy your meal!")
break
elif choice == "n":
print("Lets find you a different meal") # this prints out twice when the alternate recipes run out.
else:
print("Please select y or n to keep your meal or select a different recipe.")
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if len(my_choice) in food_bank.items() > len(v):
print("Sorry we have no more recipes")

First, the if choice == "y" and elif choice == "n" statement should inside if my_choice in v:
Second, when elif choice == "n" you need to know if that is the last recipe (i.e. 'recipe4').
my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
"recipe2":[["a","b","c"], "g", "h", "i"],
"recipe3":[["a","b","c"], "j", "k", "l"],
"recipe4":["x", "y", "z"]}
for k,v in bank.items():
if my_choice in v:
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if choice == "y":
print("Enjoy your meal!")
break
elif choice == "n":
if "recipe4" != "recipe4":
print("Lets find you a different meal") # this prints out twice when the alternate recipes run out.
else:
print("Sorry we have no more recipes")
else:
print("Please select y or n to keep your meal or select a different recipe.")
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()

If you enter ā€™nā€™ repeatedly, then once the loop gets to 'recipe4', which does not contain 'my_choice'/'["a","b","c"], then a new value is not set for 'choice'. So it sees ā€™nā€™ from last time, and prints the different meal text the second time.
Here's what I suggest for your code.
my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
"recipe2":[["a","b","c"], "g", "h", "i"],
"recipe3":[["a","b","c"], "j", "k", "l"],
"recipe4":["x", "y", "z"]}
# Create a list from your dictionary
bankList = list(bank.items())
# And then sort it according to whether 'my_choice' is in a given recipe
# This way, the later loop will go through the matching recipes first
bankList.sort(key=lambda recipe: my_choice in recipe[1], reverse=True)
choice = None
for k, v in bank.items():
if choice == "n":
print("Let's find you a different meal")
print(f"The meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
# If the user did not enter 'y' or 'n', keep asking until they do
while choice not in ["y", "n"]:
print("Please select y or n to keep your meal or select a different recipe.")
print(f"The meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if choice == "y":
print("Enjoy your meal!")
break
else:
# This code will only run if the loop completes without breaking
# In other words, if all recipes are considered and the user never says 'y' to any of them
print("Sorry, we have no more recipes")

Related

How can I handle 2 errors from user input in a while true loop

I am trying to make sure that the user enters only "s/r/e" in the shipping method input. The program is not handling the errors correctly for shipping method input. I am able to handle the input errors for the number of items. I am wondering if I am able to handle multiple errors under a single while true block. Any other recommended solutions are greatly appreciated!
This is what I have tried to do:
def mail_price_calculator(items, shipping_method):
if items <= 50:
cost = 3
if shipping_method == "s":
postage = 10
ship_by = "Standard post:"
elif shipping_method == "r":
postage = 15
ship_by = "Registered post:"
elif shipping_method == "e":
postage = 20
ship_by = "Express post:"
if items > 50:
cost = 2
if shipping_method == "s":
postage = 0
ship_by = "Standard post:"
elif shipping_method == "r":
postage = 10
ship_by = "Registered post:"
elif shipping_method == "e":
postage = 17
ship_by = "Express post:"
item_cost = items * cost
calculation = (items * cost) + postage
print("Receipt: ")
print(f"{items} items x ${cost} = ${item_cost}")
print(f"{ship_by} ${postage}")
print(f"Total: ${calculation}")
return calculation
while True:
try:
items = int(input("Enter the number of items: "))
except ValueError:
print("Sorry, please enter a number\n")
continue
if items == 0:
print("Sorry, number of item cannot be 0\n")
else:
break
while True:
try:
shipping_method = str(input("Enter shipping method (s/r/e): "))
except ValueError:
print("Please enter an alphabet: \n")
continue
if shipping_method != ("s", "r", "e", "S", "R", "E"):
print("Sorry, please enter a valid shipping method (s/r/e): \n")
else:
break
print()
mail_price_calculator(items, shipping_method)
Replace this line:
if shipping_method != ("s", "r", "e", "S", "R", "E")
with:
if shipping_method not in ("s", "r", "e", "S", "R", "E")
Or even:
if shipping_method.lower() not in "sre"
P.S. the try/except while defining shipping_method is unnecessary - input always returns a string and raises no errors

Python Else statement is voided [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
When user input is anything different from the specified letters "A", "a", "B", "b", "C", "c", "E", "e", it doesn't run the else statement but just closes. I would also like to have it repeat the program again if user input is not any of the specified letters, how can I achieve that? I believe it would be something I'd have to add in the else statement.
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Python is very indentation specific. This should do the trick:
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Your else should be part of the outer if (so same indentation), for now it is part of the inner if
Also you can simplify the tests, by first using .upper() to deal only with uppercase letters, and test the inclusion with user_input in "ABCDE"
user_input = input().upper()
if user_input in "ABCDE":
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Ask again version
user_input = input("Please choose: ").upper()
while user_input not in "ABCDE":
print("Something went wrong, try again: ")
user_input = input().upper()
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")

How to go back to the first if statement when no other choice was inputted [duplicate]

This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 2 years ago.
answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
print("################################")
print("# #")
print("# Welcome to PyLandia #")
print("# #")
print("################################")
print()
print()
print("Wha... What? Where am I?")
print()
print("*You look around to see a thick forest surrounding you.*")
print()
startGame = input("Begin the game of PyLandia? [Y/N]: ")
if startGame in yes:
intro()
elif startGame in no:
print("Ok, Maybe next time!")
I cant figure this error out! What i HAVE is that on the if and elif, when a user types Y or N, it will give the appropriate answer. That is working fine. What i NEED to add though is that if someone accidentaly typed "U" for example, it would say "No Y or N found! Try again!" Then it will go back to the first if statement to enter y/n again. I have tried looking at older articles saying to use def, or while loops, but NOTHING WORKS! i want to make a game, and i will need to implement the error retry code into EVERY QUESTION! someone please help! i cant solve it :(
I would replace the bottom part to contain this:
while True:
startGame = input("Begin the game of PyLandia? [Y/N]: ")
if startGame in yes:
intro()
break
elif startGame in no:
print("Ok, Maybe next time!")
break
else:
print("No Y or N found! Try again!")
Here's the full code:
answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
print("################################")
print("# #")
print("# Welcome to PyLandia #")
print("# #")
print("################################")
print()
print()
print("Wha... What? Where am I?")
print()
print("*You look around to see a thick forest surrounding you.*")
print()
while True:
startGame = input("Begin the game of PyLandia? [Y/N]: ")
if startGame in yes:
intro()
break
elif startGame in no:
print("Ok, Maybe next time!")
break
else:
print("No Y or N found! Try again!")

Break from raw_input in while loop

I've written a very simple dice rolling script in Python. It'll allow you to roll three times. However, I don't know how to break out of the while loop and avoid the raw_input the final time.
#!/usr/bin/python
from random import randrange, uniform
def rollDice():
dice = randrange(3,18)
print ("You rolled: %s" % dice)
maxReRoll = 2
c = 0
reRoll = "y"
while reRoll in ["Yes", "yes", "y", "Y"]:
if c > maxReRoll:
break
else:
rollDice()
c+=1
reRoll = raw_input("Roll again? y/n ")
Just a little swap is needed.
while reRoll in ["Yes", "yes", "y", "Y"]:
rollDice()
c+=1
if c >= maxReRoll: # notice the '>=' operator here
break
else:
reRoll = raw_input("Roll again? y/n ")
This should work for you:
from random import randrange
def roll_dice():
dice = randrange(3,18)
print("You rolled: %s" % dice)
max_rolls = 2
c = 0
re_roll = "y"
while re_roll.lower() in ["yes", "y"] and (c < max_rolls):
roll_dice()
c += 1
if c != max_rolls:
re_roll = input("Roll again? y/n ")

Cant get my code to Print out depending on different statements in Python

I have tried else and elif statements but nothing works any ideas?
import random
choice = input(" Witch one did u pick Rock , Paper or Scissors?")
print(choice)
computer = ["R", "P", "S"]
print(random.choice(computer))
if choice == "R" and random.choice(computer) == "R":
print("Sorry its a tie")
if choice == "R" and random.choice(computer) == "P":
print("Sorry Will wins")
You should not call random.choice(computer) everytime, this can give different results in different calls to the function. You should only call it once, and then save that result and use it in the if..elif . Also you should use if..elif , not if..if .
import random
choice = input(" Witch one did u pick Rock , Paper or Scissors?")
print(choice)
import random
computer = ["R", "P", "S"]
choosen = random.choice(computer)
print(choosen)
if choice == "R" and choosen == "R":
print("Sorry its a tie")
elif choice == "R" and choosen == "P":
print("Sorry Will wins")
Let's start from the top. First you say:
choice = input("Witch one did u pick Rock, Paper or Scissors?)
print(choice)
Because you are printing this decision out it may help with user experience and debugging to instead write:
print("User Choice: " + choice)
Moving on:
computer = ["R", "P", "S"]
print(random.choice(computer))
From a user standpoint if you're going to print this out you want to match the same style as before and write:
computer = ["Rock", "Paper", "Scissors"]
And from a programming standpoint you're going to want to save the result of the random choice in a variable so you can use it later, because calling random.choice again will create new answers. So a good way of approaching this would be:
computerDecision = random.choice(computer)
print("Computer Choice: " + computerDecision)
Finally you have your if statements. First you are checking:
if choice == "R"
The problem with this is earlier in your code you wrote:
choice = input(" Witch one did u pick Rock , Paper or Scissors?")
Meaning the output would most likely be ("Rock", "Paper" or "Scissors") not ("R", "P" or "S") so you would want:
if choice == "Rock"
And you use the same if statement twice so you can can just make a nested if and use your variable from earlier:
if choice == "Rock":
if computerDecision == "Rock":
print("Sorry its a tie")
elif computerDecision == "Paper":
print("Sorry Will wins")
elif computerDecision == "Scissors":
print("You win")
else:
print("Invalid input")
You would need to make this for "Paper" and "Scissors" as well.
That final else statement simply covers the scenario of the user inputting something besides "Rock", "Paper", or "Scissors"

Categories