gpt4 book ai didi

python - 在 Python 上使用 if 语句和 append 的问题

转载 作者:行者123 更新时间:2023-12-04 01:09:40 24 4
gpt4 key购买 nike

我是编码方面的新手,我非常困惑为什么我的代码无法正常工作,它看起来应该有效,但实际上却没有。它首先询问所需的座位数量,然后询问名称然后选择食物。它很好地附加了名称,但它只附加了第一个食物选择,之后什么都没有。我没有收到任何错误。

这是我的代码:

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):

这个 while 循环在第一个之后不会为客人运行,因为 working 当时被设置为 True 并且不会被重置.

choice = int(choice)

这部分只发生在 while 循环内,所以在第一个之后它永远不会发生在客人身上。

if choice == 1:

因为 choice 仍然是一个字符串,所以这些比较总是失败。

关于python - 在 Python 上使用 if 语句和 append 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65260849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com