python - 函数不返回任何值 - 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”然后再次循环菜单直到我退出。
解决方案
目前,当您选择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!")
推荐阅读
- php - Laravel 6:找不到驱动程序
- php - Spatie 权限:Laravel 中多个页面上的多个角色
- r - 在并排箱线图中组合时,添加颜色美学会改变 geom_text 的位置
- python - Python验证消息是否在指定秒内发送
- measure - Halcon - 相对于校准地平面的垂直测量平面
- javascript - 检查 n 深度 POJO 中的所有属性不为空
- vim - 如何从一个单词删除到行尾
- c++ - 指向成员函数或模板上下文中的静态函数的指针
- java - 如何使用 PowerMockito 在 Java 中模拟 set 方法以获取正确的布尔返回类型?
- java - 将 Hashmap 写入文件