首页 > 解决方案 > 函数不返回任何值 - Python

问题描述

我写了一个菜单函数,它循环直到用户按 3 退出。但是当用户通过按 1 或 2 询问其他选项时,我希望它打印一些东西。这是我的代码:

def Menu():
    return("\n"
          + "Menu:\n-------------"
          + "\n1 - Does This"
          + "\n2 - Does That"
          + "\n3 - Quit"
          + "\n")
    if option == 1:
        return "\nThis"
    if option == 2:
        return "\nThat"

option = None
while True:
    print(Menu())
    option = int(input("Please choose an option: "))
    if option == 3:
        print("\nBye!")
        break
    if option < 1 or option > 3:
        print("\nIncorrect input!")

按 1 时不会出现“This”,按 2 时不会出现“That”,它只是再次循环菜单,直到我按 3 退出。

这是我当前的输出:

Menu:
-------------
1 - Does This
2 - Does That
3 - Quit

Please choose an option: 1

Menu:
-------------
1 - Does This
2 - Does That
3 - Quit

Please choose an option: 2

Menu:
-------------
1 - Does This
2 - Does That
3 - Quit

Please choose an option: 3

Bye!

我想要的结果只是让它打印“This”或“That”然后再次循环菜单直到我退出。

标签: python

解决方案


目前,当您选择1或时2,您的 while 循环将再次执行。您需要实现用户输入有效值的代码。

只是为了澄清,因为你在你的Menu()函数中返回,这些行永远不会被击中,

if option == 1:
    return "\nThis"
if option == 2:
    return "\nThat"

编辑

这是一个改进的工作版本,

input_string = """Menu:-------------
1 - Does This"
2 - Does That"
3 - Quit
Please choose an option:"""

def Menu(option):
    if option == "1":
        return "\nThis"
    if option == "2":
        return "\nThat"

while True:
    option = input(input_string)
    if option in {"1","2"}:
        print(Menu(option))

    elif option == "3":
        print("\nBye!")
        break
    else:
        print("\nIncorrect input!")

推荐阅读