Crude virtual shop project fails when selection item from dictionary - python

I am making a crude shop in a Python 3.x script as a small project ( I started coding two days ago ), and when my program attempts to subtract the value of the item selected by the user from the initial amount of money the user starts out with, the program crashes.
Note: balance(): function aims to display remaining amount of money yet, but is not finished yet.
How can I fix my code, and is there any other way to improve/optimize it? Also, if you give a solution, please assume I don't know what method you will be using, so please give context and explain what you are using and other applications it can be used in.
import time
import sys
# Dictionary:
# Shop Catalog, with numbers for prices.
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
# Money Values/Variables:
# Initial Money
initialMoney = 3000
# Functions:
# Catalog browsing:
# This is where you are presented the different items on sale, and choose which you will order
def browse():
print("Welcome to the Virtual Shop Catalog")
time.sleep(1)
print("Here is what is currently on sale (item:price): ")
time.sleep(1)
print(shopCatalog)
time.sleep(1)
print("Enter '4' to quit")
time.sleep(1)
# This loop is where you choose to either return to the main menu, or order items.
while True:
try:
shopChoice = int(input("Enter item of choice: "))
if shopChoice == 4:
print("Returning back to main menu...")
time.sleep(0.5)
mainMenu()
break
# This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance
elif shopChoice == 1 or 2 or 3 or 4 or 5 or 6:
print(" Purchased 1 " + shopCatalog[shopChoice] + " .")
initialMoney = initialMoney - shopCatalog[shopChoice]
break
elif shopChoice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-6")
browse()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# Balance and money in account:
# This loop allows you to check the money in your account:
def balance():
print("hi")
# Menu selection function:
# It gives the user a number of three options, and will only accept the three integers provided.
def mainMenu ():
time.sleep(0.5)
print("1. Browse shop catalog")
time.sleep(0.5)
print("2. Check remaining balance")
time.sleep(0.5)
print("3. Quit program")
while True:
try:
choice = int(input("Enter number of choice: "))
if choice == 1:
browse()
break
elif choice == 2:
balance()
break
elif choice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-3")
mainMenu()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# On startup:
# This is the startup code and messages
print("Welcome to my virtual shop!")
time.sleep(0.5)
print("What would you like to do?")
time.sleep(0.5)
mainMenu()

