Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
menu while loop
#11
I changed myApp() to only accept unique product ids.

You should be able to copy and paste myApp() directly in your Python shell, like Idle, then just write myApp() in your shell and press enter.

You just need to change mypath for your path.

def myApp():
    # Step 1
    # get the modules
    import json
    from pathlib import Path

    """
    When you load the .json file with data = json.load(f) you have a dictionary of dictionaries
    the key is the product id and the value is another dictionary with product info
    """
    # you can use a list here and give the user the chance to choose the path he or she wants
    mypath = '/home/pedro/temp/product_data_json.json'
    
    # check if the json you want exists
    chk_file = Path(mypath) 
    if chk_file.is_file():
        print(mypath, 'exists, so open it')
        with open(mypath) as f:
            data = json.load(f)
    else:
        print("File does not exist, so make data an empty dictionary!")
        data = {}     

    # show the data so far
    for item in data.items():
        print(item)
        if len(data) == 0:
            print('No data yet!')

    # collect data
    # this is a list of things we need to know about each product
    
    collect_data = ['name', 'producer','category','price', 'stock']

    # a function to collect our data
    # this function appends product data to the dictionary 'data'
   
    def get_product_data():
        product_dict = {}
        print('First get product_id and check it ... ')
        product_id = input('Please enter the product_id: ')
        # check if this key exists, if so, don't accept it
        # the product_id must be unique, so use the dict.get(key) method
        while not data.get(product_id) == None:
            print('This product id is already in use, try again.')
            product_id = input('Please enter the product_id: ')
        # now we have a unique product_id    
        for info in collect_data:            
            product_dict[info] = input(f'Please enter the {info}: ')
        data[product_id] = product_dict
        

    replies = ['yes', 'no']
    reply = 'X'
    # still need a way to keep the product ids unique!!
    while not reply in replies:    
        print('Do you want to enter a product?')
        reply = input('Enter yes to continue, enter no to stop ')
        if reply == 'yes':
            answers = get_product_data()
            reply = 'maybe'
        elif reply == 'no':
            break

    for key in data.keys():
        print('Product ID is', key)
        print('Product is:', data[key]['name'])
        print('Product category is:', data[key]['category'])
        
    
    # save the data dictionary as a .json file
    # USE YOUR PATH    
    # open 'w' and overwrite the existing file
    print('Now saving the product data, run myApp() again to add more products later ... ')
    with open(mypath, 'w') as json_file:
      json.dump(data, json_file)
    print('data saved to', mypath)
    # open the file you just saved in mypath
    # USE YOUR PATH
    print('Now reopening', mypath, 'to have a look at the data ... ')
    with open(mypath) as f:
      data = json.load(f)

    print('data is ' + str(len(data)) + ' entries long')

    # look at the content of '/home/pedro/winter2020/20PY/json/user_data_json.json'

    for item in data.items():
        print(json.dumps(item, indent = 4, sort_keys=True))

    """
    You can open and append to this json file any time
    Make another json file for clients
    """
Reply
#12
(Dec-17-2021, 07:03 PM)BashBedlam Wrote: You're headed for trouble. If you keep going like that you will have to create a differentif/eliflist for every menu. Let's organize a little differently. In this code we have oneoperate_menufunction that accepts a tuple of two lists. One list is the options to display for the menu and the other is a list of the command associated with those options. You can change the command that any menu item calls by changing the command in the command list. I've included adummy_functionas a place holder for the commands that you will be using.
Please let me know if you need any further help with this. Smile
products = ['product_id', 'name', 'producer','category','price', 'stock']
clients = ['cnp', 'last_name', 'first_name', 'age']

def operate_menu (menu_tuple) :
	acceptable_options = {'1': 0, '2': 1, '3': 2, '4': 3, '0': 4}
	display_list = menu_tuple [0]
	command_list = menu_tuple [1]
	while True :
		print ('\n----------------------')
		for item in display_list :
			print (item)
		option = input ('Enter your option: ')
		if option in acceptable_options :
			exec (command_list [acceptable_options [option]])
		else :
			print (f'\n{option} is not an acceptable option.')

def exit_the_program () :
	print("\n\nFinished!")
	exit () 

def dummy_function () :
	print ('\nThis is just a place holder function.\n')

products_menu = ((
	"[1] Add new product",
	"[2] Product update",
	"[3] Delete product",
	'[4] Go back to main page',
	"[0] Exit the program."),
	('dummy_function ()',
	'dummy_function ()',
	'dummy_function ()',
	'operate_menu (main_menu)',
	'exit_the_program ()'))
 
clients_menu = ((
	"[1] Add new client",
	"[2] Client update",
	"[3] Delete client",
	'[4] Go back to main page',
	"[0] Exit the program."),
	('dummy_function ()',
	'dummy_function ()',
	'dummy_function ()',
	'operate_menu (main_menu)',
	'exit_the_program ()'))

display_menu = ((
	"[1] Search list of: ",
	"[2] Search a: ",
	"[3] No operation.",
	'[4] Go back to main page',
	"[0] Exit the program."),
	('dummy_function ()',
	'dummy_function ()',
	'dummy_function ()',
	'operate_menu (main_menu)',
	'exit_the_program ()'))

reports_menu = ((
	"[1] Average age of clients: ",
	"[2] The average price of the products ",
	"[3] No operation.",
	'[4] Return to the main menu',
	"[0] Exit the program."),
	('dummy_function ()',
	'dummy_function ()',
	'dummy_function ()',
	'operate_menu (main_menu)',
	'exit_the_program ()'))

main_menu = ((
	"[1] Products",
	"[2] Clients",
	"[3] Display",
	'[4] Report',
	"[0] Exit the program."),
	('operate_menu (products_menu)',
	'operate_menu (clients_menu)',
	'operate_menu (display_menu)',
	'operate_menu (report_menu)',
	'exit_the_program ()'))
 

operate_menu (main_menu)
Can you explain this line 'acceptable_options = {'1': 0, '2': 1, '3': 2, '4': 3, '0': 4}'?
'1' is position of element in tuple[1]?
Reply
#13
(Dec-28-2021, 12:58 PM)3lnyn0 Wrote: Can you explain this line 'acceptable_options = {'1': 0, '2': 1, '3': 2, '4': 3, '0': 4}'?
I'm using a dictionary to lookup the indexes formenu_tuple. I did that for two reasons.
1) So I don't have to convert the input from a string to an integer
2) Zero is the fourth element inmenu_tuple.
Edit:
3) It filters unwanted input like '7'.
3lnyn0 likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020