By not using print
plus a comma; the comma will insert a space instead of a newline in this case.
Use sys.stdout.write()
to get more control:
import sys
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: sys.stdout.write("*")
else: sys.stdout.write("+")
print
print
just writes to sys.stdout
for you, albeit that it also handles multiple arguments, converts values to strings first and adds a newline unless you end the expression with a comma.
You could also use the Python 3 print()
function in Python 2 and ask it not to print a newline:
from __future__ import print_function
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print("*", end='')
else: print("+", end='')
print()
Alternatively, join the strings first with ''.join()
:
def square(n):
for i in range(n):
print ''.join(['*' if i in (0, n-1) or j in (0, n-1) else '+' for j in xrange(n)])