Part of the series

Several example codes

~2 min read • Updated Oct 6, 2025

Program Overview

This Python program reads an integer n between 1 and 8 and prints a square pattern of size n × n using asterisks (*).
The output highlights three specific parts of the square:
- The last row
- The last column
- The secondary diagonal (from top-right to bottom-left)


Python Code:


# Read n from user
n = int(input("Enter a number between 1 and 8: "))

# Validate input
if 1 <= n <= 8:
    for i in range(n):
        row = ''
        for j in range(n):
            if i == n - 1 or j == n - 1 or i + j == n - 1:
                row += '* '
            else:
                row += '  '
        print(row)
else:
    print("The number must be between 1 and 8.")

Sample Output for n = 5:


        *  
      *   *  
    *       *  
  *         *  
* * * * * *  

Step-by-Step Explanation:

- The user inputs a number n
- The program checks that n is between 1 and 8
- A nested loop prints each row and column
- A star is printed if the position is on the last row (i == n - 1), last column (j == n - 1), or secondary diagonal (i + j == n - 1)
- Otherwise, spaces are printed to maintain alignment


Written & researched by Dr. Shahin Siami