Wondering if this is the right approach to looping back to main menu in python. After selecting a choice and completing a task, the script needs to return back to 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 its the right way
答案 0 :(得分:2)
I would suggest to the whole function in a while loop 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