In this shot, we will discuss how to generate an inverted hollow right triangle using numbers in Python.
We can print a plethora of patterns using Python. The only prerequisite for this is a good understanding of how loops work in Python. Here we will be using simple for
loops to generate an inverted hollow right triangle using numbers.
Description
A triangle is said to be a right triangle if it has a 9090 degree angle. In this shot, we use the term inverted to mean upside down, so the right angle is on the top of the triangle.
To execute this using Python programming, we will be using two for
loops:
- An outer loop to handle the number of rows.
- An inner loop to handle the number of columns.
Code
Let us look at the code snippet. below:
# Number of rows n = 5 # Loop through rows for i in range[1,n+1]: # Loop through columns for j in range[1, n+1]: # Printing Pattern if [i==n-j+1] or [j==1] or [i==1]: print[i, end=" "] else: print[" ", end=" "] print[]
Explanation
In line 2, we take the input for the number of rows [i.e. the length of the triangle].
In line 5, we create a
for
loop to iterate through the number of rows.In line 8, we create an inner nested
for
loop to iterate through the number of columns.From lines 11 to 14, we create the pattern using conditional statements. The end statement helps to stay on the same line.
In line 15, the
print[]
statement is used to move to the next line.
RELATED TAGS
communitycreator
python
triangle
In this python example, we first read number of row in the hollow right angle triangle pattern from user using built-in function In this program This python program generates hollow right angle triangle pattern made of stars up to n lines.
input[]
. And then we generate hollow right angle triangle pattern
using python's for loop.Python Source Code: Hollow Right Angle Triangle Pattern
# Hollow Right Angle Triangle Pattern Using Stars
row = int[input['Enter number of rows required: ']]
for i in range[row]:
for j in range[i+1]:
if j==0 or j==i or i==row-1:
print['*',end=" "]
else:
print[" ", end=" "]
print[]
print[]
only is used to bring control to new lines.Output
Enter number of rows required: 8
*
* *
* *
* *
* *
* *
* *
* * * * * * * *
Description
Inverted Hollow Right Number Triangle:
Here in this pattern printing, the number of lines of the pattern is taken as the input. Two for loops are used to display the pattern. The first for loop [the outer for loop] is used to count the line number so the loop is from 1 to n. the stars are printed on the boundary line which makes the pattern hollow.
Algorithm
INPUT: the number of lines
OUTPUT: the aforesaid pattern
PROCESS:
Step 1: read n [the number of lines]
Step 2: for i=1 to n repeat
For j=i to n repeat
If i=1 then
Print j
Else if j=i then
Print i
Else if j=n then
Print n
Else
Print “ “
[End of ‘if’]
[End of ‘for’ loop]
Move to the next line
[End of ‘for’ loop]
Step 3: stop.
Code
Time Complexity:
for[i=1;i