Question:
Create a function to print a diamond with the pattern shown in the example below. The function has one input, n, an integer that controls the size of the diamond.
Input: 5
Output:
o
ooo
ooooo
ooooooo
ooooo
ooo
o
Input: 3
Output
o
ooo
ooooo
ooo
o
Input: 2
o
ooo
o
Input: 1
Output:
o
Answer:
The key here is to first separate the printing of the top and bottom half. Then, for each half, find the pattern of how many times the white space should be printed and how many times o‘s should be printed.
# the function
def diamond(n):
for i in range(n):
print(' '*(n-i-1) + 'o'*(2*i+1))
for i in range(1,n):
print(' '*i + 'o'*((n-i)*2-1))
# call the function
diamond(3)
👍 Have fun while coding with Python!
👌 Please subscribe to receive notifications on future challenges.
💬 If you have any questions simply write a comment down below.