I remember it very clearly, I posted this content, but I don't know why it's gone.
Record#
- Today I learned about backtracking, try except.
- try and except are a pair and need to appear together.
- Basic logic: try code except code when there is an error.
- Use
except Exception as err:
print(err) to print error messages. - Set debug mode on the first line, debugMode = False.
- if debugMode: print(traceback)
- This makes it easy to control whether to display system error messages.
- Today's exercise is to write an order list for a pizza shop, with the following points:
- Use the name as the dictionary key for the order information, and other information as the dictionary value. Write it to a local file in this format after converting to a string.
- Because it is writing a dictionary, you need to read it first, assign it to the dictionary, write new data, and then save it.
- Use eval() when reading.
- Use a for loop to view, first key, value in item(), this is an operation on the dictionary. Since the value is an array, just use for name, print name.
- The correct answer does not use a dictionary, but a two-dimensional array, which is relatively simpler. Just use array.append.
CODE#
import os, time
debugMode = False
print("🌟Dave's Dodgy Pizzas🌟")
again="y"
def addpiz():
uname = input("Name please > ")
try:
piznum = int(input("How many pizzas? > "))
except:
piznum = int(input("You must input a numerical character, try again. > "))
pizsize = input("What size? s/m/l > ").lower()
if pizsize == "s":
pizcost = 1.99
elif pizsize == "m":
pizcost = 9.99
elif pizsize == "l":
pizcost = 19.99
toping = input("toping please > ")
total = pizcost*piznum
print(f"Thanks {uname}, your pizzas will cost {total}")
try:
f = open("piz.list","r")
pizlist = eval(f.read())
f.close()
except:
pizlist={}
pizlist[uname]=[toping,pizsize,piznum,total]
f = open("piz.list","w")
f.write(str(pizlist))
f.close
def viewpiz():
try:
f = open("piz.list","r")
pizlist = eval(f.read())
f.close()
except:
print("The piz list is empty.")
time.sleep(2)
print(f"{'Name': ^10}{'Topping': ^10}{'Size': ^10}{'Quantity': ^10}{'Total': ^10}")
for key,value in pizlist.items():
print(f"{key: ^10}",end="")
for name in value:
print(f"{name: ^10}",end="")
print()
try:
f = open("piz.list","r")
pizlist = eval(f.read())
f.close()
except:
print("The piz list is empty.")
time.sleep(2)
os.system("clear")
while True:
if again == "y":
menu = int(input("1. Add\n2. View\n"))
if menu == 1:
addpiz()
elif menu == 2:
viewpiz()
again = input("again? y/n")