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

Time:09-26

New to coding, a student and I am trying to get this output:

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

    etc.

here is my code

if userInput == 'yes': 
    addLine = input("Please enter your line: ")

    counter = counter   1

if userInput == 'no':
  
  print(f"Line {counter}: {addLine}")

  break 

sample

Right now it only prints the last iteration entered into the loop, I need it to print each iteration on separate lines at the end of the loop no matter how many times it loops.

CodePudding user response:

Because you were printing addLine which came from a while loop, it would only print the last input before breaking the while loop. To fix this, change addLine to a list and then add all the inputs to the list each time. Then, after breaking the while loop, put the code inside a for loop so that it prints for each item in the list addLine. The for loop needs to be for every number in counter, starting at 0. For example if you entered 5 inputs then it would run from 0-4, so print the line and then the number which is counter 1 so it does 1-5 instead of 0-4. Then just add addLine[num] so that it gets the correct item from the list.

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])

After some testing, this should work.

CodePudding user response:

Put your print statement inside the loop:

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

CodePudding user response:

I've reworked your code a little:

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}')

Test run:

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
  • Related