首页 > 解决方案 > 在 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']

任何和所有的帮助表示赞赏。提前致谢

塔利亚。

标签: python

解决方案


运行 '''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 并且循环将能够运行。


推荐阅读