Home > Mobile >  How to implement Repetition with a 'while' loop (python)?
How to implement Repetition with a 'while' loop (python)?

Time:11-16

Write a program that prints a sentence the required number of times (each sentence must start on a new line)

Solved the problem with a (for) loop and tried with a while loop How to solve it with while?

text = input('data input:')
amount = int(input())
for _ in range(amount): 
  print(text)

text = input('data input:') 
amount = int(input())
while True:
     print(text * amount)
     break

CodePudding user response:

You can use a counter that you decrement at each iteration:

text = input('data input:') 
amount = int(input())

while amount>0:
    print(text)
    amount -= 1

Example:

data input:test
3
test
test
test

This is however rarely something that you would do in python, the for loop is probably the canonical way.

Another approach: print(*[text]*3, sep='\n') (but the for loop is preferable in my opinion)

CodePudding user response:

You could try this:

text = input('data input:') 
amount = int(input())
while amount:
     print(text)
     amount -=1

As soon as amount turns to 0, the condition evaluates to False thus ending the loop.

If you want to preserve the value of amount you can declare another temporary variable for handling the loop and assign it the value of amount Something like this:

text = input('data input:') 
amount = int(input())
temp = amount
while temp:
     print(text)
     temp -=1
  • Related