I’m working on my AP create task. I made a shopping cart where if you type "shop" in the code, a prompt pops up that allows you to add a item to cart.
Code:
def shop():
if user_1 == "shop":
print("\n")
shop_1 = input("type a item to add to cart")
shopping_list.append(shop_1)
Right now, it works so that when you enter an item and press enter, it basically stops the code. How would I make it so it repeats and u can keep typing variables to add to the list?
CodePudding user response:
You can use this code inside a infinite loop.
while True:
#your code
If you want to stop running the loop at a place, you may change your condition to this
while ((input_variable := input())!= "stop"):
CodePudding user response:
I guess you could do a while loop. So that it will keep asking until you are done.
still_shoping = True
while still_shoping:
def shop():
if user_1 == "shop":
print("\n")
shop_1 = input("type a item to add to cart. or type 'done' if you wanna go to the next step")
if shop_1 == "done":
still_shoping = False
else:
shopping_list.append(shop_1)
CodePudding user response:
You can do it this way to prevent stopping the code:
shopping_list = []
def get_input():
"""
This function just get user Input
"""
inp = input("Enter input:\n")
return inp
def show_list():
"""
This function just prints the shopping list
"""
print(f"shopping list is as follow : {shopping_list}")
def shop():
inp = get_input()
if inp =="shop":
print("\n")
shop_1 = input("type a item to add to cart")
shopping_list.append(shop_1)
# Here is what you want, this line calls the shop function to get new input from the user and check its value again.
shop()
elif inp == "show":
show_list()
shop()
elif inp =="exit":
exit()