简体   繁体   中英

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.

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM