Python main()执行不正确

2024-04-19 08:51:30 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的python程序中,我定义了多个函数,然后一个主函数也包含菜单。菜单是应该显示的第一件事,但是程序首先尝试运行在主函数之前的已定义函数。这导致了许多问题。任何建议。你知道吗

#!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()

Tags: 函数程序inputstringrawreturn定义def
1条回答
网友
1楼 · 发布于 2024-04-19 08:51:30

()是函数调用表示法。所以在opt_list中,列出的是所有函数调用,而不是函数名。您必须将其更改为:

opt_list = [fn1, fn2, ...]

然后按如下方式调用每个函数:

for f in opt_list:
    f()

相关问题 更多 >