Python Program to Print Diamond Pattern using Range() – My programming school

How to Print Diamond Pattern in Python using range function?

In this python program, we will explain a step-by-step rule to print Diamond shape utilizing the Python range() function. It also involves a working example for help.

Range() function to Print Diamond Pattern

We have shown various procedures to print diamond patterns in this post. Kindly peruse and assess them individually.

Diamond pattern program requirement

The goal of this activity is to deliver a diamond pattern like the one provided underneath. The pattern is utilizing the star image and prints across 9 lines.

You need to foster a program that uses a number and prints, utilizing stars, a complete diamond of the given length. let see Example, if the line size is 9, the code have to print:

    
        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************
 ***************
  *************
   ***********
    *********
     *******
      *****
       ***
        *

Additionally, you should utilize the Python range strategy for navigating through the loop.

Example – 1

In this technique, we will utilize the Python string field to repeat itself by a number specified along with the multiplication given symbol.

T_lines=9 
for iter in range (T_lines-1):
   print ((T_lines-iter) * ' ' + (2*iter+1) * '*') 
for iter in range (T_lines-1, -1, -1):
   print ((T_lines-iter) *' ' + (2* iter+1) * '*')

The above code delivers a similar diamond shape, as displayed in the past for example.

Output:

print diamond pattern using range function in python

Example -2

Presently, we’ll utilize the code that prints the diamond pattern with only one loop statement.

In this example, we use Python 3.6 f-string highlight, a blend 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}}")

At the point when you run the above code, it prints the diamond pattern as indicated by our essential.

Output:

print diamond pattern using range function in python

Related Posts

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment