+ 1
How can I terminate my while loop?
I’m trying to understand how to end my while loop after the inventory number gets printed out. Any help would be greatly appreciated. Thanks! inventory = {"apples": 12, "bananas": 24, "cherries": 36, "dates": 48} inventory_items = ["apples", "bananas", "cherries", "dates"] print(inventory_items) desired_fruit = input("Which fruit from the list above do you want to know the inventory to?") while True: chosen_fruit = False for i in inventory: if desired_fruit == i: chosen_fruit = True if chosen_fruit: print(inventory[i]) else: print("Error. Make sure to input one of the listed inventory items in lower case form. Thank you!")
5 Antworten
+ 2
I tried to put a break after print(inventory[i]) but it kept iterating and printing the inventory number until it reached an Execution Time Out
+ 1
Just put a break after the print statement.
+ 1
Only a break after the print starement actually won’t help much. It’ll just infinitely print out your number. The reason behind this is that a break only breaks the loop you’re currently in. Because the print is in a for loop, it’ll break the for loop and not the while. The way I usually get around this, is setting a variable to True, changing the loop to run “while variable” rather than while True, and then set that variable to False once you want it to break.
https://code.sololearn.com/cG484zmuW6kx/?ref=app
+ 1
Shane Sorry I did not see the for loop and thought that the break will do. You can start by saying something like x = True.
while x:
....
...
..
.
when the condition is true and you print the value. Just do x = False and then break.