Skip to content Skip to sidebar Skip to footer

How To Print A String X Times Based On User Input

Hi, Disclaimer: I am new to python and coding in general I am trying to make a simple application that will print a word a specific number of times. Running my code now, despite my

Solution 1:

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

word = input('Enter your word:')

for i inrange(times):
    print(word)

Solution 2:

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

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

word = input('Enter your word:')

fortime in range(int(times)):
    print(word)

Solution 3:

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

Solution 4:

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.

Post a Comment for "How To Print A String X Times Based On User Input"