Reputation: 43
1
121
12321
1234321
123454321
1234321
12321
121
1
I can only print stars but have no logic for numbers.
userInput = int(input("Please input side length of diamond: "))
if userInput > 0:
for i in range(userInput):
for s in range(userInput -3, -2, -1):
print(" ", end="")
for j in range(i * 2 -1):
print("*", end="")
print()
for i in range(userInput, -1, -1):
for j in range(i * 2 -1):
print("*", end="")
print()
Upvotes: 2
Views: 3451
Reputation: 9711
Another (very simple) way to handle this is to take advantage of:
For example:
def diamond(n, c=1):
"""Print a diamond pattern of (n) lines.
Args:
n (int): Number of lines to print.
"""
string = f'{int("1"*c)**2:^{n}}'
if c < (n//2)+1:
print(string)
diamond(n=n, c=c+1)
if c <= n:
print(string)
>>> diamond(7)
1
121
12321
1234321
12321
121
1
There are different ideas as to whether n
applies to the number of lines printed, or the center value of the diamond. This example implements the former; but is easily modified to implement the latter.
Upvotes: 0
Reputation: 73470
The following can do this concisely using a helper function:
def up_and_down(n): # 1,2, ..., n, ..., 2, 1
return (*range(1, n), *range(n, 0, -1))
def diamond(n):
for i in up_and_down(n):
print((n-i)*' ', *up_and_down(i), sep='')
>>> diamond(5)
1
121
12321
1234321
123454321
1234321
12321
121
1
Upvotes: 3
Reputation: 1
for i in range (1,6):
for j in range(6-i):
print(" ", end=" ")
for k in range(1,i):
print(k, end = " ")
for l in range(i, 0, -1):
print(l, end= " ")
print()
for i in range (4,0,-1): for j in range(6-i): print(" ", end=" ")
for k in range(1,i):
print(k, end = " ")
for l in range(i, 0, -1):
print(l, end= " ")
print()
Upvotes: 0