python - 在 Python 上使用 if 语句和追加的问题
问题描述
我对编码比较陌生,我对为什么我的代码不起作用感到非常困惑,它看起来应该但它没有。它首先询问所需的座位数量,然后询问那里的名字,然后询问食物的选择。它很好地附加了名称,但它只附加了第一个食物选择,之后什么也没有。我没有收到任何错误。
这是我的代码:
people = []
working = False
seatNum = input("How many seats do you need: ")
while (not seatNum.isnumeric()):
print("Invalid")
seatNum = input("How many seats do you need: ")
print("Mince pie = 1, Chocolate coins = 2, Apple pie = 3")
seatNum = int(seatNum)
for i in range(seatNum):
Nam = input("Enter name: ")
people.append(Nam)
choice = input("Enter your choice: ")
while (working == False):
while (not choice.isnumeric()):
print("Invalid")
choice = input("Enter your choice: ")
choice = int(choice)
if choice == 1 or choice == 2 or choice == 3:
working = True
else:
print("Enter number between 1-3")
choice = input("Enter your choice: ")
if choice == 1:
people.append("Mince Pie")
elif choice == 2:
people.append("Chocolate coins")
elif choice == 3:
people.append("Apple pie")
print(people)
那是我的代码非常混乱,但还没有完成。这是输出:
How many seats do you need: 3
Mince pie = 1, Chocolate coins = 2, Apple pie = 3
Enter name: a
Enter your choice: 1
Enter name: b
Enter your choice: 2
Enter name: c
Enter your choice: 3
['a', 'Mince Pie', 'b', 'c']
这是所需的输出:
How many seats do you need: 3
Mince pie = 1, Chocolate coins = 2, Apple pie = 3
Enter name: a
Enter your choice: 1
Enter name: b
Enter your choice: 2
Enter name: c
Enter your choice: 3
['a', 'Mince Pie', 'b', 'Chocolate coins', 'c', 'Apple pie']
任何和所有的帮助表示赞赏。提前致谢
塔利亚。
解决方案
运行 '''While(working == False)''' 循环后。您在循环内设置了 working = True 。下一次为下一个人运行循环时,working 仍然等于 True。所以循环不会运行。试试这个部分代码:
#Add your original code
for i in range(seatNum):
Nam = input("Enter name: ")
people.append(Nam)
choice = input("Enter your choice: ")
working = False #This statement is what I added
while (working == False):
while (not choice.isnumeric()):
print("Invalid")
choice = input("Enter your choice: ")
choice = int(choice)
#Continue your code normally
这样,每次循环运行时,工作变量都将为 False 并且循环将能够运行。
推荐阅读
- json - 如果存在,如何从 JSON 中获取特定值
- r - 使用R、dplyr和rowwise时如何定义一个变量来记录处理的行数?
- php - 紧凑():未定义的变量:运算符 - Laravel
- selenium - Selenium Headless Firefox - 非常慢
- python-3.x - Skimage RAG 合并灰度图像
- node.js - 卡在 Node.js 中的 oracle Ref 光标
- vue.js - 条目模式“'./src/components/*.vue'”不匹配任何文件/构建 Web 组件 VUEJS
- sql-server - 比较两个不同列的时间并创建显示时间差异的第三列
- c# - 无法在 Interop.QBFC13.IQBSessionManager 从注册表中读取密钥(HRESULT 异常:0x80040150 (REGDB_E_READREGDB))
- python - 从生成器对象保存图像 - Python