P_n
P_n

Reputation: 992

How to return to the main menu in a loop?

I'm wondering if this is the right approach to looping back to the main menu in python. After selecting a choice and completing a task, the script needs to return back to the main menu instead of exiting.

#!/usr/bin/python

def mainmenu():
    print ('1. Scan')
    print ('2. Ping')
    print ('3. Exit')
    print

    choice = int(raw_input('> Enter your choice: '))

    if choice == 1:
       print ('Starting Scan\n')
       mainmenu()
    elif choice == 2:
       print ('Starting Ping\n')
       mainmenu()
    elif choice == 3:
       print ('Exiting\n')
       exit(0)
mainmenu()

This kind of works, but don't think it's the right way.

Upvotes: 1

Views: 6350

Answers (1)

Himanshu Bansal
Himanshu Bansal

Reputation: 486

I would suggest putting the whole function in a while loop to repeat the process.

#!/usr/bin/python

def mainmenu():
    while(True):
        print ('1. Scan')
        print ('2. Ping')
        print ('3. Exit')
        print

        choice = int(input('> Enter your choice: '))

    
        if choice == 1:
            print ('Starting Scan\n')
        elif choice == 2:
            print ('Starting Ping\n')
        elif choice == 3:
            print ('Exiting\n')
            exit(0)
mainmenu()

Using recursion is not recommended for such programs.

Upvotes: 4

Related Questions