The price doesn't add up - python

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

Related

Expected expression ATM

I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")

How to print Congrats with out the error in python

The program goes as follows, asks to choose a product, then asks for the amount of the choice, then the user inputs the amount, but if the amount is different from the declared values (mo), the program prints "wrong coins", but when the user inputs the correct coin and amount, it should print only the "change" part of the code. In my program, it prints "change" and then wrong coin value
prod = ["Coffe", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
mo = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nPick an item:")
for number in range(0, item_number, 1):
print(number + 1,
prod [number],
'{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) -1
if choice < item_number and choice >= 0:
print("You should input", "{0:.2f}€".format(cost[choice]), 'in total')
else:
print("Exiting the program")
exit(0)
money = float(input("How much do you enter?; "))
while money < cost[choice]:
money += float(input("You should insert "+str("{:.2f}".format(cost[choice] - money))))
if money != mo:
print("Invalid amount.\nPlease enter a valid coin: 0.1 / 0.2 / 0.5 / 1 / 2 / 5 / 10")
else:
print("Try again")
change = money - cost[choice]
print("Change {0:.2f}€".format(change))
The logic may be different
continuously ask for money (a while True allow to write the input once)
verify if the choosen is in the list not equal (a float can't be equal to a list)
increment your total money
stop if you have enough
money = 0
while True:
new_money = float(input(f"You should insert {cost[choice] - money:.2f}: "))
if new_money not in mo:
print("Invalid amount.\nPlease enter a valid coin: " + "/".join(map(str, mo)))
continue
money += new_money
if money >= cost[choice]:
break
change = money - cost[choice]
print(f"Change {change:.2f}€")
The other code, with some improvments
print("\nPick an item:")
for number in range(item_number, ):
print(f'{number + 1} {prod[number]} {cost[number]:.2f}€')
print("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) - 1
if 0 < choice <= item_number:
print(f"You should input {cost[choice]:.2f}€", 'in total')
else:
print("Exiting the program")
exit(0)

how do i use loop with double input. first asks for a letter then the output then asks if u wanna play again or quit(1, 2)

so basically I want to start with the door input then check if the door has money or not then ask the user again if he would like to play again using the play input. if user enters 2 then asks again which door and so on. if the user enters 2 or if the number of miss on the door(no money) is = 3 then the game stops. right now the problem is it will run the loop jackpot ==1 till the it hits jackpot == 0 and play ==1 is not working
import random
total = 0
miss = 0
prizeMoney = 0
door = input("Enter a character from A to Z representing the door you wish to open:")
while miss < 3:
if len(door) > 0:
jackpot = random.randint(0, 1)
if jackpot == 1:
prizeMoney = random.randint(500, 1000)
total = total + prizeMoney
print("Behind Door", door, " is", prizeMoney, "$")
elif jackpot == 0 :
print("Sorry, there is no hidden money behind Door", door, ".This is a miss.")
miss = miss + 1
print()
play = input("Do you wish to quit (1) or open another door (2)?")
if play == "2" and miss <= 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
play == "1"
print("Congratulations!! You have won $", total, ".")
else:
miss == "3"
print("Sorry the game is over. You win $", total, ". Try again.")
else:
print("try again")
Try this code see if this works, there were lots of mistakes I added break statements and refined the logic
import random
total = 0
miss = 0
prizeMoney = 0
door = input("Enter a character from A to Z representing the door you wish to open:")
while miss < 3:
if len(door) > 0:
jackpot = random.randint(0, 1)
if jackpot == 1:
prizeMoney = random.randint(500, 1000)
total = total + prizeMoney
print("Behind Door", door, " is", prizeMoney, "$")
play = int(input("Do you wish to quit (1) or open another door (2)?"))
if play == 2 and miss < 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
print('only 3 miss allowed or you pressed quit')
print("Congratulations!! You have won $", total, ".")
break
elif jackpot == 0 :
print("Sorry, there is no hidden money behind Door", door, ".This is a miss.")
miss = miss + 1
play = int(input("Do you wish to quit (1) or open another door (2)?"))
if play == 2 and miss < 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
print('only 3 miss allowed or you pressed quit')
print("Congratulations!! You have won $", total, ".")
break
else:
print("try again")
break

How do I get or initialize the variable that I want?

I'm trying to write a simple program, but I meet a problem that the program does not output the given variable "tax" in the end.
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
tax = total*0.06
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
when you initialized tax, you gave it a value of 0 because total*0.06 at that point equaled zero.
python goes line by line so the variable "tax" didn't change its value for the whole code, you only changed "total".
so to get the tax, you should calculate it again.
print("Current total: $",total)
tax=0.06*total
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
Here the value of total gets updated but the tax is calculated before the check as given below, hence tax will output tax = total*0.06 where initially total=0
Please try this:
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = tax = 0
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
tax = total*0.06
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
I guess your problem is solved.Also start using python dictionary instead of using lots of if else statements
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
tax = total*0.06
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
price_dict = {
1: menu1,
2: menu2,
3: menu3,
4: menu4
}
if 0 < choose < 5:
total += price_dict[choose]
else:
if choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $",total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
tax = total*0.06
print("Current total: $",total)
print("Sales tax: $",tax)
print("Total Bill: $",total+tax)
print("Have a nice day!")
main()
Now your tax is always 0. You have to calculate the tax at the end. Like this:
def main():
# define and initialize constants and variables
menu1 = 6
menu2 = 2.5
menu3 = 1.25
menu4 = 3.75
choose = total = 0
# display welcome
print("Welcome to Yum Yum Snack Bar!")
try:
while choose != 5:
print("\nPlease choose from the following menu:")
print("1) Personal Pizza $6.00")
print("2) Pretzel $2.50")
print("3) Chips $1.25")
print("4) Hot Dog $3.75")
print("5) Exit ")
choose = int(input("\nEnter your choice here: "))
if choose == 1:
total += menu1
elif choose == 2:
total += menu2
elif choose == 3:
total += menu3
elif choose == 4:
total += menu4
elif choose == 5:
continue
else:
print("Invalid choice. Must choose 1 – 5. Try again.")
print("Current total: $", total)
except:
print("Invalid choice. Must choose 1 – 5. Try again.")
main()
print("Current total: $", total)
tax = total * 0.06
print("Sales tax: $", tax)
print("Total Bill: $", total + tax)
print("Have a nice day!")
main()

Crude virtual shop project fails when selection item from dictionary

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.

Categories