cb879
cb879

Reputation: 23

How do I print a character multiple times by a user input number?

My friend and I recently started learning python and we have a task that the both of us are struggling with. The task involves getting a number from the user and printing that many underscores. Example: user entered 8, the the code will print 8 underscores in one line. My code is

num = input('Enter a number: ')

after that, to make it print the underscores I thought it would be something like

print('_'*num)

I tried many variations of that and suggestions from the internet but I still can't get it to work without a syntax error. My friend and I are both very stuck on this, any help appreciated. Feel free to ask questions, I found this hard to explain since I'm new to this.

Upvotes: 1

Views: 3738

Answers (6)

Sam Morgan
Sam Morgan

Reputation: 3318

Many of the responses here are way too complex for a very simple problem. The only issue with your code is that num is a string, not an integer. You cannot multiply two strings, thus this will throw TypeError: can't multiple sequence by non-int of type 'str'. The fix is simple, change the type:

num = input('Enter a number: ')
print("_" * int(num))

Upvotes: 2

MatthewProSkils
MatthewProSkils

Reputation: 380

for i in (0, userinput): print('hello world', end = ') end = is for no newline

Upvotes: -1

Rob Raymond
Rob Raymond

Reputation: 31166

You need to cast the input to an integer

num = int(input("Number"))
"_______________________________"[:num] # substring
"".join(["_" for i in range(num)]) # build array then construct string
"_"*num # string repetition

Upvotes: 1

Albert Alberto
Albert Alberto

Reputation: 950

This is what you are looking for:

i = input("Enter the number: ")  # get input from user
character = "_"
for x in range(int(i)):
    print(character, end="")  # repeat print the specified character. end="" ensurer that all is in one line

Upvotes: 0

user13973539
user13973539

Reputation:

num = int(input("enter: "))

this is inputting the number of times you want the unerscore to be printed.

for i in range(num):

this for loop repeats the code inside n times

print("_", end =" ")

The end =" " makes sure that the next print statement happens on the same line, so the final code would be:

num = int(input("enter: "))
for i in range(num):
   print("_", end =" ")

Hope this helps! (It's my first time answering lol)

Upvotes: 0

jdaz
jdaz

Reputation: 6053

Most likely the issue is you need to use int(input("Enter a number: ")) instead of just input, to convert the input from a string to an integer.

Upvotes: 3

Related Questions