Reputation: 11
I need to display the following 'FUN' using patterns in Python. The problem I am having is that I need to have them all on a single line with space between each character. I do understand when I use print()
function that it will move to the next line. I tried searching for an example but was not successful.
Below is my code for 'F U N' which will print out in vertical order.
#Pattern F
for row in range(5):
for col in range(7):
if (col==0 or col==1) or ((row==0 or row==2)):
print("F",end="")
else:
print(end=" ")
print()
print()
#Pattern U
for row in range(5): # there are 5 rows
for col in range(7): # 7 columns
if ((col==0 or col==6) and row<3) or (row==3 and (col==1 or col==5)) or (row==4 and col>1 and col<5):
print("U", end="")
else:
print(end=" ")
print()
print()
# Pattern N
for row in range(5):
for col in range(9):
if (col==0 or col==1 or col==6 or col==7) or (row==col-1): #and (col>0 and col<5)):
print("N",end="")
else:
print(end=" ")
print()
Upvotes: 1
Views: 4135
Reputation: 9810
I would go for not printing the characters directly, but rather save them into strings first, using dedicated functions. Once you have these strings, they are easily combined to form words:
def pattern_f():
return [
''.join([
'F' if (col == 0 or col == 1 or row == 0 or row ==2) else ' '
for col in range(7)]) for row in range(5)
]
def pattern_u():
return [
''.join([
'U' if ((col==0 or col==6) and row<3) or (row==3 and (col==1 or col==5)) or (row==4 and col>1 and col<5) else ' '
for col in range(7)]) for row in range(5)
]
def pattern_n():
return [
''.join([
'N' if (col==0 or col==1 or col==6 or col==7) or (row==col-1) else ' '
for col in range(7)]) for row in range(5)
]
##separate printing:
for string in pattern_f():
print(string)
print()
for string in pattern_u():
print(string)
print()
for string in pattern_n():
print(string)
print()
##combining
for f,u,n in zip(pattern_f(), pattern_u(), pattern_n()):
print(f,u,n)
This gives the following output:
FFFFFFF
FF
FFFFFFF
FF
FF
U U
U U
U U
U U
UUU
NN N
NNN N
NN N N
NN N N
NN NN
FFFFFFF U U NN N
FF U U NNN N
FFFFFFF U U NN N N
FF U U NN N N
FF UUU NN NN
Hope this helps.
Upvotes: 1