~2 min read • Updated Oct 6, 2025
Program Overview
This Python program reads an integer n between 1 and 80 and prints a square pattern of size n × n using asterisks (*).
The output highlights three specific parts of the square:
- The first row
- The last column
- All elements on and above the main diagonal (i ≤ j)
If n = 0 is entered, the program displays nothing.
Python Code:
# Read n from user
n = int(input("Enter a number between 1 and 80: "))
# Validate input
if 1 <= n <= 80:
for i in range(n):
row = ''
for j in range(n):
if i == 0 or j == n - 1 or i == j or i < j:
row += '* '
else:
row += ' '
print(row)
elif n == 0:
pass # No output for n = 0
else:
print("The number must be between 0 and 80.")
Sample Output for n = 5:
* * * * *
* *
* *
* *
* *
Step-by-Step Explanation:
- The user inputs a number n
- If n = 0, the program does nothing
- If n is between 1 and 80, a nested loop prints each row and column
- A star is printed if the position is on:
— The first row (i == 0)
— The last column (j == n - 1)
— The main diagonal (i == j)
— Above the main diagonal (i < j)
- Otherwise, spaces are printed to maintain alignment
Written & researched by Dr. Shahin Siami