如何在 python3 中的不同行上打印每个迭代?

How do I print each iteration on separate lines in python3?

编码新手,一名学生,我正在尝试获得此输出:

    Line 1: input from user
              
    Line 2: input from user
                
    Line 3: input from user
                
    Line 4:input from user

    etc.

这是我的代码

sample

现在它只打印进入循环的最后一次迭代,我需要它在循环结束时在单独的行上打印每个迭代,无论它循环多少次。

将您的打印语句放入循环中:

while True:
   ...
   print(f"Line {counter}: {addLine}")

我稍微修改了你的代码:

user_input = ''
add_line = []

while True:
    user_input = input('Would you like to enter new lines?: ')

    if user_input == 'yes':
        add_line.append(input('Please enter your line: '))
    
    if user_input == 'no':
        break

print('Verse')
for i in add_line:
    print(f'Line {add_line.index(i) + 1}: {i}')

测试运行:

Would you like to enter new lines?: yes
Please enter your line: this is a line
Would you like to enter new lines?: yes
Please enter your line: another line
Would you like to enter new lines?: no
Verse
Line 1: this is a line
Line 2: another line

因为您正在打印来自 while 循环的 addLine,它只会打印中断 while 循环之前的最后一个输入。要解决此问题,请将 addLine 更改为列表,然后每次都将所有输入添加到列表中。然后,在打破 while 循环后,将代码放入 for 循环中,以便它打印列表 addLine 中的每个项目。 for 循环需要针对 counter 中的每个数字,从 0 开始。例如,如果您输入 5 个输入,那么它将从 0-4 运行,所以打印该行然后数字是 counter+1 所以它是 1-5 而不是 0-4。然后只需添加 addLine[num] 以便它从列表中获取正确的项目。

userInput = ''
counter = 0
addLine = []
lineNumber = 0
newLine = ''

while True:
    userInput = input('Would you like to enter more lines?: ')

    if userInput == 'yes':
        addLine.append(input('Please enter your line: '))
        counter += 1
    elif userInput == 'no': 
        break

print('Verse')
for num in range(counter):
    print('Line ' + str(num + 1) + ': ' + addLine[num])

经过一些测试,这应该可以工作。