livepython.net

275. Python Program to Print a Hollow Square

EasyPhase 1 · Warm-up

This uses a for loop, one if and * to repeat text. You know all three.

Overview

A hollow shape has stars only on its edges. You decide, row by row, which rows are full and which are empty inside.

Problem Statement

Sven plans a fence around a garden in a farm game. Read a whole number n and print a hollow square of size n:

  • The first row and the last row are full: n stars, with one space between the stars.
  • Every other row has one star at the start and one star at the end. Between them are 2 * n - 3 spaces. This puts the last star right under the last star of the first row.

No row has a space in front of its first star.

Steps

  1. Read n and turn it into a whole number.
  2. Loop over the row numbers from 1 to n.
  3. If the row is the first or the last one, print a full row of stars.
  4. Otherwise, print a star, the spaces and a star.

Examples

Example 1. Input 4 gives:

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

Why: the first and the last rows have 4 stars. The 2 middle rows have a star, 5 spaces and a star, because 2 * 4 - 3 is 5.

Example 2. Input 2 gives:

* *
* *

Why: there are only 2 rows, the first and the last, so both are full. A square of size 2 has no inside.

Input

One whole number n (1 or more). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

n lines. For n = 1, the square is a single star. A space at the end of a line is fine: the tests ignore it. The tests try 5 different inputs.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 10 · For Loops
solution.py
# write your code here

EXPECTED OUTPUT

1* * * *
2* *
3* *
4* * * *

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.