Alfredo
Alfredo

Reputation: 3

print a character horizontally using the for loop

I'm trying to print characters n numbers of times horizontally, and thus far, I have this code:

#print n times  *

times=input("¿How many times will it print * ? " )

for i in range(times):
  print"* \t"

but the result is this:

¿How many times will it print * ? 5 *
*
*
*
*

How do I make the asterisk print horizontally?

EG:
* * * * * *

Upvotes: 0

Views: 1514

Answers (3)

Zachary Craig
Zachary Craig

Reputation: 2220

That's because by default, python's print function adds a newline after it, you'll want to use sys.stdout.write(), as you can see here

EG:

#print n times  *
import sys
times=input("¿How many times will it print * ? " )

for i in range(times):
  sys.stdout.write("* \t")
#Flush the output to ensure the output has all been written
sys.stdout.flush() 

Upvotes: 0

SsJVasto
SsJVasto

Reputation: 496

You can start by trying this. As far as I know, print() systematically inserts a \n (line break) after each call, so the solution is to call "print()" only once.

#print n times  *

times=input("¿How many times will it print * ? " )

str = ""
for i in range(times):
  str += "* \t"

print(str)

Upvotes: 0

omri_saadon
omri_saadon

Reputation: 10631

First of all you need to cast your input into int.

Second, by adding a comma at the end of your print statement, it will print horizontal.

Also, as you are using python 2.x, you should use raw_input instead of input

times = int(raw_input("How many times will it print * ? " ))

for i in range(times):
  print "* \t",

Output:

*   *   *   *   *   

Upvotes: 1

Related Questions