Jacob Quam Jacob Quam - 9 months ago 28
Python Question

Python main() not executing properly

In my python program, I have multiple functions defined, then a main function that also holds the menu. The menu is the first thing that should be displayed, but the program is attempting to run the defined functions that are before the main function, first. This is resulting in many problems. Any suggestions.

#!usr/bin/env python
import operator

saved_string = ''


def remove_letter():
return

def num_compare():
return

def print_string():
print saved_string
return

def calculator():
sign_dict = {"+": operator.add(), "-": operator.sub(), "*": operator.mul(), "&": operator.div()}

num1 = int(raw_input("First number: "))
sign = str(raw_input("Action: "))
num2 = int(raw_input("Second number: "))


print sign_dict[sign] (num1, num2)



return

def accept_store():
global saved_string
saved_string = str(raw_input("Enter string: "))
return

def main():
opt_list = [accept_store(),
calculator(),
print_string(),
num_compare(),
remove_letter()]

while(True):
print "SELLECT OPTIONS:"
print "1\tAccept and Store"
print "2\tCalculator"
print "3\tPrint String"
print "4\tNumber Compare"
print "5\tRemove Letter"
opt_choice = int(raw_input("SELLECTION: "))
opt_choice -= 1
opt_list[opt_choice]()


return


main()

Answer Source

() is a function call notation. So in opt_list, you're listing all the function calls, not the function names. You'd have to change it to:

opt_list = [fn1, fn2, ...]

Then call each function like:

for f in opt_list:
    f()