Shop catalog is defined as:
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
However, you are trying to access the key by number. Such as
shopCatalog[2] which doesn't exist as a valid key. A valid key would be
shopCatalog['2. Gucci Belt']
Instead, try a list of tuples. A list is better because the order is guaranteed. In a dict, even though you numbered your items, it may print out of order.
shopCatalog = [ ('MCM Backpack', 790), ('Gucci Belt' : 450) , ...]
If you want the first item, you can just access it by the index. If you want them numbered, again, just use the index (although for both, keep in mind it is zero-indexed so you may have to add on to print your numbering and subtract one to get the right item.
Also, there is a flaw in your logic here:
shopChoice == 1 or 2 or 3 or 4 or 5 or 6:
While people talk like that, coding doesn't work like that. Instead, you'd have to do:
shopChoice ==1 or shopChoice ==2 and so on. But skip all of that and just say:
elif 1 <= shopChoice <= 6:

The error is:
Traceback (most recent call last):
File "C:/Users/s4394487/Downloads/crap.py", line 96, in <module>
mainMenu()
File "C:/Users/s4394487/Downloads/crap.py", line 73, in mainMenu
browse()
File "C:/Users/s4394487/Downloads/crap.py", line 38, in browse
print(" Purchased 1 " + shopCatalog[shopChoice] + " .")
KeyError: 1
shopCatalog is a dictionary, so you can access its values using keys. The keys are '1. MCM Backpack', '2. Gucci Belt' etc. Not numbers.
If you want to access the first, second etc. values in a dictionary, you can use an OrderedDictionary in Python: https://docs.python.org/3/library/collections.html#collections.OrderedDict

Try the below code, now i think it will work:
import time
import sys
# Dictionary:
# Shop Catalog, with numbers for prices.
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
# Money Values/Variables:
# Initial Money
initialMoney = 3000
# Functions:
# Catalog browsing:
# This is where you are presented the different items on sale, and choose which you will order
def browse():
global initialMoney
print("Welcome to the Virtual Shop Catalog")
time.sleep(1)
print("Here is what is currently on sale (item:price): ")
time.sleep(1)
print(shopCatalog)
time.sleep(1)
print("Enter '4' to quit")
time.sleep(1)
# This loop is where you choose to either return to the main menu, or order items.
while True:
try:
shopChoice = input("Enter item of choice: ")
if shopChoice == 4:
print("Returning back to main menu...")
time.sleep(0.5)
mainMenu()
break
# This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance
elif shopChoice in ('1','2','3','4','5','6'):
print(" Purchased 1 " + str(shopCatalog[[i for i in shopCatalog.keys() if str(shopChoice) in i][0]]) + " .")
initialMoney = initialMoney - shopCatalog[[i for i in shopCatalog.keys() if str(shopChoice) in i][0]]
break
elif shopChoice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-6")
browse()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# Balance and money in account:
# This loop allows you to check the money in your account:
def balance():
print("hi")
# Menu selection function:
# It gives the user a number of three options, and will only accept the three integers provided.
def mainMenu ():
time.sleep(0.5)
print("1. Browse shop catalog")
time.sleep(0.5)
print("2. Check remaining balance")
time.sleep(0.5)
print("3. Quit program")
while True:
try:
choice = int(input("Enter number of choice: "))
if choice == 1:
browse()
break
elif choice == 2:
balance()
break
elif choice == 3:
print("You want to leave already...? Ok, have a good day!")
time.sleep(1)
break
else:
print("Invalid option. Please pick a choice from 1-3")
mainMenu()
except ValueError:
print("Invalid option. Please input an integer.")
exit
# On startup:
# This is the startup code and messages
print("Welcome to my virtual shop!")
time.sleep(0.5)
print("What would you like to do?")
time.sleep(0.5)
mainMenu()
Your code didn't work because there are no such a key i.e 1 or 2 etc so i simply just check each key if shopChoice is in it, if it is, get the value of it, if it isn't, check the next one.

Related

Why colorama make printing slower in python (Thonny)?

It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))

Looping back to a specific line in Python

