Question

python programming: Can you please add comments to describe in detail what the following code does:...

python programming:

Can you please add comments to describe in detail what the following code does:

import os,sys,time

sl = []
try:
   f = open("shopping2.txt","r")
   for line in f:
       sl.append(line.strip())
   f.close()
except:
   pass

def mainScreen():
   os.system('cls') # for linux 'clear'
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print(" SHOPPING LIST ")
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print("\n\nYour list contains",len(sl),"items.\n")
   print("Please choose from the following options:\n")
   print("(a)dd to the list")
   print("(d)elete from the list")
   print("(v)iew the list")
   print("(q)uit the program")
   choice = input("\nchoice: ")
   if len(choice) > 0:
       if choice.lower()[0] == "a":
           addScreen()
       elif choice.lower()[0] == "d":
           deleteScreen()
       elif choice.lower()[0] == "v":
           viewScreen()
       elif choice.lower()[0] == "q":
           sys.exit()
       else:
           mainScreen()
   else:
       mainScreen()


def addScreen():
   global sl
   os.system('cls') # for linux 'clear'
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print(" ADD SCREEN ")
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print("\n\n")
   print("Please enter the name of the item that you want to add.")
   print("Press ENTER to return to the main menu.\n")
   item = input("\nItem: ")
   if len(item) > 0:
       sl.append(item)
       print("Item added :-)")
       saveList()
       time.sleep(1)
       addScreen()
   else:
       mainScreen()

def viewScreen():
   os.system('cls') # for linux 'clear'
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print(" VIEW SCREEN ")
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print("\n\n")
   for item in sl:
       print(item)

   print("\n\n")
   print("Press enter to return to the main menu")
   input()
   mainScreen()

def deleteScreen():
   global sl
   os.system('cls') # for linux 'clear'
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   print(" DELETE SCREEN ")
   print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
   count = 0
   for item in sl:
       print(count, " - ", item)
       count = count + 1
   print("What number to delete?")
   choice = input("number: ")
   if len(choice) > 0:
       try:
           del sl[int(choice)]
           print("Item deleted...")
           saveList()
           time.sleep(1)
       except:
           print("Invalid number")
           time.sleep(1)
       deleteScreen()

   else:
       mainScreen()

def saveList():
       f = open("shopping2.txt", "w")
       for item in sl:
           f.write(item+"\n")
       f.close()


mainScreen()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi, In this program first It calls the function mainScreen, In the mainScreen it shows the menu . Here menu has infinate loop.


# importing required libraby files
import os,sys,time

#we declared s1 this is an array type of string to store the data from the file shopping2.txt file
sl = []

# try is an type of exception handling. If suppose in our program shopping2.txt file not available in our system then
# the program will terminate suddenly with some exception which is called abnormal termination.

#if we are use try it will handle the exception. In our program if file not found then it will goto except: and just pass / skip the code.
# you can print like "File ot found" for the knowing the programmer about to fie.

#Here we open a file by using predefined function in python i.e open in this we passed,
#file name and the mode of file. r means read mode. Just we retriving the data from the text file
try:
f = open("shopping2.txt","r")

# line is an local veriable and we get each string from the file (f)
for line in f:
       #we append / add the string int to the s1 string array.
       # strip method is used to remove any empty spaces before the string as well as end of the string.
sl.append(line.strip())
     
   #we should close the file. If we didn't close the file which is already open, might be get exception.
f.close()
except:
pass

#this function / definition called and display the menu .
def mainScreen():
  
   #here cls means clear the screen of console.
os.system('cls') # for linux 'clear'
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print(" SHOPPING LIST ")
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print("\n\nYour list contains",len(sl),"items.\n")
print("Please choose from the following options:\n")
print("(a)dd to the list")
print("(d)elete from the list")
print("(v)iew the list")
print("(q)uit the program")

#here we getting the input from the console. we sholud give like a,d,v and q based on the menu.
choice = input("\nchoice: ")

#It checks the length of entered input and it should be > zero
if len(choice) > 0:
       #if condition is true then it invokes corresponding function.
       # lower method converts if the user enter A then it converts A to 'a'. if user enter 'a' then a to 'a' no issu.
if choice.lower()[0] == "a":
addScreen()
elif choice.lower()[0] == "d":
deleteScreen()
elif choice.lower()[0] == "v":
viewScreen()
elif choice.lower()[0] == "q":
sys.exit()   #if user enter q then it will exit from the entaire prorgram.
else:
mainScreen()   #if user entered another key which is not in our menu. then again it invokes the main function.
else:
mainScreen()    # if conidition is not true it invokes main function. until we press q it will execute continuously.


def addScreen():
   #goabl s1 means we can access s1 from any where in this program and we can use as well as.
global sl
os.system('cls') # for linux 'clear'
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print(" ADD SCREEN ")
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print("\n\n")
print("Please enter the name of the item that you want to add.")
print("Press ENTER to return to the main menu.\n")

