How to Get out Infinite Loop

How to Get out Infinite Loop

You work for a bakery that sells two items: muffins and cupcakes. The number of muffins and cupcakes in your shop at any given time is stored in the variables muffins and cupcakes , which have been defined for you. Write a program that takes strings from standard input indicating what your customers are buying ("muffin" for a muffin, "cupcake" for a cupcake). If they buy a muffin, decrease muffins by one, and if they buy a cupcake, decrease cupcakes by 1. If there is no more of that baked good left, print ("Out of stock"). Once you are done selling, input "0" , and have the program print out the number of muffins and cupcakes remaining, in the form "muffins: 9 cupcakes: 3" (if there were 9 muffins and 3 cupcakes left, for example).

to_buy=input()
while to_buy != "0":
if to_buy==muffins and muffins>0:

    muffins-=1
else:
    print("Out of stock")
if to_buy==cupcakes and cupcakes>0:

    cupcakes-=1
else:
    print("Out of stuck")
print("muffins:",muffins,"cupcakes:",cupcakes)

The above is the question and the code that i have wrote. When I try to run it, the code kept going into a infinite loop, I don't know why.

1

3 Answers

the code kept going into a infinite loop, I don't know why.

to_buy=input()
while to_buy != "0":

You never change to_buy, so the loop continues indefinitely. For instance, suppose to_buy is "3". Then the while loop condition is True, so execution enters the while loop. But inside the while loop to_buy never changes, so the while loop executes over and over again.

To get around that problem, you can do this:

while True:  #Infinite loop

    to_buy = input()
    if to_buy == "0": break  #Terminate the infinite loop

    #Rest of code here
8

this line: to_buy=input()

must be inside the loop

the variable to_buy never changed it's value while looping.. so therefore, it will not exit the loop and it result to infinite loop.

in order to exit the loop. you must change the value of variable to_buy.

in Order to do that.

you must place the input inside the loop

I will suggest also to use a do while, so it will process the input first

2
to_buy=input()
while to_buy != "0":
    if to_buy=="muffin":
        if muffins>0:
            muffins-=1
        else:
            print("Out of stock")
    if to_buy=="cupcake":
        if cupcakes>0:
            cupcakes-=1
        else:
            print("Out of stock")
    to_buy=input()
print("muffins:", muffins, "cupcakes:", cupcakes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.