I am writing a program (for no specific purpose), where I take orders from users, which run the program. At some point, I ask them if they are happy with their decision. They have the option to "say" Yes or No. If their answer is no, I need the program to loop back to a specific point in the code. How can I do that?
Here's the code:
import datetime
import calendar
import time
import colorsys
import math
# Definitions
date = time.strftime("%A")
MenuItems = {0:["Beef steak (0.5 kg) with french fries or basmati rice and mushroom sauce.","Patata con pollo (potato slices with chicken and cooked cream) with cooked vegetables.","Moussaka with green beans, carrots and broccoli \033[92m(vegeterian)\033[37m."],
1:["Beef stroganoff with noodles.","Risotto with pork meat and cooked vegatables.","Gratinated cottage cheese pancakes \033[92m(vegeterian)\033[37m."],
2:["Spaghetti carbonara.","Noodle soup with cut up parsley.","Gnocchi with tomato sauce and sauteed vegetables \033[92m(vegeterian)\033[37m."],
3:["Fried hake with cooked potatoes.","Pizza Palermo (tomato sauce, cheese, ham, pancetta and mushrooms.","Pizza Margherita (tomato sauce, cheese, olives) \033[92m(vegeterian)\033[37m."],
4:["Warm salad with octopus.","Chicken filet with paears in spicy sauce.","Gratinated cheese tortellini with spinach, sour cream and an egg \033[92m(vegeterian)\033[37m."],
5:["Black angus burger with cheddar.","Macaroni with beef filet and tomatoes.","Spaghetti with vegetable sauce \033[92m(vegeterian)\033[37m."]}
DrinkItems = {0:["Soft beverages","Carbonated beverages","Alcoholic beverages","Hot beverages"],
1:["Cedevita (0,5l)","Ice Tea (0,5l)","Water (0,5l) \033[92m(FREE)\033[37m","Apple juice (0,25l)","Orange juice (0,25l)","Strawberry juice (0,25l)","Peach juice (0,25l)","Lemonade (0,5l)","Water with taste (0,5l)"],
2:["Coca Cola (0,25l)","Coca Cola Zero (0,25l)","Coca Cola Zero Lemon (0,25l)","Cockta (0,25l)","Fanta (0,25l)","Schweppes Bitter Lemon (0,25l)","Schweppes Tonic Water (0,25l)","Schweppes Tangerine (0,25l)","Radenska (0,25l)","Sprite (0,25l)","Red Bull (0,25l)"],
3:["Laško beer (0,33l)","Union beer (0,33l)","Malt (0,33l)","Non-alcoholic beer (0,33l)","Corona Extra (0,33l)","Guiness Extra Stout (0,33l)","Sparkling wine (0,10l)","White wine (0,10l)","Red wine (0,10l)","Blueberry Schnapps (0,03l)","Grappa (0,03l)","Stock (0,3l)","Jägermeister (0,03l)","Liquer (0,03l)","Rum (0,03l)","Tequila (0,03l)","Vodka (0,03l)","Gin (0,03l)","Whiskey (0,03l)","Cognac (0,03l)"],
4:["Coffee","Coffee with milk","Cocoa","Hot Chocolate","Irish Coffee","Tea (green, black, herbal, chamomile)"]}
MenuPrices= {0:[6.00, 4.50, 4.50],
1:[5.00, 4.50, 4.00],
2:[5.00, 4.00, 4.50],
3:[4.50, 4.50, 4.50],
4:[4.50, 5.00, 4.00],
5:[5.00, 5.00, 4.00]}
# Introduction of the Bartender
print ("Hello! Welcome to the e-Canteen!")
print ("")
time.sleep(1)
print ("Today is \033[1m" + (date) + "\033[0m.")
time.sleep(1)
# Menus available for current day
todayWeekday = datetime.datetime.today().weekday()
if todayWeekday < 6:
print ("We are serving:")
for x in MenuItems[todayWeekday]:
print(str(MenuItems[todayWeekday].index(x)+1)+".", x)
time.sleep(0.5)
# Canteen is closed on Sunday
else:
print ("Sorry, we're closed.")
exit()
# Ordering the menus
print ("")
time.sleep(1)
menu = int(input("Please choose a menu item by typing in a number from 1 to 3: "))-1
print ("")
if menu < int(3):
print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Person chooses higher menu item than 3
else:
print("Sorry, we do not have more than 3 menu items per day. Please choose a menu item from 1 to 3.")
time.sleep (1)
while menu >= 3:
menu = int(input("Please choose a menu by typing in a number from 1 to 3: "))-1
# Person chooses a menu item from 1 to 3
if menu < 3:
print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Any additional orders
# Choosing beverage category
print ("------------------------------------------------------------")
print ("")
time.sleep(2)
category = DrinkItems[0]
print("Please choose a type of beverage you would like to order:")
time.sleep(1)
for x in DrinkItems[0]:
print(str(DrinkItems[0].index(x)+1)+".", x)
print("")
time.sleep(0.5)
# Choosing beverage
category = int(input("Enter your number here: "))
print("")
print("You chose \033[1m" +DrinkItems[0][category-1] +"\033[0m. Here is a list:")
for x in DrinkItems[category]:
print(str(DrinkItems[category].index(x)+1)+".", x)
print("")
time.sleep(0.5)
drink = int(input("Please choose a beverage by entering the number in front of your desired beverage: "))-1
# User deciding if she/he is happy with her/his decision
decision = input("\nYou chose " +DrinkItems[category][drink] +". Are you happy with your decision? ").lower()
if decision == 'yes':
additional = input("Great! Would you like to order anything else? ").lower()
if additional == "yes":
what = input("What else would you like to order (menu, drink or both)? ").lower()
if what == "menu":
print("I understand. The program will return you to the menus.")
elif what == "drink":
print("I understand. The program will return you to the drinks.")
elif what == "both":
print("I understand. The program will return you back to the menus (no orders until now will be lost).")
elif additional == "no":
print("Awesome! The program will now summ up your price. Please wait a moment...")
time.sleep(2)
elif decision == "no":
change = input("I'm sorry to hear that. What else would you like to change (menu, drink or both)? ").lower()
if change == "menu":
print("I understand. The program will return you to the menus.")
elif change == "drink":
print("I understand. The program will return you to the drinks.")
elif change == "both":
print("I understand. The program will return you back to the menus.")
# Any additional beverages
# Billing
print(sum(DrinkItems[category][drink]))
# End
I am new relatively new to the coding scene.
Thank you in advance for any answers.
You can wrap your code inside a while loop:
while True:
// your code
// at some point in the code:
happiness = input("Are you happy?")
if happiness == "yes":
break
To go to a specific point in the code, you will have to use this pattern (or something similar) several times.
You can use break statement to stop the(infinite)loop while continue is used to skip something that is what you're looking for here.
So, your code needs to be like this
# User deciding if she/he is happy with her/his decision
while True:
decision = input("\nYou chose "+". Are you happy with your decision? ").lower()
if decision == 'yes':
additional = input("Great! Would you like to order anything else? ").lower()
if additional == "yes":
what = input("What else would you like to order (menu, drink or both)? ").lower()
if what == "menu":
print("I understand. The program will return you to the menus.")
elif what == "drink":
print("I understand. The program will return you to the drinks.")
elif what == "both":
print("I understand. The program will return you back to the menus (no orders until now will be lost).")
break
elif additional == "no":
print("Awesome! The program will now summ up your price. Please wait a moment...")
time.sleep(2)
break
elif decision == "no":
continue

