Print the outline of a square.
What to build
Two loops with a decision inside them.
Requirements
- Read
n. - Print
nrows ofncharacters. - Cells on the edge are
*, and all others are spaces.
Input
One whole number n.
Output
n lines.
Constraints
n is from 1 to 30.
Example
Input:
3
Output:
***
* *
***
Why it works
Testing the row and column of each cell turns the shape into one simple condition, and it works for every size.
Examples
Example 1 · Input
3
Expected output
*** * * ***
Example 2 · Input
4
Expected output
**** * * * * ****
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A cell is a star if it is in the first or last row, or the first or last column.
Hint 2
Build each row as text, then print it.
Solution
Show one correct solution (try it yourself first)
n = int(input())
for row in range(n):
line = ""
for col in range(n):
if row == 0 or row == n - 1 or col == 0 or col == n - 1:
line += "*"
else:
line += " "
print(line)