Home > database >  I have written a code in python of multiple functions. I'm unit testing my code but the main fu
I have written a code in python of multiple functions. I'm unit testing my code but the main fu

Time:08-01

I have created a program of online selling system. It has a main menu and some options. I have implemented each component as a function. But when I'm running it goes well and shows me the main menu but when I select any option it displays the main menu again. I'm not sure if I'm doing it correctly, I'm just a beginner. Here is code;

def main_menu(): 
    print("=======================================================")
    print("\t\tWelcome to our online System")
    print("=======================================================")
    print("<1> List the available services")
    print("<2> Search for a service")
    print("<3> Purchase a service")
    print("<4> List my services")
    print("<5> Quit ")
    selected_option = int(input("Please select an option from the above:"))
    return selected_option

all_services = { '1': ['MS Word', '$20'], '2':['Photoshop', '$120'],
                  '3':['Music player','$89'], '4': ['Photo Advance', '$99'],
                  }

def option1(argu):
    print('\nThe available services and applications are:\n')                
    for key, value in all_services.items():
        print(key, '-', value[0])
    print("\nThank You!")
def option2():
    service_search = input("\nPlease enter the service name you want to search or a negative number to exit:")
    search_result = {}
    for id, name in all_services.items():
        if service_search in name[0].replace(" ","").lower():
            search_result[id] = name 
    if len(search_result) > 0:
    print('\n',len(search_result), 'services have been found:\n')
    for key, val in search_result.items():
        print('Service ID:', key, '\nService Name:', val[0], '\nCost:', val[1])
    else:
        print('This service is not available')
    another_search = input('Do you want to search for another course (Y/N)?')
    if another_search == 'Y':
        option2()
    elif another_search == 'N':
        main_menu()
    else:
        print('Exit')
def option3():
    print("The available services are:\n")
    for id, name in all_services.items():
        print(id,'-' ,name[0])
    select_option = input('\nPlease select the service code you want to purchase or a negative number to exit:')
    print('\nservice detail:\nName:',all_services[select_option][0], '\nCost:', all_services[select_option][1])
    confirm_purchase = input('\nDo you want to buy this service (Y/N)?')
    if confirm_purchase == 'Y':
        print('Please enter your name and your credit card details:\n')
        customer_name = input('Name: ')
        card_no = input('Card Number: ')
        card_expmo = input('MM: ')
        card_expy = input('YYYY:')
        with open('customer.txt', 'w') as f:
            f.write(customer_name   select_option   all_services[select_option][0]  all_services[select_option][1])
        print('Thank You!\nYou have been purchasing the ',all_services[select_option][0],'.')
        another_purchase = input('Do you want to purchase another service (Y/N)?')
        if another_purchase == 'Y':
           option3()
        else:
           print('Thankyou for purchasing from our online shop')
    elif confirm_purchase == 'N':
        print('\n')
        main_menu()
    else:
        print('Exit')
def option4():
    name_search = input('Please enter your name to search:')
    with open('/content/customer.txt', 'r') as info:
        purchase_details = []
        for line in info:
            line_list = line.split(',')
            purchase_details.append(line_list)
        for i in range(len(purchase_details)):
            if name_search in purchase_details[i][0]:
                print('Hello', name_search,'you have purchased the following:\n')
                print(i,'-',purchase_details[i][2])


if __name__ == '__main__':
  main_menu()
  if main_menu() == 1:
    option1(all_services)
  elif main_menu() == 2:
    option2()
  elif main_menu() == 3:
    option3()
  elif main_menu() == 4:
    option4()
  elif main_menu() == 5:
    print('Goodbye')
  else:
    print('Please enter a valid option')

Following is the output I'm getting from the above code;

=======================================================
         Welcome to our online System
=======================================================
<1> List the available services
<2> Search for a service
<3> Purchase a service
<4> List my services
<5> Quit 
Please select an option from the above:5
=======================================================
        Welcome to our online System
=======================================================
<1> List the available services
<2> Search for a service
<3> Purchase a service
<4> List my services
<5> Quit 
Please select an option from the above:5
=======================================================
        Welcome to our online System
=======================================================
<1> List the available services
<2> Search for a service
<3> Purchase a service
<4> List my services
<5> Quit 
Please select an option from the above:5
=======================================================
        Welcome to our online System
=======================================================
<1> List the available services
<2> Search for a service
<3> Purchase a service
<4> List my services
<5> Quit 
Please select an option from the above:5
=======================================================
        Welcome to our online System
=======================================================
<1> List the available services
<2> Search for a service
<3> Purchase a service
<4> List my services
<5> Quit 
Please select an option from the above:5
=======================================================
        Welcome to our online System
=======================================================
<1> List the available services
<2> Search for a service
<3> Purchase a service
<4> List my services
<5> Quit 
Please select an option from the above:5
Goodbye

CodePudding user response:

Every time you write main_menu() you call the main_menu function and cause the menu to 'repeat itself'.

Try:

if __name__ == '__main__':
  choice = main_menu()
  if choice == 1:
    option1(all_services)
  elif choice == 2:
    option2()
  elif choice == 3:
    option3()
  elif choice == 4:
    option4()
  elif choice == 5:
    print('Goodbye')
  else:
    print('Please enter a valid option')

Note that we only write main_menu() once, so it is only called once. This will fix at least the repeating problem.

You might also want to consider adding a while loop to allow the user to continue using the menu after finishing with an option:

if __name__ == '__main__':
  while True:  
    choice = main_menu()
    if choice == 1:
      option1(all_services)
    elif choice == 2:
      option2()
    elif choice == 3:
      option3()
    elif choice == 4:
      option4()
    elif choice == 5:
      print('Goodbye')
      break
    else:
      print('Please enter a valid option')
  • Related