Vending Machine Program help(python)

I'm kinda stuck on something. Well, alot of things but one step at a time right. I'm not sure how to get the program to add the choices that the user input together. The assignment asks me to make a vending machine that gets a users input, return the total to them when they input 0 to quit, then it will ask them to enter the money to pay, if it is a valid amount, it will dispense change, if not, it will ask for more money. Right now though, I'm stuck on it returning the user choices and adding the total together. I will paste my code below. thanks
def main():
userchoice = ()
while userchoice != 0:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
Options()
# Now, the first input will ask the user to enter their choice
userchoice = float(input("Please enter the number corresponding to your preferred item or 0 to quit: "))
# Now, the program will print the choice and re-run it until the user selects 0
choices = []
choices.append(userchoice)
if userchoice == 1:
print("You selected one can of Dr.Pepper for $1.50")
elif userchoice == 2:
print("You selected one can of Mtn.Dew for $1.50")
elif userchoice == 3:
print("You selected one bottle of Water for $1.00")
elif userchoice == 4:
print("You selected one bag of Doritos for $1.75")
elif userchoice == 5:
print("You selected one Snickers bar for $1.50")
elif userchoice == 6:
print("You selected one pack of Gum for $0.50")
elif userchoice == 0:
print(choices)
else:
print("Invalid Choice, Please Try Again")
def Options():
print("\t1. Dr.Pepper - $1.50\n"
"\t2. Mtn.Dew - $1.50\n"
"\t3. Water - $1.00\n"
"\t4. Doritos - $1.75\n"
"\t5. Snickers - $1.50\n"
"\t6. Gum - $0.50")
def Sum(userchoice):
return userchoice + userchoice
main()
I have discovered one problem which is that when you declare choices you declare it inside the loop, meaning it becomes [] each time the user picks something.
Try this:
def main():
choices = []
userchoice = ()
while userchoice != 0:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
Options()
# Now, the first input will ask the user to enter their choice
userchoice = int(input("Please enter the number corresponding to your preferred item or 0 to quit: "))
# Now, the program will print the choice and re-run it until the user selects 0
choices.append(userchoice)
if userchoice == 1:
print("You selected one can of Dr.Pepper for $1.50")
elif userchoice == 2:
print("You selected one can of Mtn.Dew for $1.50")
elif userchoice == 3:
print("You selected one bottle of Water for $1.00")
elif userchoice == 4:
print("You selected one bag of Doritos for $1.75")
elif userchoice == 5:
print("You selected one Snickers bar for $1.50")
elif userchoice == 6:
print("You selected one pack of Gum for $0.50")
elif userchoice == 0:
print(choices)
else:
print("Invalid Choice, Please Try Again")
def Options():
print("\t1. Dr.Pepper - $1.50\n"
"\t2. Mtn.Dew - $1.50\n"
"\t3. Water - $1.00\n"
"\t4. Doritos - $1.75\n"
"\t5. Snickers - $1.50\n"
"\t6. Gum - $0.50")
def Sum(userchoice):
return userchoice + userchoice
main()
This means that the choices variable now has something useful in it.
Here is a more refined approach, it always helps to see different design concepts:
options = {
'1': {'title':'Dr.Pepper','price':1.50},
'2': {'title':'Mtn.Dew','price':1.50},
'3': {'title':'Water','price':1.00},
'4': {'title':'Doritos','price':1.75},
'5': {'title':'Snickers','price':1.50},
'6': {'title':'Gum','price':0.50}
}
def get_number(question):
value = input(question)
while 1:
try:
value = int(value)
break
except:
value = input(f'(must be a number) {question}')
return value
def main():
choices = []
amount = 0
while 1:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
for k, v in options.items():
print(f"\t{k}. {v['title']} - ${v['price']:.2f}")
# Now, the first input will ask the user to enter their choice
userchoice = get_number('Please enter the number corresponding to your preferred item or 0 to quit:')
if userchoice == 0:
break
# Now, the program will print the choice and re-run it until the user selects 0
choice = options.get(str(userchoice), None)
if choice:
choices.append(choice['title'])
amount += choice['price']
print(f"You selected one {choice['title']} for ${choice['price']:.2f}")
else:
print('Invalid Choice, Please Try Again')
print('Your Cart Contains:')
for each in sorted(choices):
print(each)
print(f'Total Amount: {amount}')
return choices, amount
choices, amount = main()

