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

How do I write a while loop inside an if statement if I want to ask user to add elements to the list

I want the program to ask user to add something to the list, then ask him if its all. If no, the while loop keeps asking to add until he’s done and then the program prints the list with all the added elements.

Not sure how to do this, I’m a beginner, program keeps ignoring my while loop.

shopping_cart = []



statement = input("Do you want to add an item to the cart?: ")
added_items = ""

if statement == "yes":
    while len(added_items) == " ":
        added_items = shopping_cart.append(input("What item to add?: "))
    print(shopping_cart)
elif statement == "no":
    print(shopping_cart)

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 :

Collecting user input and the if statement should be inside the the while loop so that the system keeps looping till user type no

shopping_cart = []

while True:
    statement = input("Do you want to add an item to the cart? (yes/no): ")
    if statement.lower() == "yes":
        item = input("What item to add?: ")
        shopping_cart.append(item)
    elif statement.lower() == "no":
        break

print("Items in your shopping cart:", shopping_cart)
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