This python program explains a step by step process to print Diamond pattern using the Python range function. It includes a working sample for help.
Range() to Print Diamond Pattern
We have demonstrated multiple techniques to print diamond pattern in this post. Please read and evaluate them one by one.
Diamond pattern program requirement
Our objective of this exercise is to produce a diamond shape like the one given below. The pattern is using the star symbol and prints across nine lines.
You need to develop a program that takes a number and prints, using stars, a full diamond of the given length. For Example, if the line size is 9, the code should print:
* *** ***** ******* ********* *********** ************* *************** ***************** *************** ************* *********** ********* ******* ***** *** *
Also, you must make use of Python range method for traversing through the loop.
Technique-1
Here, we’ve created a function and used inner loops with range() function to print the pattern.
""" Program desc: Python sample code to print Diamond pattern """ """ Function to print Diamond pattern """ def diamond_pattern(lines): star = 0 for line in range(1, lines + 1): # inner loop to print blank char for space in range (1, (lines - line) + 1): print(end = " ") # inner loop to print star symbol while star != (2 * line - 1): print("*", end = "") star = star + 1 star = 0 # line break print() star = 1 ubound = 1 for line in range(1, lines): # loop to print spaces for space in range (1, ubound + 1): print(end = " ") ubound = ubound + 1 # loop to print star while star <= (2 * (lines - line) - 1): print("*", end = "") star = star + 1 star = 1 print() # Main Code # Enter the size of Diamond pattern lines = 9 diamond_pattern(lines)
Technique-2
In this technique, we’ll use the Python string property to repeat itself by a number specified along with the multiplication symbol.
lines = 9 for iter in range(lines-1): print((lines-iter) * ' ' + (2*iter+1) * '*') for iter in range(lines-1, -1, -1): print((lines-iter) * ' ' + (2*iter+1) * '*')
The above code produces the same diamond shape, as shown in the previous example.
Techniques-3
Now, we’ll use the code which prints the diamond pattern with just one loop statement.
In this sample, we are using Python 3.6 f-string feature, and a combination of the reversed(), and range() functions.
lines = 9 for x in list(range(lines)) + list(reversed(range(lines-1))): print(f"{'': <{lines - x - 1}} {'':*<{x * 2 + 1}}")
Once you run the above code, it does print the diamond pattern as per our requirement.