Home » Pyramid Pattern in Python

Pyramid Pattern in Python

Pyramid Pattern in Python

Hello everyone, welcome back to programminginpython.com! I recently started a new series on pattern programming, I explained how to print a  Floyd’s Triangle pattern in the previous post. Here I will explain to you how to print a pyramid pattern or a triangle pattern in Python.

Program on GitHub

You can also watch the video on YouTube here.

Ad:
The Complete Python Bootcamp From Zero to Hero in Python – Enroll Now.
Udemy

Pyramid Pattern – Code Visualization

Task

Python Program to print a Pyramid/Triangle Pattern.

Approach

  • Read an input integer for asking the range of the triangle using  input()
  • Run 3 for loops, one main for column looping, and the other 2 sub-loops for row looping, in the first loop, loop through the range of the triangle for column looping.
  • In the second loop, loop through the value of the range – 1, this is to print space ` `
  • In the third loop, loop through the value of i+1 and print *

Program on GitHub

Program

__author__ = 'Avinash'

# Print a Triangle

# Range of the triangle
num = int(input("Enter the range: \t "))

# i loop for range(height) of the triangle
# first j loop for printing space ' '
# second j loop for printing stars '*'

for i in range(num):
    for j in range((num - i) - 1):
        print(end=" ")
    for j in range(i + 1):
        print("*", end=" ")
    print()

Output

Pyramid Pattern In Python
Pyramid Pattern In Python

Program on GitHub

That is it for this tutorial. Also, feel free to look at programs on other patterns or some algorithms implementation in Python here or look at all of the posts here.

Ad:
The Complete Python Bootcamp From Zero to Hero in Python – Enroll Now.
Udemy

Course Suggestion

Machine Learning is everywhere! So I strongly suggest you take the course below.
Course: Machine Learning Adv: Support Vector Machines (SVM) Python

Online Python Compiler

Leave a Reply

Your email address will not be published. Required fields are marked *