The price doesn't add up

creating a pizza ordering program for IT class, almost finished with it but I'm currently stuck with a problem that I can't seem to fix or don't know how to. As the user is finished choosing their pizza it was suppose to add up the total cost of the pizza they have chosen but the problems is they don't add up the instead the price stays the same
Name:Jack
Telephone:47347842
ORDER:
['2. Hawaiian pizza', 8.5]
['1. Pepperoni pizza', 8.5]
['3. Garlic cheese pizza (with choice of sauce)', 8.5]
Total Price: 8.50
Here's the price list that they have to choose from
['1. Pepperoni pizza', 8.5]
['2. Hawaiian pizza', 8.5]
['3. Garlic cheese pizza (with choice of sauce)', 8.5]
['4. Cheese pizza (with choice of sauce)', 8.5]
['5. Ham and cheese pizza', 8.5]
['6. Beef & onion pizza', 8.5]
['7. Vegetarian pizza', 8.5]
['8. BBQ chicken & bacon aioli pizza', 13.5]
['9. Boneless pizza (italian style anchovy with no bones)', 13.5]
['10. Pizza margherita', 13.5]
['11. Meat-lover’s pizza', 13.5]
['12. Tandoori pizza', 13.5]
I don't know if the problems lies in this code but it seem like it is. I originally I tried using 'cost.append' but it only came up with an error like this
unsupported operand type(s) for +: 'int' and 'str'
def Choice_of_pizza():
for i in range(1,pizza_no
+1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
cost.append(MENU[pizza_kind-1][0][pizza])
customerOrder.append(MENU[pizza_kind-1][pizza])
global total_cost
total_cost = sum(cost) #Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza()
So I went and replace it with 'cost=+customerOrder[i][1]' but even then it somewhat works with the names of the pizza being added but not the prices unto the customer details.
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
for i in range(len(customerOrder)):
cost=+customerOrder[i][1]
global total_cost
total_cost=0
#Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost=+cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost=+cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza(
The intended goal was, as the user input there choice one by one it takes out the name and places the price into the cost list but it doesn't seem to do that.
here's the original full code
#----------------------------important stuff-----------------------------------
#time delay
import time
#loop system for the details section
running = True #Loop
import re
Delivery_cost = 3.0
cost=[]
customerOrder=[]
customer_name=[]
customer_name_2=[]
customer_telephone_2=[]
house_no=[]
street_name=[]
#------------------------------menu list --------------------------------------
MENU =[
['1. Pepperoni pizza', 8.50], ['2. Hawaiian pizza', 8.50], ['3. Garlic cheese pizza (with choice of sauce)', 8.50],['4. Cheese pizza (with choice of sauce)', 8.50], ['5. Ham and cheese pizza', 8.50], ['6. Beef & onion pizza', 8.50], ['7. Vegetarian pizza', 8.50], ['8. BBQ chicken & bacon aioli pizza', 13.50], ['9. Boneless pizza (italian style anchovy with no bones)', 13.50], ['10. Pizza margherita', 13.50],['11. Meat-lover’s pizza', 13.50],['12. Tandoori pizza', 13.50]
]
#-----------------------------details------------------------------------
def pick_or_deli():
global delivery
delivery = input("P - pick up / D - delivery:")
delivery = delivery.upper() #Changes the letter inputted to an uppercase
if delivery == "D": #statement if person choosed delivery
while running == True:
global customer_name #This can be called when printing out final order and details
customer_name = input("Name:")
if not re.match("^[a-zA-Z ]*$", customer_name): #Checks whether input is letters only
print("Please use letters only")
elif len(customer_name) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
customer_name = customer_name.title()
break #Breaks the loop when valid input has been entered
while running == True:
global customer_telephone
customer_telephone = input("Telephone:")
if not re.match("^[0-9 ]*$", customer_telephone): #Checks whether input is numbers only
print("Please use numbers only")
elif len(customer_telephone) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
while running == True:
global house_no
house_no = input("House number:")
if not re.match("^[0-9 /]*$", house_no): #Checks whether input is numbers only
print("Please use numbers only")
elif len(house_no) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
while running == True:
global street_name
street_name = input("Street name:")
if not re.match("^[a-zA-Z ]*$", street_name): #Checks whether input is letters only
print("Please use letters only")
elif len(street_name) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
street_name = street_name.title()
break #Breaks the loop when valid input has been entered
elif delivery == "P": #statement for if person choosed pickup
while running == True:
global customer_name_2
customer_name_2 = input("Name:")
if not re.match("^[a-zA-Z ]*$", customer_name_2): #Checks whether input is letters only
print("Please use letters only")
elif len(customer_name_2) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
customer_name_2 = customer_name_2.title()
break #Breaks the loop when valid input has been entered
while running == True:
global customer_telephone_2
customer_telephone_2 = input("Telephone:")
if not re.match("^[0-9 ]*$", customer_telephone_2): #Checks whether input is numbers only
print("Please use numbers only")
elif len(customer_telephone_2) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
else:
print("Please enter P or D")
pick_or_deli()
pick_or_deli()
#-----------------------------order script-------------------------------------
print('''\nWelcome to ~~~~~ Dream Pizza ~~~~~
To pick an order from the Menu pick the designated number that is next to the product.\n
From 1 for Pepperoni pizza.\n
Or 2 for Hawaiian pizza.\n
and so on.\n
The delivery cost is $3\n
To cancel the order throughout press 0 and it will reset itself.\n
But first decide how many pizza you want.\n''')
time.sleep(3.0)
#--------------menu text and design can be called again------------------------
def menu_design():
print(*MENU, sep = "\n")\
menu_design()
#------------------deciding how many pizzas they want---------------------------
def order():
global pizza_no
while True:
try: #Validating the inputs
pizza_no = int(input('''\nNo. of pizzas you want (min 1 - max 5):\n'''))
if pizza_no < 1:
print("Please order between 1 - 5 pizzas") #Checks whether input is between 1 and 5
continue
if pizza_no > 12:
print("Please order between 1 - 5 pizzas")
continue
else:
break #Breaks the loop when valid input has been entered
except ValueError: #Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
order()
#--------------------------------picking pizza-----------------------------------
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
for i in range(len(customerOrder)):
cost=+customerOrder[i][1]
global total_cost
total_cost=0
#Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost=+cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost=+cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza()
#-----------------------------------reciept---------------------------------------
def customerDetails(): #Prints customer order and details
if delivery == "D": #if person choosed delivery
print ("")
print ("CUSTOMER and ORDER DETAILS")
print ("")
print ('Name: {}' .format(customer_name))
print ('Telephone: {}' .format(customer_telephone))
print ('Address:')
print (house_no, street_name)
print ("")
print ('ORDER:')
print(*customerOrder, sep = "\n")
print ('Total Price: $ {:.2f}' .format(total_cost))
print ('Total Price + Delivery Cost: $ {:.2f}' .format(Combined_Total))
else: #if person choosed pickup don't have to speccify
print ("")
print ("CUSTOMER and ORDER DETAILS")
print ("")
print ('Name:{}' .format(customer_name_2))
print ('Telephone:{}' .format(customer_telephone_2))
print ("")
print ('ORDER:')
print(*customerOrder, sep = "\n")
print ('Total Price: {:.2f}' .format( total_cost))
customerDetails()
#-----------confrimation of customers order proceed or cancel---------------------
print ("")
def confirm(): #Confirms details of customer and order
confirmation = input("Y - confirm order / N - cancel order:")
confirmation = confirmation.upper() #Changes the letter inputted to an uppercase
if confirmation == "Y": #if Y is entered, order is confirmed
print("DETAILS CONFIRMED")
elif confirmation == "N": #if N is entered, order is cancelled
print("DETAILS CANCELLED - order has been reset")
customerOrder[:] = []
cost[:] = []
menu_design()
order()
Choice_of_pizza()
customerDetails()
confirm()
else:
print("Please enter Y or N") #If anything other than Y or N is entered, it will ask again
confirm()
confirm()
#----statement im customer would like to order more or finalised there order---
print ("")
def order_more(): #Placing another order
order_more = input("Z - order more / x - exit program:")
order_more = order_more.upper() #Changes the letter inputted to an uppercase
'''cost[:] = []'''
if order_more == "Z":
menu_design() #Calls the functions - will run the code that the def defines
order()
Choice_of_pizza()
customerDetails()
confirm()
print ("")
print ("THANK YOU FOR YOUR SHOPPING AT DREAMS PIZZA")
if delivery == "D":
print ("Your order will be delivered in 25mins") #Ending statement
elif delivery == "P":
print ("Your order will be ready to pick up in 20mins") #Ending statement
elif order_more == "X":
print ("")
print ("THANK YOU FOR YOUR ORDER")
if delivery == "D":
print ("Your order will be delivered in 25mins") #Ending statement
elif delivery == "P":
print ("Your order will be ready to pick up in 20mins") #Ending statement
else:
print ("Please enter X or Z") #If anything other than X or Z is entered, it will ask again
order_more()
order_more()
Also why I only have one list? it is because I was required to only use one
Code Issues:
For addition assignment the syntax is:
x += y # this assigns x to (x + y)
Not:
x = +y # this assign x to y
Glbols are not causing a problem in your code, but are usually frowned upon and negatively reflect on programming skills i.e. Why are Global Variables Evil?.
Choice_of_pizza function fix
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
cost = 0
for i in range(len(customerOrder)):
cost += customerOrder[i][1]
global total_cost # globals are discouraged
total_cost=0
#Sum of the pizzas
global Combined_Total # globals are discouraged
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost += cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost += cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue

the input is not working in the second time

when an invalid answer (a number higher than 2) is given and is sent back to the intro(name) (see the else statement at the bottom) which is the introduction, the choise1 is auto completed and is redirected to crowbar()
def intro(name):#added the whole code
print( name + " you are in a back of a car hands tied, you can't remember anything apart the cheesy pizza you had for breakfast")
time.sleep(1)
print("you can see 2 men outside the car chilling out, they haven't seen that you have waken up")
time.sleep(1)
print("you figure out that your hands are not tied hard and manages to break free")
time.sleep(1)
print("and you see a piece of paper with your adress in it on the armrest in the middle of the front seats")
time.sleep(1)
print(" you see a crowbar under the back seat ")
time.sleep(1)
print("CHOOSE WISELY")
time.sleep(1)
print("""
1)grab the crowbar
2)check to see if the door was open""")
def car():
if choise1 == 1:
crowbar()
elif choise1 == 2:
door()
else:
print("that's not a valid answer")
intro(name)
choise1 = int(input("enter 1 or 2"))
car()
you can use function with parameter in this example (x )
def car(x):
if x == 1:
print("crowbar()")
elif x == 2:
print("door()")
else:
print("that's not a valid answer")
print("intro(name)")
choise1 = int(input("enter 1 or 2"))
car(choise1)

Categories