Part of the series

Several example codes

~3 min read • Updated Oct 5, 2025

Program Overview

This Python program reads an integer n between 0 and 80 and prints a square pattern of size n × n using asterisks (*).
- If n is between 1 and 80, the output shows only the four borders of the square.
- If n = 0, the program defaults to a sample size (e.g., 7) and displays borders, the main diagonal (top-left to bottom-right), and the secondary diagonal (top-right to bottom-left).


Python Code:


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

# Special case: n = 0 → show borders + both diagonals
if n == 0:
    n = 7  # default sample size
    for i in range(n):
        row = ''
        for j in range(n):
            if i == 0 or i == n - 1 or j == 0 or j == n - 1 or i == j or i + j == n - 1:
                row += '* '
            else:
                row += '  '
        print(row)

# Normal case: show only borders
elif 1 <= n <= 80:
    for i in range(n):
        row = ''
        for j in range(n):
            if i == 0 or i == n - 1 or j == 0 or j == n - 1:
                row += '* '
            else:
                row += '  '
        print(row)

else:
    print("The number must be between 0 and 80.")

Sample Output for n = 0:


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

Step-by-Step Explanation:

- If n = 0, the program uses n = 7 as a sample size
- Stars are printed on borders, main diagonal (i == j), and secondary diagonal (i + j == n - 1)
- If n is between 1 and 80, only the borders are printed
- The nested loop builds each row character by character


Written & researched by Dr. Shahin Siami