×

How to Print Pattern in Python

How to Print Pattern in Python.

Pattern programs are really important for beginners and they are always asked in all the technical interviews.

Multiple loops approach is used to print the different type of patterns. (de)

defined the function 'pypart' for simple pyramid.
def pypart(rows):
# to handle the printing of rows, this outer loop is used.
for i in range(0, rows):
# this inner loop is used to handle the printing of number of columns.
# Values change according to the outer loop.
for j in range(0, i+1):
# for printing stars and one space after that every star.
print("* ",end="")
# \r to end line after each row.
print("\r")
taking number of rows as input.
using 'int' because input takes ‘str’ type as input and we have to convert it into ‘int’ type.
rows= int(input("Enter the number of rows:"))
pypart(rows) 

Simple Pyramid Pattern

OUTPUT

How To Print Pattern In Python
Function to demonstrate printing pattern
def pypart(rows):
myList = []
for i in range(1,rows+1):
myList.append("* "*i)
print("\n".join(myList))
taking number of rows as input.
using 'int' because input takes ‘str’ type as input and we have to convert it into ‘int’ type.
rows= int(input("Enter the number of rows:"))
pypart(rows)

Simple Pyramid Using lists

OUTPUT

How To Print Pattern In Python

Simple Pyramid after 180 degree rotation

def pyramidpart2(rows):
# number of spaces n = 2*rows - 2 # this loop is used to handle the printing of rows for i in range(0, rows): # inner loop is used to handle number spaces # values are changed according to the requirement for j in range(0, n): print(end=" ") # n is decremented after each loop n = n - 2 # this inner loop is used to handle number of columns # values are changed according to the outer loop for j in range(0, i+1): # printing stars print("* ", end="") # \r to end line after each row. print("\r") 
taking number of rows as input.
using 'int' beacuse input takes str type as input and we have to convert it onto int type.
rows= int(input("Enter the number of rows:"))
pyramidpart2(rows)

OUTPUT

How To Print Pattern In Python

3.    Simple Triangle pattern

defined the function 'triangle' for simple triangle pattern.
def triangle(rows):
# no. of spaces
k = 2rows - 2 # To handle the printing of rows, this outer loop is used. for i in range(0, rows): # printing of spaces is handled by this inner loop. # values will change according to the requirement. for j in range(0, k): print(end=" ") # k is decremented after each loop k = k - 1 # this inner loop is used to handle the printing of columns. # Values will change according to the requirement. for j in range(0, i+1): # for printing the stars print(" ", end="")
# \r to end the line
print("\r")
taking number of rows as input.
using 'int' beacuse input takes ‘str’ type as input and we have to convert it onto ‘int’ type
rows= int(input("Enter the number of rows:"))
triangle(rows)

OUTPUT

How To Print Pattern In Python

4.    Inverse Triangle pattern.

defined the function 'triangle' for simple triangle pattern.
def triangle(rows):
# no. of spaces
k = 2rows - 2 # To handle the printing of rows, this outer loop is used. for i in range(rows, -1,-1): # printing of spaces is handled by this inner loop. # values will change according to the requirement. for j in range(k,0,-1): print(end=" ") # k is decremented after each loop k = k + 1 # this inner loop is used to handle the printing of columns. # values will change according to the requirement. for j in range(0, i+1): # for printing the stars print(" ", end="")
# \r to end the line
print("\r")
taking number of rows as input.
using 'int' beacuse input takes str type as input and we have to convert it onto int type
rows= int(input("Enter the number of rows:"))
triangle(rows)

OUTPUT

How To Print Pattern In Python

5.    Diamond pattern

 # taking number of rows as input.
# using 'int' beacuse input takes str type as input and we have to convert it onto int type
row = int(input("Enter the number of row: ")) 
# k is used to print the space 
k = 2 * row - 2 
# to print the number of rows this outer loop is used 
for i in range(0, row): 
    # to print the number of spaces this inner loop is used
    for j in range(0, k): 
        print(end=" ") 
    # k is decremented after each iteration 
    k = k - 1 
    # to print the stars this inner loop is used
    for j in range(0, i + 1): 
        print("* ", end="") 
    print("") 
# For printing downward triangle Pyramid 
# k is used to print space
k = row - 2 
# this loop is used to print downward triangle and handle the printing of rows
for i in range(row, -1, -1): 
    # to print the spaces this inner loop is used
    for j in range(k, 0, -1): 
        print(end=" ") 
    # k is incremented after each iteration 
    k = k + 1 
    # stars will be printed by this inner loop
    for j in range(0, i + 1): 
        print("* ", end="") 
    print("")  

OUTPUT

How To Print Pattern In Python

6.    Half Diamond Pattern

 # taking number of rows as input.
# using 'int' because input takes str type as input and we have to convert it onto int type
r = int(input("Enter the number of rows: "))
# this outer loop will be used to print the number of rows in the upper simple pyramid
for i in range(0, r): 
    # This inner loop will be used to print the stars 
    for j in range(0, i + 1): 
        print("*", end=' ') 
    print(" ") 
# To print the downward inverse simple pyramid
# this outer loop will print the number of rows of the downward inverse simple pyramid
for i in range(r + 1, 0, -1):
    # this inner loop is used to print the stars
    for j in range(0, i - 1): 
        print("*", end=' ') 
    print(" ")  

OUTPUT

How To Print Pattern In Python

7.    Hour-glass Pattern

 # hour_glass_pattern is defined
def hour_glass_pattern(rows):
    # this loop is used to print the upper half
    for i in range(1, rows + 1): 
        # for printing spaces at the beginning of each row
        for k in range(1, i):
            print(" ", end = "")
        # for printing 'i' to 'row' values at the end of each row
        for j in range(i, rows + 1): 
            print("*", end = " ") 
        print()
    # this loop is used for printing the lower half
    for i in range(rows - 1, 0, -1): 
        # for printing spaces at the beginning of each row
        for k in range(1, i):
            print(" ", end = "")
        # for printing 'i' to 'row' values at the end of each row
        for j in range(i, rows + 1):
            print("*", end = " ")
        print()
# taking number of rows as input.
# using 'int' beacuse input takes ‘str’ type as input and we have to convert it onto ‘int’ type
rows= int(input("Enter the number of rows:"))
hour_glass_pattern(rows)     

OUTPUT

How To Print Pattern In Python

Related Topics

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Write Dictionary to CSV in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.