调用我的函数时不起作用?

时间:2018-12-28 15:15:07

标签: python function

我正在将计算机科学用于GCSE,并且我们有一个项目应交,但是我似乎无法弄清楚如何工作。它告诉我“ NameError:名称'option1'未定义”,即使我定义了它,它似乎也不起作用。如果您可以检查下面的代码并告诉我如何解决问题,并说明如何以及为什么不起作用,我将非常感谢!谢谢! (目前,请不要忽略寄存器和排行榜功能,我自己弄清楚那些我知道登录功能应该如何工作。)

##### login, register or see the leaderboard.
def option():
    option1 = int(input("""Would you like to:
    1. Login
    2. Register
    3. See the Leaderboard"""))

##### MAIN CODE
while choice == True:
    option()

    if option1 == 1:
        login()
        choice = False

    elif option1 == 2:
        register()
        choice = False

    elif option1 == 3:
        leaderboardopen()
        choice = False

    else:
        print("Incorrect value given. Please try again.")

3 个答案:

答案 0 :(得分:1)

您只需要返回所选的选项并在您的主代码中捕获返回的值即可:

##### login, register or see the leaderboard.
def option():
    option1 = int(input("""Would you like to:
    1. Login
    2. Register
    3. See the Leaderboard"""))
    return option1

##### MAIN CODE
choice = True
while choice == True:
    option1 = option()

    if option1 == 1:
        login()
        choice = False

    elif option1 == 2:
        register()
        choice = False

    elif option1 == 3:
        leaderboardopen()
        choice = False

    else:
        print("Incorrect value given. Please try again.")

答案 1 :(得分:0)

您尚未定义choice。另外,您是在函数内部声明option1,因此,当您不在该函数中时,将不会对其进行定义。试试这个,您需要从函数中返回一些信息。

##### login, register or see the leaderboard.

choice = True

def option():
    option = int(input("""Would you like to:
    1. Login
    2. Register
    3. See the Leaderboard"""))
    return option

##### MAIN CODE
while choice == True:
    option = option()
    if option == 1:
        login()
        choice = False

    elif option == 2:
        register()
        choice = False

    elif option == 3:
        leaderboardopen()
        choice = False

    else:
        print("Incorrect value given. Please try again.")

答案 2 :(得分:0)

如上文提到的Robert和Paritosh所述,option1option函数之外并不存在。我可以建议以下解决方案:

def option():
    return int(input("Would you like to:"))

##### MAIN CODE
while choice == True:
    option1 = option()
    if option1 == 1:
        login()
    # continue your logic