- What are Pattern Programs in Python?
- Number Pattern Problem
- Incrementing Number Pattern Problem
- Pyramid Pattern Problem with Stars
- Inverted Semi-Pyramid Pattern Problem with Numbers:
- Inverted Semi-Pyramid Pattern Problem with Descending order of Numbers:
- Semi-Pyramid Pattern Problem with Numbers descending in each row:
- Alphabet Pattern Programs in Python
- Star Pattern in Python
- FAQs
What are Pattern Programs in Python?
Patterns programs consist of alphabets, numbers or symbols in a particular structure. These programs enhance the logic, looping concepts and coding skills. They are primarily asked questions in the technical interviews in order to test a programmer’s thinking and logic building skill. To be able to solve pattern questions, one must have a good knowledge of how the looping conditions work.
As they are widely asked by interviewers whenever you go for a python developer job or a software developer job, therefore, understanding the importance of this, we have come up with this article on “Pattern Program in Python”.
To understand basics of python get started with this Python Tutorials.
Number Pattern Problem
The pattern we want to form should look like as following
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Let’s go ahead and see how can we print this pattern program in python:
depth = 6
for number in range(depth):
for i in range(number):
print(number, end=" ")
print(" ")
Code Explanation:
We start off by initializing a variable called “depth” and give it a value of 6 with the help of this command:
depth = 6
Going ahead, we have a nested for loop. We have the outer for loop to set the depth or number of rows in this pattern. When we use the command:
for number in range(depth):
This helps us to get a list of numbers 0-5. Because the depth value is 6, this means that 6 is exclusive and that is why the range goes from 0-5.
Then, we set the inner for loop using this command:
for i in range(number).
In the inner for loop, initially, the value of the number is 0, that is why we skip the first row. Then we go back to the outer for loop and the number value becomes 1. Once the number value is 1, we head inside the inner loop and print 1.
After that number value is incremented again and it becomes 2, then we head to the inner loop and print 2 2.
Similarly, we go back to the outer loop and this time number value becomes 3. After this inside the for loop, we print 3 3 3.
Further which, again we go back to the outer loop, then the value of “number“ becomes 4 and we print 4 4 4 4 with the inner loop.
Finally, we will print 5 5 5 5 5.
Incrementing Number Pattern Problem
The pattern we want to form should look like as following
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Now, let’s go ahead and see how can we have a sequence of numbers in each row with python:
depth = 6
for number in range(1, depth):
for i in range(1, number + 1):
print(i, end=' ')
print("")
Code Explanation:
We start off by initializing the value of depth to be 6. Then, we set the outer for loop with this command:
for number in range(1, depth)
With the help of this command, we create a range of numbers which go on from 1 to 5. Then, we go ahead and set the inner for loop with this command:
for i in range(1, number + 1).
Inside the for loop, we print the digits using this command:
print(i, end=' ').
Initially, the value of the number is 1 in outer for loop, so we enter the inner for loop and go ahead and print 1.
Then in the outer for loop, the value of number becomes 2, so we enter the inner for loop and we print 1 2.
Similarly, we go back to the outer loop and here the number value becomes 3, so this time we enter the inner loop and print 1 2 3.
Going ahead, the value of “number” in the outer loop becomes 4, so with the inner loop we print
1 2 3 4
And in the final iteration, we print out: 1 2 3 4 5
Pyramid Pattern Problem with Stars
The pattern we want to form should look like as following
* * * * * * * * * * * * * * *
Let’s see the code for this pattern program in python:
def diamond(n):
for m in range(0, n):
for i in range(0, m+1):
print("* ",end="")
print("\r")
n = 5
diamond(n)
Code Explanation:
We start off by defining a method called “diamond” with this command: def diamond(n).
We set the outer for loop with this command:
for m in range(0, n)
Then, we go ahead and set the inner for loop using this command:
for i in range(0, m+1)
Initially, the value of’ is 0 in the outer for loop, so we go inside the for loop and print *. Then, the value of’ in the outer for loop becomes 1, this time we go inside the inner loop and print * *. Similarly, the value of’ in the outer loop becomes 2, so, we go inside the inner loop and print * * *.
Going ahead, the value of’ is incremented in the outer loop and it becomes 3, so, with the inner loop, we print * * * *.In the final iteration, we print out * * * * *.
Inverted Semi-Pyramid Pattern Problem with Numbers:
The pattern we want to form should look like as following
1 1 1 1 1 2 2 2 2 3 3 3 4 4 5
Let’s write the code for this:
row = 5
a = 0
for i in range(row, 0, -1):
a += 1
for j in range(1, i + 1):
print(a, end=' ')
print('\r')
Code Explanation:
We start off by initializing two variables. We set the value of row to be equal to 5 and the value of a to be equal to 0. After that we set the outer for loop with this command:
for i in range(row, 0, -1):
This outer for loop gives us numbers in descending order starting with 5 going on till 1. In the outer for loop, we increment the value of a with 1. After that, we set the inner for loop using this command:
for j in range(1, i + 1).
In the first iteration, the value of ‘i’ in outer for loop is 5, so with the inner for loop we print:
1 1 1 1 1
In the second iteration, the value of ‘i’ in outer for loop is 4, so in the inner for loop we print:
2 2 2 2
In the third iteration, the value of ‘i’ in the outer loop is decremented to 3, then, with the inner loop we print:
3 3 3
Going ahead in the fourth iteration, the value of ‘i’ in the outer loop is decremented to 2, so this time with the inner loop, we print:
2 2
And finally, in the last iteration, we print out 1.
Basic tutorial for Python to get started
Inverted Semi-Pyramid Pattern Problem with Descending order of Numbers:
The pattern we want to form should look like as following
5 5 5 5 5 4 4 4 4 3 3 3 2 2 1
Let’s look at the code to implement this pattern program in python:
depth = 5
for i in range(depth, 0, -1):
n = i
for j in range(0, i):
print(n, end=' ')
print("\r")
Code Explanation:
We start off by initializing the value of depth to be equal to 5. Then using the outer for loop, we produce a list of numbers in descending order from 5 to 1. Inside the outer for loop, we set the value of n to be equal to i. After that, we start off the inner for loop using this command:
for j in range(0, i):
In the first iteration the value of ‘i’ is 5 in the outer loop, so with the inner loop we print: 5 5 5 5 5
In the second iteration, the value of ‘i’ in the outer loop is decremented to 4, so we enter the inner loop and print 4 4 4 4
Then in the third iteration, the value of ‘i’ becomes 3, so with the inner loop, we print: 3 3 3
Going ahead in the fourth iteration, the value of ‘i’ becomes 2, this time we print out 2 2 with the inner loop.
Finally, in the last iteration, the value of ‘i’ becomes 1 and we print out 1.
Semi-Pyramid Pattern Problem with Numbers descending in each row:
1 2 1 3 2 1 4 3 2 1 5 4 3 2 1
Let’s look at the code for this pattern program in python:
size = 6
for row in range(1, size):
for column in range(row, 0, -1):
print(column, end=' ')
print("")
Code Explanation:
We start off by setting the value of variable size to be equal to 6. Then, we set the outer for loop with this command: for row in range(1, size). With this outer for loop, we produce a list of numbers starting from 1 going on till 5. Then, we set the inner loop with this command:
for column in range(row, 0, -1)
- In the first iteration, the value of row is 1 in the outer loop, so we enter the inner for loop and print 1.
- Then in the second iteration, the value of row is 2 in the outer loop, so this time we enter the inner loop and print: 2 1
- After that, in the third iteration, the value of row becomes 3 in the outer loop, so in the inner loop we go ahead and print: 3 2 1
- Going ahead, in the fourth iteration, the value of row becomes 4 in the outer loop, so this time, in the inner loop we print: 4 3 2 1
- Finally, in the last iteration, we go ahead and print: 5 4 3 2 1
Alphabet Pattern Programs in Python
Triangle Patterns
a) Pattern:-
A
BC
DEF
- The initial value set to 65 because the ASCII value of A is 65
- Outer loop decide no. of rows
- char() function convert no. to their corresponding value of ASCII letter
Code:
initialValue = 65
for i in range(0, 6):
for j in range(0, i + 1):
# It will convert the ASCII value to the character
alphabate = chr(initialValue)
# print(alphabate, end=' ')
print(f"{alphabate}", end="")
initialValue += 1
print("")
Output:
b) Pattern:-
A
BB
CCC
- Defining a variable called num with a value of 65(65 => A).
- The outer loop ranges from 0 to 5, which means the loop will run 5 times, and the inner loop will increment by 1.
- char function converts ASCII number to the corresponding character.
- Print with f string.
- print(“\r”) stands for a line break.
Code:
# defining A = 65
#num = A
num = 65
for i in range(0, 5):
for j in range(0, i + 1):
char = chr(num)
# printing char value
print(f"{char} ", end="")
# incrementing number
num = num + 1
# ending line after each row
print("\r")
Output:
c) Right-Angled Triangle Pattern with Same Character
- Initializing a function with name letter_range in which 2 arguments will pass one is started (where you want to start) end(where you want to end).
- The inner loop will increment value by 1 and print the character after that a line break.
Pattern:-
A
AB
ABC
Code:
# initializing function letter_range
def letter_range(start, end):
# outer loop
for i in range(start, end):
# inner loop
for j in range(65, i + 1):
print(f"{chr(j)}", end="")
print()
# calling Function
letter_range(65, 75)
Output:
d) Pattern:-
A B C D E
B C D E
C D E
D E
E
- Initializing a function with the name alpha, which takes an integer value.
- In the outer loop, we use for in loop for iteration, which goes from 1, n+1.
- The inner loop goes from i, n + 1 where i = current value of outer loop iteration.
- Using ord() function to return Unicode character. For example print(ord(‘B’)) -> # 66.
- Every time the inner loop exits, we use the print() function for spacing.
Code:
# defining Function alpha
def alpha(n):
for i in range(1, n + 1):
for j in range(i, n + 1):
print(chr(ord('A') - 1 + j), end=' ')
print()
# calling function
alpha(5)
Output:
e) Pattern:
A A A A A
B B B B
C C C
D D
E
- Initializing and declaring variables with the value of i = 0, j = 0, n = 5.
- Using for in loop within a range of 1, n+1 where n = 5
- Also, passing the third argument (-1) in for loop
- ord() function is added which returns a Unicode character.
- For example print(ord(‘C’)) -> # 67.
Code:
# patterns of alphabets
i = 0
j = 0
n = 5
for i in range(1, n + 1):
for j in range(n, i - 1, -1):
print(chr(ord('A') - 1 + i), end=" ")
print("")
Output:
Star Pattern in Python
a) Diamond Pattern in Python: It like a diamond star pyramid. Basically, it is made by two upper and lower equilateral pyramid and just connected by their mouth
Code:
n = int(input('Enter the number:'))
k = 2 * n - 2
for i in range(0, n):
for j in range(0, k):
print(end= ' ')
k = k - 1
for j in range(0, i + 1):
print('* ', end= '') # No space
print('') # No space
k = n - 2
for i in range(n, -1, -1):
for j in range(k, 0, -1):
print(end= ' ')
k = k + 1
for j in range(0, i + 1):
print('* ', end= '') # No space
print('') # No space
Output:
b) Sandglass pattern of star: X like pyramid of star, where basically upper equilateral pyramid and lower equilateral pyramids are connected.
code:
n = int(input('Enter the number:'))
i = 0
while i <= n - 1:
j = 0
while j < i:
# display space
print('', end= ' ')
j += 1
k = i
while k <= n - 1:
print('*', end= ' ')
k += 1
print()
i += 1
i = n - 1
while i >= 0:
j = 0
while j < i:
print('', end= ' ')
j += 1
k = i
while k <= n - 1:
print('*', end= ' ')
k += 1
print('')
i -= 1
Output:
c) Empty diamond pattern: It is as similar as the diamond like pattern but not any object into the pyramid.
Code:
n = int(input('Enter the number:'))
i = 1
while i <= n:
j = n
while j > i:
# display space
print(' ', end= ' ')
j -= 1
print('* ', end= ' ')
k = 1
while k < 2 * (i - 1):
print(' ', end= ' ')
k += 1
if i == 1:
print()
else:
print('* ')
i += 1
i = n - 1
while i >= 1:
j = n
while j > i:
print(' ', end= ' ')
j -= 1
print('* ', end= ' ')
k = 1
while k < 2 * (i - 1):
print(' ', end= ' ')
k += 1
if i == 1:
print( )
else:
print('*')
i -= 1
Output:
d) Square pattern: The program will take the length of the side as input and print the pattern of a square.
code:
n = int(input('Enter the number:'))
for i in range(n):
for j in range(n):
print('* ', end= '')
print()
Output:
e) Rectangle pattern: The program will take the length & breadth as input and print the rectangle pattern.
code:
rows = int(input('Enter the number for rows:'))
columns = int(input('Enter the number for columns:'))
for i in range(rows):
for j in range(columns):
print('* ', end= '')
print('')
Output:
FAQs
Q1 How do you create a pattern in Python?
The for loop is used to print various patterns in python. Various patterns use multiple for loops using the following concept:
- outer loop: prints the number or rows
- inner loop: prints the number of columns and inner nested loops
- variable: to print whitespaces according to the requirement of the code.
Q2 What is a pattern in Python?
Patters in python are printed using for loops. Different numeric, alphabetic or symbolic patterns can be formed using these loops by manipulating values or print statements according to the question to find the right solution.
Q3 How do I learn a python pattern program?
Steps:
1. Decision: Take the decision of how many rows and columns are required. The nested loops are used to print any pattern in python. For letting the user decide the size of the pattern, the “input()” function is used.
2. Iteration
(i) Rows: outer loop is iterated for the number of rows using the “for” loop and “range()” function.
(ii) Columns: outer loop is iterated for the number of columns depending on the values of the outer loop.
3. Print: “print()” function is iterated in each nested “for” loop to display different patterns
4. Adding a new line: A new line is added after each iteration of the outer loop using the “print()” function to appropriately display the pattern.
Q4 What does “R” mean in Python?
“R” or “r” is used as a prefix for string literals to create raw strings. Standard strings treat backslash (\) as a literal character. Using “r” or “R” is useful when we want to use backlash as a part of the string instead of an escape character.
Example: Executing a string with an escape character
a='We\nRun'
print(a)
Output:
We
Run
Example: Executing a string using “r” (raw string)
raw_a = r'We\nRun'
print(raw_a)
Output:
We\nRun
Q5 What does end =’ do in Python?
The print() function is a function that, by default, adds a new line at the end. By using ‘,’ at the end, it can be suppressed in Python 2.
Example: print b,
Whereas in Python 3, “end=’ ” is appended to add a space in place of a new line.
Example: print(b, end=” “)
This brings us to the end of this article where we learned some basic programs and pattern program in python. In order to get a free course on Python, click on the banner below.
Embarking on a journey towards a career in data science opens up a world of limitless possibilities. Whether you’re an aspiring data scientist or someone intrigued by the power of data, understanding the key factors that contribute to success in this field is crucial. The below path will guide you to become a proficient data scientist.