不断添加新变量,直到满足条件为止

2024-10-04 03:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一段代码,它将反复添加新变量,直到用户说“不”

当前代码:

fizzydrinks = [] 
max = 0
while max == 0:
    ask = input("Do you want to add an item to the list?")
    if ask == "Y":
        item = input("Enter your fizzy drink to the List: ")
    elif ask =="N":
        max = max + 1
    fizzydrinks.append(item)
    print (fizzydrinks)

此代码的问题在于,当您输入最后一个变量并对添加更多项目说“否”时,它会重复您在列表中输入的最后一个项目

这是输出:

Enter your fizzy drink to the List: Coke
['Coke']
Do you want to add an item to the list?Y
Enter your fizzy drink to the List: Tango
['Coke', 'Tango']
Do you want to add an item to the list?N
['Coke', 'Tango', 'Tango']

Tags: theto代码youanadditemdo
1条回答
网友
1楼 · 发布于 2024-10-04 03:27:34

您需要您的程序在用户输入N后立即退出while循环

fizzydrinks = [] 

while True:
    ask = input("Do you want to add an item to the list?")
    if ask == "Y":
        item = input("Enter your fizzy drink to the List: ")
    else:
        break
    fizzydrinks.append(item)
    print (fizzydrinks)

这将使用典型的while True:循环,并在满足退出条件后立即使用break

相关问题 更多 >