Home > Software design >  Why is my while loop printing continously in the python IDLE shell
Why is my while loop printing continously in the python IDLE shell

Time:02-19

I am trying to write a loop that keeps asking the user for the number of items they bought, only stopping when the user inputs 0 or less. Here is my code:

quantity = int(input("Enter the amount of items bought: "))
while (quantity>0):
    print("You bought", quantity, 'items')

The problem is that this "print("You bought", quantity, 'items')" keeps printing continuously in the IDLE shell. Any help is appreciated.

CodePudding user response:

You're never actually changing the variable inside the loop so, if it enters said loop, it will never exit.

A simple fix is the re-ask within the loop:

quantity = int(input("Enter the amount of items bought: "))
while (quantity>0):
    print("You bought", quantity, 'items.')
    quantity = int(input("Enter the amount of items bought: "))

However, that unnecessarily duplicates code. There are many ways to fix that, but the best way is probably using the walrus operator introduced in Python 3.8 (from memory):

try:
    while (quantity := int(input("Enter the amount of items bought: "))) > 0:
        print(f"You bought {quantity} items.")
except ValueError:
    print("Invalid integer.")

You'll notice I've also added a check for the user entering an invalid integer, that's to prevent your program ending badly when they do so (and they will, trust me).

You should always assume the user of your code is a psychopathic software tester :-)

CodePudding user response:

In the snippet given, it seems you haven't changed the variable quantity after buying the item. I would suggest removing the loop entirely, if there is a currency value. Try this:

quantity = int(input("Enter the amount of items bought: ")) # Ask for amount bought 
print("You bought" str(quantity) " items.") # Buy message
currency-=cost_of_item # Replace cost of item with the cost of what you are buying and currency with the money variable

However, you could also try this if you still want to keep the loop inside your code:

quantity = int(input("Enter the amount of items bought: "))
while (quantity>0):
    print("You bought", quantity, 'items') # Same code as before
    quantity=0 # Exit loop 

CodePudding user response:

A loop makes code run over and over until it reaches a condition. Your code says

quantity = whatever the user inputs

while quantity is > than 0 print this statement

You're going to need to place the user input inside of your loop so it will say instead

while quantity is smaller than 0 ask a user for input

CodePudding user response:

Change it to this:

while (quantity>0):
    quantity = int(input("Enter the amount of items bought: "))
    print("You bought", quantity, 'items')

This way, you are asking for quantity every iteration.

  • Related