首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Python上使用if语句和append时出现的问题

在Python上使用if语句和append时出现的问题
EN

Stack Overflow用户
提问于 2020-12-12 10:01:03
回答 3查看 51关注 0票数 3

我对编码比较陌生,我对我的代码为什么不能工作感到非常困惑,它看起来应该工作,但它不是。它首先询问所需的座位数量,然后询问那里的名字,然后是食物选择。它会附加名字,但只会附加第一个食物选项,之后就不会添加任何东西了。我没有收到任何错误。

下面是我的代码:

代码语言:javascript
运行
复制
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)

这就是我的代码,虽然非常混乱,但它还没有完成。下面是输出:

代码语言:javascript
运行
复制
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']

下面是所需的输出:

代码语言:javascript
运行
复制
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']

任何和所有的帮助都是感激的。提前感谢

塔莉亚。

EN

Stack Overflow用户

发布于 2020-12-12 10:14:27

运行‘While(working == False)’循环之后。在循环中设置working = True。下一次为下一个人运行循环时,working仍然等于True。因此循环将不会运行。尝试以下部分代码:

代码语言:javascript
运行
复制
#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,并且循环将能够运行。

票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65260849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档