Python Forum
'else' statement not executing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'else' statement not executing
#2
Change

main_opt = ['opt1', 'opt2', 'opt3']
to
main_opt = [opt1, opt2, opt3]
and

main_opt[choice - 1] + '()'
to

main_opt[choice - 1]()
your code

main_opt[choice - 1] + '()'
just creates a string that you don't use at all -i.e. you don't assign it to a variable.

Of course you can always do

eval(main_opt[choice - 1] + '()')
Actually, I would do

#!/usr/bin/env/python3

def opt1():
   print("in opt 1")
   return


def opt2():
   print("in opt 2")
   return


def opt3():
   print("in opt 3")
   return


def main_mnu():
   print('This is the Main Menu. Please make a selection.')
   print('    1) opt1')
   print('    2) opt2')
   print('    3) opt3')

   main_opt = {'1':opt1, '2':opt2, '3':opt3}

   while True:
       choice = input('Enter choice: ')
       try:
            main_opt[choice]()
            break
       except KeyError as err:
            print('Not an option, try again.', err)


if __name__ == '__main__':
   main_mnu()
Reply


Messages In This Thread
'else' statement not executing - by sparkz_alot - Jul-19-2017, 08:22 PM
RE: 'else' statement not executing - by buran - Jul-19-2017, 08:30 PM
RE: 'else' statement not executing - by sparkz_alot - Jul-20-2017, 12:03 AM
RE: 'else' statement not executing - by ichabod801 - Jul-20-2017, 01:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  if /else statement not executing correctly bluethundr 3 2,859 Apr-15-2019, 10:20 PM
Last Post: bluethundr
  if-elif-else statement not executing laila1a 4 3,148 Jan-05-2019, 02:22 PM
Last Post: buran
  print() statement not executing.. bmohanraj91 3 3,762 May-01-2017, 03:56 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

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