Python 3 | Program to print double sided stair-case pattern
Last Updated :
24 Aug, 2023
Below mentioned is the Python 3 program to print the double-sided staircase pattern.
Examples:
Input: 10
Output:
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
Note: This code only works for even values of n.
Example1
The given Python code demonstrates a staircase pattern. It defines a function pattern(n) that takes an integer n as input. It uses two nested loops: the outer loop iterates from 1 to n, and the inner loops handle space and star printing based on the row number and the condition of odd or even. If a row number is odd, it increments the value of k by 1; otherwise, it keeps it the same. The space and star printing is adjusted accordingly. The output is a staircase-like pattern of stars and spaces. The driver code sets n to 10 and calls the pattern function to print the pattern.
Python3
def pattern(n):
for i in range ( 1 ,n + 1 ):
k = i + 1 if (i % 2 ! = 0 ) else i
for g in range (k,n):
if g> = k:
print (end = " " )
for j in range ( 0 ,k):
if j = = k - 1 :
print ( " * " )
else :
print ( " * " , end = " " )
n = 10
pattern(n)
|
Output:
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
Time Complexity: O(n2), where n represents the given input.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Example 2
Here to implement the double-sided staircase pattern we will use nested loops to control the printing of characters for each line.
Python3
def print_double_sided_staircase(height):
for i in range ( 1 , height + 1 ):
for j in range (i):
print ( "*" , end = "")
print ( " " * ( 2 * height - 2 * i), end = "")
for j in range (i):
print ( "*" , end = "")
print ()
height = int ( input ( "Enter the height of the double-sided staircase: " ))
print_double_sided_staircase(height)
|
Output:
* *
** **
*** ***
**** ****
***** *****
************
Share your thoughts in the comments
Please Login to comment...