InsideDarkWeb.com

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.

Stack Overflow Asked by excj5 on November 18, 2021

6 Answers

6 Answers

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

Answered by Sam Morgan on November 18, 2021

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

Answered by Rob Raymond on November 18, 2021

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

Answered by Albert Alberto on November 18, 2021

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)

Answered by user13973539 on November 18, 2021

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

Answered by MatthewProSkils on November 18, 2021

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.

Answered by jdaz on November 18, 2021

Add your own answers!

Related Questions

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.