Goal:
After the user inputs whether they want to add another new item or not I want the code to start over at the newItem input line so that I don't have to just keep the if-train going and end up adding a cap to it.
Listed below is the code I've written so far.
shopping_cart_menu = []
shopping_cart_prices = []
print("Welcome to the shopping cart program. Please select an option from the menu below.")
print("*******************")
print("01: Add a new Item")
print("02: Display Cart contents")
print("03: Remove Item")
print("04: Compute Total")
print("05: Quit")
print("*******************")
menuAnswer = input(" ")
if menuAnswer == "01":
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followUp = input("Would you like to add another item? Y/N: ")
if answer = "Y"
Here is how you can use a while loop:
menuAnswer = input(" ")
if menuAnswer == "01":
while True:
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followUp = input("Would you like to add another item? Y/N: ")
if answer != "Y":
break
Using a while loop will allow you to loop the if statements. The line "followup = followup.upper()" will capitalise the input too.
shopping_cart_menu = []
shopping_cart_prices = []
print("Welcome to the shopping cart program. Please select an option from the menu below.")
print("*******************")
print("01: Add a new Item")
print("02: Display Cart contents")
print("03: Remove Item")
print("04: Compute Total")
print("05: Quit")
print("*******************")
menuAnswer = input(" ")
if menuAnswer == "01":
followup = "Y"
while followup == "Y":
newItem = input("What item would you like to add? ")
shopping_cart_menu.append({newItem})
followup = input("Would you like to add another item? Y/N: ")
followup = followup.upper()
Related
I wanted a create a function in Python where the user inputs the name of the menu and then it returns it in their order. After they are finished with ordering, the function would then calculate the price. My problem is I typed "Apple", but it came back empty. Is there anyway I could get around this? Any assistance is appreciated.
Here is the function:
menu = [{"Menu":"Apple","Price":9.00},{"Menu":"Banana","Price":5.00}], my_order = [], userInput = 0
try:
userInput = input("Enter item menu name that you want to select >> ") except ValueError:
print("Item does not exist.") if userInput in menu:
print("The item is in the list") else:
print("The item is not in the list. Please choose a different item.") while userInput != "Stop" or userInput != "stop":
print(f"Available menu: {menu}")
userInput = input("Do you want to add the item from the menu? If so please type appropriate item menu name. If no please type Stop. >> ")
if userInput == "Stop" or userInput == "stop":
print("The program has ended no more items will be added.")
print(f"Your order: {my_order}")
break
elif userInput not in menu:
print("Item does not exist in the list, try another item.")
print(f"Your order: {my_order}")
continue
else:
menu["Menu"] = userInput
my_order.append(userInput)
print(f"Your order: {my_order}")
continue
The way you use a dictionary is to have a key and a value related to it, in this case your menu dictionary should be {"item":price}.
That way if you want to know the price of an Apple yo do
print(menu["Apple"])
Did not understand why the Try/except in this case.
menu = {"Apple" : 9.00, "Banana" : 5.00}
my_order = []
userInput = ""
while userInput != "Stop" or userInput != "stop":
print(f"Available menu: {menu}")
userInput = input("Do you want to add the item from the menu? If so please type appropriate item menu name. If no please type Stop. >> ")
if userInput == "Stop" or userInput == "stop":
print("The program has ended no more items will be added.")
print(f"Your order: {my_order}")
break
elif userInput not in menu:
print("Item does not exist in the list, try another item.")
print(f"Your order: {my_order}")
continue
else:
my_order.append(userInput)
print(f"Your order: {my_order}")
continue
I let you continue calculating the total for the bill.
Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!
switch = True
players = []
while True:
user_adding = input("Would you like to add? yes or no ")
user_adding = user_adding.title()
if user_adding.lower() == "yes":
player_name = input("who do you want on the list? ")
players.append(player_name)
number_of_players = len(players)
elif user_adding.lower() == "no":
player_1 = players[0]
print(player_1)
print(f"There are {number_of_players}")
switch = False
Can't get to the elif statement here and i am not sure why...what could it be..
You have to enter "no" to get to the elif, but you need to have done yes first or the code will raise an exception at players[0]:
Would you like to add? yes or no yes
who do you want on the list? Bob
Would you like to add? yes or no no
Bob
There are 1
Some notes on this code: the switch value is never used, and there's no reason to title() case user_adding if you're going to lower() it later.
Here's a slightly simpler version that will break the loop after you say "no", and won't crash if 0 players are entered:
players = []
while True:
user_adding = input("Would you like to add? yes or no ")
if user_adding.lower() == "yes":
player_name = input("who do you want on the list? ")
players.append(player_name)
elif user_adding.lower() == "no":
print(" ".join(players))
print(f"There are {len(players)}")
break
else:
print(f"I don't know what '{user_adding}' means!")
One mistake i saw is that the number_of_players is not accessible in elif statement unless it goes first through if statement.
Because if you are trying to input no at the first time, players is empty and it will cause an Indexerror
Try :
players = []
while True:
user_adding = input("Would you like to add? yes or no ")
user_adding = user_adding.title()
if user_adding.lower() == "yes":
player_name = input("who do you want on the list? ")
players.append(player_name)
number_of_players = len(players)
elif user_adding.lower() == "no":
if len(players) :
player_1 = players[0]
print(player_1)
print(f"There are {number_of_players}")
switch = False
else:
print("No Players")
The problem isn't that you aren't entering the elif. The problem is that your loop doesn't examine the value of switch that the elif sets to False. You want while switch:, not while True:.
I am trying to create a phone book and I have everything except I need to run the entire code over and over instead an individual if statement. I am not sure how to continue any advice?
I have used a while loop.
#Intro
print("Address book to store friends contact")
print("-" * 50)
print("-" * 50)
#Display of options
print("Select an option: ")
print("1-Add/Update contact")
print("2- Display all contacts")
print("3- Search")
print("4- Delete contact")
print("5- Quit")
#Selection
option = input("Select which one you would like to choose. Ex. Select an
option. Type here: ")
#Map
contacts = {}
#Main program
for i in range(0,1):
if option == "Add/Update contact":
person_added = input("Who would you like to be updated or added")
next_question = input("What is there contact information")
#The code below will add the person to the list or update them
contacts [person_added] = next_question
elif option == "Display all contacts":
print(contacts)
elif option == "Search":
search_question = input("Who are you looking for: ")
for search in contacts.items():
if search == search_question:
print("I found" + search)
else:
print("Contact not found")
elif option == "Delete contact":
person_deleted = input("Who would you like to be deleted ")
del(contacts[person_deleted])
else:
print("Thank You! Goodbye")
I'm a bit confused on the logic of doing this.
I want the user to be able to input the number of items they have, and then ask them at the end if they are done. Right now I'm asking after every single item, and I don't like it.
How should I modify this code to get what I want?
Input:
if next1 == "2":
next2=input("How many would you like to add? ")
val = int(next2)
print("")
count = 0
while count < int(next2):
count = count + 1
next3=input(str(count) + ". Input: ")
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
add(next3)
home()
elif check in ("NnNo"):
sort(numbers)
home()
Function:
def add(next2):
numbers.append(next2)
sort(numbers)
home()
Okay, well generally you might do something like this
def confirm_with_user():
user_data = ""
while user_data not in "YyYesNnNo":
user_data = input("Are you sure? (Y/N) ")
return user_data.lower() in "yes":
Then at the point in your code when you want to confirm with your user you just do
if confirm_with_user():
#proceed...
else:
#They don't want to proceed