Explain to me this code please

import os, time 

pizza = []

try:
  f = open("pizza.txt","r")
  pizza = eval(f.read())
  f.close()
except:
  print("ERROR: No existing pizza list, using a blank list")

def viewPizza():
  h1 = "Name"
  h2 = "Topping"
  h3 = "Size"
  h4 = "Quantity"
  h5 = "Total"
  print(f"{h1:^10}{h2:^20}{h3:^10}{h4:^10}{h5:^10}")
  for row in pizza:
    print(f"{row[0]:^10}{row[1]:^20}{row[2]:^10}{row[3]:^10}{row[4]:^10}")
  time.sleep(2)
  
def addPizza():
  time.sleep(1)
  os.system("clear")
  name = input("Name > ")
  toppings = input("Toppings: ")
  size = input("Size (s/m/l):").lower()
  while True:
    try:
      qty = int(input("Quantity: "))
      break
    except:
      print("Error: Quantity must be a whole number")
  cost = 0
  if size == "s":
    cost = 5.99
  elif size == "m":
    cost = 9.99
  else:
    cost = 14.99
  total = cost * qty
  total = round(total, 2)
  row = [name, toppings, size, qty, total]
  pizza.append(row)



while True:
  time.sleep(1)
  os.system("clear")
  print("Dominos Pizza")
  print()
  menu = input("1: Add Pizza\n2: View pizzas\n>")
  if menu == "1":
    addPizza()
  else:
    viewPizza()
  f = open("pizza.txt","w")
  f.write(str(pizza))
  f.close()
1 Like

what do you want to know? If you don’t know python and your friend/a website/your teacher just gives you this code it says two things:

  • whoever’s teaching you, if they advertised it as for beginners, is not a good teacher
  • go learn python (BASICS) before you attempt this

we can “explain” what is going on but you should learn python first

7 Likes

In my opinion, if you want to learn Python, use Replit’s 100 day coding course!

2 Likes

I will try my best, I’m explaining it from top to bottom, just like how a computer reads it

Line 1: import os, time
It imports package OS and package Time, os for clearing screen, time for pausing

pizza = []
Yep just declaring pizza is a variable that is an empty list

Try except statement:
If you got a pizza.txt, it’s content is now a pizza!
If not, pizza remains empty
(I recommend u use except FileNotFoundError instead of except to prevent catching unexpected error.)

—We now go to While True first, just like a computer, everything below will not indicate which command, we are gonna run one by one anyways

We wait for a second and clear the screen
We print ‘domino pizza’ and a new line
Asking you to type something, u wanna add or view pizza

If you type 1
We add pizza
—jumping back to the function call

We wait another second, clear screen
We ask you for your name, toppings and size
We are going to ask you how many pizza you want, forever
We are gonna try making your answer as a number, and stop asking you forever
(again, use except ValueError not except to avoid capturing the wrong error)
If your answer is not a number, we are gonna ask you again, and repeat it forever
If your size is s(small), your cost is going to be 5.99
If your size is m(medium), your cost is going to be 9.99
If you size is anything else, we don’t care and we are gonna take 14.99 for each pizza you ordered, we just take your cash without mercy

Your total will be your cost times your quantity, and we round it to 2 decimal places
We will store it in pizza, with the order of “name, toppings , size, quantity, total”
— go back

Or… if you type anything other than 1, we would love to let you see our pizza!
Yes we view pizza
—jumping back to function call

We align and title the 5 things we got
We are going to show you the 5 info according to the title(one line one pizza)
We wait 2 seconds
—go back

Ok no matter you view or add our pizza, we are going to delete the entire pizza.txt and create it again with our new pizza informations

We go back, to the top of the while True, and ask you if you wanna add or view pizza, again

Ok and it’s what the program does

2 Likes

By the way I run this code inside my brain, and I used 16 minutes to write this

import os, time 

This line imports the os and time modules, which will be used later in the program.

pizza = [  ]

this line initializes an empty list called pizza, which will contain the list of pizzas.

try:

  f = open("pizza.txt","r")

  pizza = eval(f.read())

  f.close()

except:

  print("ERROR: No existing pizza list, using a blank list")

The code inside the try block attempts to read the contents of a file called pizza.txt using the open() function, which takes in the filename and a mode (“r” for read mode). The contents of the file are then read using the read() function and passed to the eval() function, which basically evaluates a string of code so that it becomes executable code. In this case, the contents of the file should be a list in string format, so eval() converts the string representation of the list into an actual list object, which is then assigned to the pizza list.

If the try block fails due to an error (such as the file not existing), the code inside the except block is executed, which prints an error message and initializes the pizza list as an empty list.

def viewPizza():
   h1 = "Name"
   h2 = "Topping"
   h3 = "Size"
   h4 = "Quantity"
   h5 = "Total"
  print(f"{h1:^10}{h2:^20}{h3:^10}{h4:^10}{h5:^10}")

  for row in pizza:

    print(f"{row[0]:^10}{row[1]:^20}{row[2]:^10}{row[3]:^10}{row[4]:^10}")

  time.sleep(2)

This function, called viewPizza(), just prints out the current list of pizzas in a formatted table. It starts by defining h1, h2, h3, h4, and h5 as header strings for the table columns. Then, it uses a for loop to iterate over each pizza in the pizza list and format the data using the print() function. Finally, the function calls time.sleep(2) to pause for 2 seconds before returning.

def addPizza():

time.sleep(1)

addPizza() is used to add a new pizza to the list. Currently, it just waits for one second using the time.sleep() function to simulate taking input for a new pizza to add to the list. In your implementation, you would add code to properly get input from the user, construct a new row for the list and then append it to the pizza list.

Overall, the script sets up a basic framework for a program that can manage a list of pizzas, but it doesn’t yet do any real pizza management.

Hey, you forgot to scroll down the code block
He got more codes below lol and add_pizza is not useless

No. I am pretty advanced in the Python language, and just for fun, I checked out the course. I think it is sort of okay but defiantly not the best. In my opinion. Get a book. Usborne as a great book on Python!

100 days of code is for people who have only written a few lines of code or know none at all, so this is not a accurate judgement. People who are “pretty advanced in the python language” are not the target audience afaik. It is learn how to code, not learn how to code further with existing extensive knowledge XD

2 Likes

@TaokyleYT @Idkwhttph please stop trying to help him. If this person really can’t understand the entire code, either let them elaborate before giving them a TL;DR or don’t help them in this situation. This code and the concepts needed to explain it (literally the foundations of the code) are not going to make any sense to someone who doesn’t know programming so we could teach this person python from the ground up or just let them elaborate & proceed

2 Likes

What I mean is I think it is a harder way to learn.

Yet it is free. Keep that into account.

It is free along with w3schools, freecodecamp and replit ask.

This Python script maintains a simple pizza ordering system. It starts by attempting to read a list of pizza orders from a file called “pizza.txt” and storing it in the pizza list. If the file doesn’t exist or there is an error, it initializes an empty pizza list.

The script provides two main functions: addPizza allows the user to input details for a new pizza order (name, toppings, size, and quantity) and calculates the total cost, while viewPizza displays the existing pizza orders in a tabular format. The user can choose between these two options in a menu loop. After each operation, the updated pizza list is saved back to the “pizza.txt” file.