首页 > 解决方案 > while循环的问题(基于python)

问题描述

我是使用 Python 的新手,我需要一些关于这个 while 循环的帮助:

List=[]
x=str(input("name: "))
y=int(input("mark: "))
List.append(x,y)
while x!="0":
    x=str(input("name: "))
    y=int(input("mark: "))
    List.append((x,y))

这个 while 循环的问题是,当我在 'name:' 后面加上 '0' 来中断循环时,程序不会立即中断:相反,它要求我输入 y ('mark: ') 并在输出它还会打印我的元组 ('0',0)

我会尽量说清楚:

***Expected output:***

name: Lisa

mark: 6

name: John

mark: 8

name: 0

[('Lisa',6),('John',8)]

***My actual output with my code:***

name: Lisa

mark: 6

name: John

mark: 8

name: 0

mark:0  #I put 0 because the program asks me for another int (wrong)

[('Lisa',6),('John',8),('0',0)]

我也试过这段代码,同样的问题:

while True:
    if x=="0":
        break
    else:
         x=str(input("inserisci cognome: "))
         y=int(input("inserisci voto: "))
         List.append((x,y))

标签: pythonpython-3.xwhile-loop

解决方案


这是一个简单的例子。我假设您想将一个元组附加到列表中。在此示例中,while 将永远运行,除非 x 不等于“0”。

List = []

while True:
     x=str(input("inserisci cognome: "))
     if x == "0":
         break
     y=int(input("inserisci voto: "))
     List.append((x,y))

推荐阅读