-2

I am trying to make a simple application that will print a word a specific number of times. I have this code:

# Double Words
times = input('How many times would you like to repeat your word?')
word = input('Enter your word:')
for times in times:
    print(word)

When I run the code, word is only printed once, despite the loop. What is wrong, and how can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

4 Answers4

0
times = int(input('How many times would you like to repeat your word?'))

word = input('Enter your word:')

for i in range(times):
    print(word)
Ironkey
  • 2,568
  • 1
  • 8
  • 30
0

Your code does not work because you use same variable to iterate over the times and better use range():

# Double Words

times = input('Ho w many times would you like to repeat your word?')

word = input('Enter your word:')

for time in range(int(times)):
    print(word)
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

You can use:

for n in range(int(times)):

   print(word)

But this may give you error as if the user enters a non-integer value.

Harsh S.
  • 45
  • 7
0

The easiest way is to do it in one line is the following, no looping required:

times = input('Ho w many times would you like to repeat your word?')
word = input('Enter your word:')

print('\n'.join([word] * int(times)))

'\n'.join() to add a newline between each element.

[word] * int(times) makes a times long list - with each element being word so that you can use join() on it.

Note: If you don't care about the newline between entries, you can just do print(word * int(times)).

Collin Heist
  • 1,962
  • 1
  • 10
  • 21