【问题标题】:Global name 'method' is not defined (Difficulty passing parameter) [closed]未定义全局名称“方法”(传递参数困难)[关闭]
【发布时间】:2015-03-23 14:13:49
【问题描述】:

我已经定义变量'method'的值并将其返回给一个名为method_menu的函数,然后尝试将它解析到main。我已经尝试了很多事情,但我无法弄清楚我哪里出错了。

这是我定义并返回“方法”的函数:

def method_menu():
    #caeser or frequency
    print()
    print(".-METHOD MENU-----------------.")
    print("|                             |")
    print("|  (C) Caesar Cipher          |")
    print("|  (F) Frequency              |")
    print("|  (Q) Quit                   |")
    print("|                             |")
    print("`-----------------------------'")
    method = input("Press 'C' or 'F'").lower()
    return method

这里是 main(尝试使用第 15 行和第 19 行的变量)我最初认为我必须使用 def main(method, text) 解析参数,但它无法识别:

def main():
    # the main menu loop
    while True:

        # show the main menu and save their choice
        main_choice = main_menu(main_menu)

        # when they choose to quit break out of the infinite loop
        if main_choice == 'q':
                break

        # user chooses to cipher
        elif main_choice == 'c':
                method_menu(method,text)

        # user chooses to decipher
        elif main_choice == 'd':
                method_menu(method,text)

        else:
                print("Error - choice not recognised")

如果对任何人有用的话,这里是完整的程序:http://pastebin.com/e2M8K9Pa

有人能告诉我如何正确地将参数解析为 main 吗?

【问题讨论】:

    标签: python parameters parameter-passing


    【解决方案1】:

    您将main_menu() 函数调用的返回值分配给名称main_choice,而不是method

    main_choice = main_menu(main_menu)
    

    只需将 那个 传递给 method_menu()

    elif main_choice == 'c':
        method_menu(main_choice, text)
    
    elif main_choice == 'd':
        method_menu(main_choice, text)
    

    您现在将收到 text 的名称错误;您永远不会在任何地方调用 get_source() 函数,也不会将任何内容分配给 text

    接下来,method_menu() 实际上不带任何参数;在您实际加密或解密之前,该函数要求提供更多选项。调用函数没有参数,然后根据返回值继续你的程序。大概你也想打电话给source_menu()

    【讨论】:

    • 不。 OP上面代码块中的函数是method_menu,不带参数。
    • @Carsten: 对,但是text 也没有定义,这将是 first 错误。 method_menu() 不带任何参数是下一个。
    • 是的,我在某种程度上认为 OP 试图通过将 method 传递给函数来获取 method_menu 的返回值(在函数内部称为 method)一个参数。但如果没有进一步的解释,这就是太多的猜测。
    【解决方案2】:
    1. 函数调用和定义:main_menu 的函数参数与函数同名。必须避免这种情况。def main_menu(main_menu):main_choice = main_menu(main_menu)
    2. 在我们的例子中,不需要在函数main_menu 中传递任何参数。

    3. 变量名:不要使用与函数名相同的变量,代码中main_menumain_menu函数内的变量名。必须避免这种情况。

    4. 变量未定义method 变量未在我们的代码中定义,我们在method_menu(method,text) 行使用。

    5. 函数没有参数method_menu() 函数不接受任何参数,但在代码中我们在调用此函数时提供了两个 method_menu(method,text) 参数,这是错误的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2015-12-22
      相关资源
      最近更新 更多