Using Integers With Dictionary To Create Text Menu (switch/case Alternative)
I am working my way through the book Core Python Programming. Exercise 2_11 instructed to build a menu system that had allowed users to select and option which would run an earlier
Solution 1:
I finally found a solution to the problem of sorting a dictionary and printing the function names as a string. In the last part of the edited question (3rd code section), I had the fixed code for the question that started this post: how to use integers in a dictionary to create a menu - with the intention of creating a switch/case style alternative and avoiding the ugly if/elif/else problems in the first code section.
Here's the final version of the working code:
import os
defmenu_system():
os.startfile("cpp2_11alt.py")
defloopCount_zero_to_ten():
os.startfile("cpp2_5b.py")
defpositive_or_negative():
os.startfile("cpp2_6.py")
defprint_a_string_one_character_at_a_time():
os.startfile("cpp2_7.py")
defsum_of_a_tuples_values():
os.startfile("cpp2_8.py")
defrefresh_the_menu():
for x in range(4): print(" ")
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
for z in range(2): print(" ")
defexit_the_program():
quit()
deferrhandler():
print("not sure what you want")
actions = {'1':menu_system,
'2':loopCount_zero_to_ten,
'3':positive_or_negative,
'4':print_a_string_one_character_at_a_time,
'5':sum_of_a_tuples_values,
'x':exit_the_program,
'm':refresh_the_menu}
for key in sorted(actions):
print (key, '=>', actions[key].__name__)
selectedaction = input("please select an option from the list: ")
whileTrue:
actions.get(selectedaction,errhandler)()
selectedaction = input("please select an option from the list: ")
quit()
adding the .__name__
method allowed me to print the function names as a string.
Using the for loop:
for key insorted(actions):
print (key, '=>', actions[key].__name__)
created the ability to sort the dictionary.
Post a Comment for "Using Integers With Dictionary To Create Text Menu (switch/case Alternative)"