在 python 3.8 上运行
当我意识到如果用户尝试进行无效选择时我需要一种方法来“循环”菜单时,我正在创建一个菜单,但最终的 if 语句基本上根本不评估。
def menu():
print("1) Generator Parameters\n2) AI Parameters\n3) Help")
choice = input("\nX ")
# converting choice to an int here
choice = int(choice)
if choice == 1:
clear()
print("You are in the Generator sub-menu")
if choice == 2:
clear()
print("You are in the AI sub-menu")
if choice == 3:
clear()
print("You are in the help sub-menu")
if 0 >= choice > 3:
clear()
print("Please make a valid selection\n")
input()
menu()
我已经查看了类似问题的其他解决方案,但是大多数解决方案使用不同的语言,我无法确定可能的问题。(我是编程新手)
我已经成功地运行了输入 1、2 和 3,但是除了那些之外的任何东西都只是一个空行和一个代码 0。
任何想法为什么我没有得到任何东西?
(clear()是一个函数,使用system.os在命令行中写入“cls”,只是清除CLI)
我建议做两个额外的改变。
改变你的输入行。输入行允许您输入提示,因此您不需要单独的打印语句。您还可以在 int 语句中将选项转换为 int。修改变量并将其重新分配为与之前所做的相同的名称可能会很尴尬。
使用正确的 if、elif、else 格式。由于您的代码当前存在,如果输入 1,您的代码将检查 choice == 1 是否为真,但随后还会检查是否 choice == 2 then choice == 3 then choice < 1 或 choice > 3。使用设置一旦匹配完成,下面的 if 将跳出 if else 并且 else 语句将更好地处理意外结果。
最后,不清楚 clear() 在这里做什么。是自定义方法吗?
choice = int(input("1) Generator Parameters\n2) AI Parameters\n3) Help\n"))
if choice == 1:
clear()
print("You are in the Generator sub-menu")
elif choice == 2:
clear()
print("You are in the AI sub-menu")
elif choice == 3:
clear()
print("You are in the help sub-menu")
else:
clear()
print("Please make a valid selection\n")
input()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句