livepython.net

284. Python Program to Print a Star Pyramid

MediumPhase 2 · Practice

This one takes a few steps, but you know every tool it uses: a for loop and how * repeats text.

Overview

The star pyramid is one of the most common pattern questions. Each row grows on both sides, so for every row you work out two numbers: the spaces and the stars.

Problem Statement

Aiko draws a pyramid for a desert scene in a game. Read a whole number n and print a pyramid of n rows:

  • Row 1 has n - 1 spaces and then 1 star.
  • Each new row has 1 space less and 2 stars more.
  • So row i has n - i spaces and then 2 * i - 1 stars.
  • The last row has no spaces and 2 * n - 1 stars.

The stars touch: there are no spaces between them.

Examples

Example 1. Input 4 gives:

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

Why: row 1 has 3 spaces and 1 star. Each row has 1 space less and 2 stars more, so the last row has no spaces and 7 stars.

Example 2. Input 2 gives:

 *
***

Why: row 1 has 1 space and 1 star. Row 2 has 3 stars, so the top star sits right above the middle star.

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. Line i has n - i spaces and then 2 * i - 1 stars. The spaces at the start of a line matter: the tests check them. The tests try 6 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.