#here input fuction takes the input from the user from the consloe and stored in to the item.
item = input("\nItem: ")
if len(item) > 0:   #item lenth should be > zero
sl.append(item)   # we added this item to s1
print("Item added :-)")   # giving an acknowledment for added item succssfully.
saveList()       # invokes the saveList it will save the list of data entered by the user.
time.sleep(1)   #it will wait one second and again invokes the addScreen method. sleep method suspends execution of the current thread for a given number of seconds.
addScreen()
else:
mainScreen()

def viewScreen():
os.system('cls') # for linux 'clear'
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print(" VIEW SCREEN ")
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print("\n\n")
# we print each and every item from the s1 by using for loop.
for item in sl:
print(item)

print("\n\n")
print("Press enter to return to the main menu")  
input()   #here we are not save input from the consloe. We can press enter or any key
mainScreen()   #invokes main menu

def deleteScreen():
global sl
os.system('cls') # for linux 'clear'
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print(" DELETE SCREEN ")
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
count = 0

#here we display the all the list from s1 including with numbers.
#for that we took one count veriable and prits the items along with count number.
for item in sl:
print(count, " - ", item)
count = count + 1   # increasing count value
print("What number to delete?")

#choice is the number of item.
choice = input("number: ")

#as we know try hndle the exceptions.
if len(choice) > 0:
try:
del sl[int(choice)]   #our s1 is an array string type. So based on number we can delete the item from the s1.
print("Item deleted...")
saveList()   # after delete item from the list we should save the current list in s1.
time.sleep(1)   # suspend one second.
except:
print("Invalid number")   # if we gave invalid number then try passed to except: and it prints the Invalid number
time.sleep(1)
deleteScreen()   # again It invokes the delete screen menu.

else:
mainScreen()       # invokes main screen.

# function for save the data in to the s1.
def saveList():
       # we open file shopping2.txt file and we use the mode of w -> writing mode
       # user able to do write the data in to the file
f = open("shopping2.txt", "w")
     
   #we save the item data in to file from the s1 array
for item in sl:
f.write(item+"\n") # write method is used to write the data in to the file.
f.close()   # we should close the file after writing.

#First program will start from here.   

mainScreen()

Hit like if you are happy with this. Instead of hitting dislike, it's better to ask the requirements or doubts.

Please comment below if you have any queries regarding this.

Have a great day.

Add a comment
Know the answer?
Add Answer to:
python programming: Can you please add comments to describe in detail what the following code does:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - dis...

    Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - displays the items in the cart ---------------------------------------------------------------------""" import os os.system('clear') print("\n\nCart Contents:") print("Your selected items:", cart) def catMenu(): #function that displays the category menu """catMenu function - displays the categories user picks from ---------------------------------------------------------------------""" import os os.system('clear') print(""" 1 - Books 2 - Electronics 3 - Clothing d - display cart contents x -...

  • I'm making a To-Do list in Python 2 and had the program running before remembering that...

    I'm making a To-Do list in Python 2 and had the program running before remembering that my professor wants me to put everything in procedures. I can't seem to get it to work the way I have it now and I can't figure it out. I commented out the lines that was originally in the working program and added procedures to the top. I've attached a screenshot of the error & pasted the code below. 1 todo_list = [] 2...

  • Can you add code comments where required throughout this Python Program, Guess My Number Program, and...

    Can you add code comments where required throughout this Python Program, Guess My Number Program, and describe this program as if you were presenting it to the class. What it does and everything step by step. import random def menu(): #function for getting the user input on what he wants to do print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the...

  • Can you please enter this python program code into an IPO Chart? import random def menu():...

    Can you please enter this python program code into an IPO Chart? import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the non-numbers #if user enters letters, then except will show the message, Numbers only! try: c=int(input("Enter your choice: ")) if(c>=1 and c<=3): return c else: print("Enter number between 1 and 3 inclusive.") except: #print exception print("Numbers Only!")...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • Add high level comments throughout the program to explain what each line of code does. Finally,...

    Add high level comments throughout the program to explain what each line of code does. Finally, use a diagramming tool (Visio, Lucidchart, MSPaint, paper & pen) to create a flowchart of the code below. path = "/Users/user1/data/baby_names/" myyear = input("Please provide the year to be searched:") babyname = input("Please provide the baby name to be searched:") babyname = babyname.capitalize() baby_counts = count_babies(myyear, babyname) print("There were {0} boys and {1} girls with that name in {2}".format( baby_counts[0], baby_counts[1], myyear)) def count_babies(year,...

  • Use python to code! Q1 - You need to keep track of book titles. Write code...

    Use python to code! Q1 - You need to keep track of book titles. Write code using function(s) that will allow the user to do the following. 1. Add book titles to the list. 2. Delete book titles anywhere in the list by value. 3. Delete a book by position. Note: if you wish to display the booklist as a vertical number booklist , that is ok (that is also a hint) 4. Insert book titles anywhere in the list....

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • Something is preventing this python code from running properly. Can you please go through it and...

    Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT