Editor

Python Program to Print a Staircase Pattern

Beginner · Patterns

A staircase pattern prints steps of `#` that rise from left to right: the bottom step is n characters wide, each step above is one shorter, and all of them line up on the right. It is a popular coding practice problem, usually asked as a function that takes the number of steps n.

Program

staircase_pattern.py
def staircase(n):
for i in range(1, n + 1):
spaces = " " * (n - i) # empty space to the left of the step
blocks = "#" * i # the step itself
print(spaces + blocks)
steps = 5 # or: steps = int(input("How many steps? "))
print("A staircase of", steps, "steps:")
staircase(steps)
Output
A staircase of 5 steps:
    #
   ##
  ###
 ####
#####

How it works

  1. The drawing is done by a function, staircase(n), so the same code can draw a staircase of any size.
  2. Row i has n - i spaces followed by i hashes, so every row is exactly n characters wide.
  3. Because every row has the same width, the hashes all end in the last column and the steps rise from left to right.
  4. The top row has a single # and the bottom row is a full row of n hashes.

Other ways to write it

Wider steps

Wider steps
n = 5
width = 3 # how wide each step is
for i in range(1, n + 1):
print(" " * (width * (n - i)) + "#" * (width * i))
Output
            ###
         ######
      #########
   ############
###############

Multiplying by width makes every step 3 characters wide, which looks more like a real flight of stairs.

Stairs drawn with lines

Stairs drawn with lines
n = 5
for i in range(n):
print(" " * (n - 1 - i) + "___|")
Output
                ___|
            ___|
        ___|
    ___|
___|

Each step is a tread ___ and a riser |, and every step up starts 4 characters further right, so the steps join into one flight of stairs.

Try it yourself

Change staircase() so the steps go down from left to right instead.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises