Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my while loop printing continously in the python IDLE shell

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading