gpt4 book ai didi

python - 如何对循环进行 "restart"以便两个 Python 列表在程序结束之前完成?

转载 作者:行者123 更新时间:2023-12-01 08:46:49 25 4
gpt4 key购买 nike

我正在尝试创建一个程序,其中用户将 3 个水果和 3 个非水果输入到两个不同的列表中。

用户首先通过输入“fruits”或“nonfruits”来选择第一个列表。然后,用户输入每个符合条件的项目,直到第一个列表已满。

我的问题是,一旦第一个选定的列表已满,程序就会结束。我希望提示用户将数据输入到另一个列表中,直到它也已满。

我认为添加“while len(fruits) < 3 and len(notfruits) < 3:”会起作用,但似乎没有什么区别。

我该怎么做?

fruits = []
notfruits = []
print(fruits)
print(notfruits)
print("Please enter fruits or notfruits:")
y = str(input(": "))
while len(fruits) < 3 and len(notfruits) < 3:
if y == "fruits":
while len(fruits) < 3:
x = str(input(": "))
x = x.strip()
if x in notfruits:
print(x + " is not a fruit!")
elif x in fruits:
print(x + " is already in the list!")
else:
fruits.append(x)
print(fruits)
elif y == "notfruits":
while len(notfruits) < 3:
x = str(input(": "))
x = x.strip()
if x in fruits:
print(x + " is a fruit!")
elif x in notfruits:
print(x + " is already in the list!")
else:
notfruits.append(x)
print(notfruits)
else:
print("Not a valid option!")

最佳答案

  1. 考虑使用or代替and
  2. 将输入部分移动到循环内,否则y将永远不会改变

这就是我的意思:

fruits = []
notfruits = []
print(fruits)
print(notfruits)

while len(fruits) < 3 or len(notfruits) < 3: # replaced `and` with `or`
print("Please enter fruits or notfruits:") #
y = str(input(": ")) # moved the input here
if y == "fruits":
while len(fruits) < 3:
x = str(input(": "))
x = x.strip()
if x in notfruits:
print(x + " is not a fruit!")
elif x in fruits:
print(x + " is already in the list!")
else:
fruits.append(x)
print(fruits)
elif y == "notfruits":
while len(notfruits) < 3:
x = str(input(": "))
x = x.strip()
if x in fruits:
print(x + " is a fruit!")
elif x in notfruits:
print(x + " is already in the list!")
else:
notfruits.append(x)
print(notfruits)
else:
print("Not a valid option!")

关于python - 如何对循环进行 "restart"以便两个 Python 列表在程序结束之前完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53269313/

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