
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to print pattern in Python?
Patterns in Python can be printed using nested for loops. The outer loop is used to iterate through the number of rows whereas the inner loop is used to handle the number of columns. The print statement is modified to form various patterns according to the requirement.
The patterns can be star patterns, number patterns, alphabet patterns. The patterns can be of different shapes, triangle, pyramids, etc.
Example
All these patterns can be printed with the help of for loops with modified print statements which forms these different patterns.
The basic idea between the printing of these patterns is the same with slight differences.
We will implement the code for some of these patterns.
Printing Triangle
Example
def triangle(n): k=n-1 for i in range(1,n+1): for j in range(k): print(" ",end="") k=k-1 for p in range(i): print("*",end=" ") print() print("Enter number of rows") r=int(input()) triangle(r)
Output
Enter number of rows 5 * * * * * * * * * * * * * * *
Let us try running the above code with different number of rows −
Number pattern
Example
def num_pattern(n): num=1 for i in range(1,n+1): for j in range(i): print(num,end=" ") num+=1 print() print("Enter number of rows") r=int(input()) num_pattern(r)
Output
Enter number of rows 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Alphabet pattern
Example
def alpha_pattern(n): st="ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(1,n+1): for j in range(i): print(st[j],end=" ") print() print("Enter number of rows") r=int(input()) alpha_pattern(r)
Output
Enter number of rows 5 A A B A B C A B C D A B C D E
Pyramid (rotated 180 degree)
Example
def pyramid(n): k=n-1 for i in range(1,n+1): for j in range(k): print(" ",end="") for p in range(i): print("*",end=" ") k=k-1 print() print("Enter number of rows") r=int(input()) pyramid(r)
Output
Enter number of rows 5 * * * * * * * * * * * * * * *
Run the above code on IDE to get an accurate view of the pattern.
- Related Questions & Answers
- Python Program to Print an Inverted Star Pattern
- Python program to print rangoli pattern using alphabets
- Python Program to print the pattern ‘G’
- Print matrix in diagonal pattern
- Program to print Interesting pattern in C++
- Program to print Kite Pattern in C++
- Program to print number pattern in C
- Program to print Diamond Pattern in C
- Program to print numeric pattern in C
- Program to print pyramid pattern in C
- Print the given pattern recursively
- PHP program to print the number pattern
- Java Program to Print Pyramid Star Pattern
- Java Program to Print Diamond Star Pattern
- Java Program to Print Square Star Pattern