9 Complete the menu: A real program

 

In this chapter

  • Erik and Simon create load and save functions in the main program
  • Simon adds exit functions to the main menu and get_order() function
  • Simon explains why he thinks Erik just created a real program
  • The brothers discuss future plans

“Now let’s get real,” Simon said. “Yesterday, we played with sample orders and simple programs. Today, it’s time to use what you learned in your real program.”

“Yes, let’s do it!” Erik said.

“Open your main_menu.py file, where you wrote the main menu. We should add a couple of functions there to work with the JSON file. Let’s recall what we have to do first.” Simon pulled out his diagram from yesterday.

“We have to write a function that will load the list of orders from a JSON file. But first, it has to check if the file exists. If the file doesn’t exist, we’ll create an empty list and return it from this function. If the file exists, we’ll read from it, convert the JSON file to a Python list, and return that list.

“Let me help you.” Simon felt that it might be a bit confusing for Erik. “Usually, in functions that work with files, we pass the filename as an argument.” Simon started the function at the bottom of the file, right before the last line with main_menu():

def load_orders(filename):

“Now we have to check if the file exists. There is a special function for that, and we can find it in the os module.”

“What is ‘os’?” Erik asked.

New things you have learned today

Code for this chapter