This Python program explains a step-by-step process to print Diamond patterns 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 patterns in this post. Please read and evaluate them one by one.
Diamond pattern program requirement
Our objective for this exercise is to produce a diamond shape like the one given below. The pattern uses the star symbol and prints across nine lines.
Must Read: Print patterns in Python with examples
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 the Python range method for traversing through the loop.
Technique-1
Here, we’ve created a function and used inner loops with a 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.
Also Check: Alphabet Pattern “A” Using Python Range()
Techniques-3
Now, we’ll use the code that creates 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 prints the diamond pattern as per our requirement.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.