The Road To Python Mastery
The Road To Python Mastery
Explanation:
Goal: Print a triangle that looks like this:
markdown
Copy code
*
* *
* * *
* * * *
* * * * *
1.
2. How it works:
○ rows = 5: This is the total number of rows in the triangle.
○ i = 1: This starts at 1 because we start building from the first row.
○ while i <= rows: This loop runs as long as i (the current row) is less than or
equal to the total number of rows.
○ print("* " * i): The * i means "repeat * (star with a space) i times."
○ i += 1: This moves to the next row by increasing i by 1.
3. Flow:
○ Row 1: i = 1, prints *.
○ Row 2: i = 2, prints * *.
○ Row 3: i = 3, prints * * *.
○ ... and so on, until i = 5.
rows = 5
i = 1
while i <= rows:
spaces = rows - i
print(" " * spaces + "* " * i)
i += 1
Explanation:
Goal: Print a triangle aligned to the right, like this:
markdown
Copy code
*
* *
* * *
* * * *
* * * * *
1.
2. How it works:
○ spaces = rows - i: Calculates how many spaces to print before the stars.
■ Example: On row 1, spaces = 5 - 1 = 4. We print 4 spaces.
○ " " * spaces: Prints the calculated number of spaces.
○ "* " * i: Prints i stars.
○ print(" " * spaces + "* " * i): Combines spaces and stars on the
same line.
3. Flow:
○ Row 1: spaces = 4, i = 1 → prints *.
○ Row 2: spaces = 3, i = 2 → prints * *.
○ Row 3: spaces = 2, i = 3 → prints * * *.
○ ... until i = 5.
3. Rhombus
Code:
python
Copy code
rows = 5
i = 1
while i <= rows:
print(" " * (rows - i) + "* " * rows)
i += 1
Explanation:
Goal: Print a rhombus like this:
markdown
Copy code
* * * * *
* * * * *
* * * * *
1.
markdown
Copy code
2. **How it works**:
- `rows = 5`: Total number of rows in the rhombus.
- `" " * (rows - i)`: Calculates spaces to indent each row.
- `"* " * rows`: Always prints the same number of stars (5 in this
case).
- `print(" " * (rows - i) + "* " * rows)`: Combines spaces and stars.
3. **Flow**:
- Row 1: `spaces = 4`, prints 4 spaces + 5 stars.
- Row 2: `spaces = 3`, prints 3 spaces + 5 stars.
- Row 3: `spaces = 2`, prints 2 spaces + 5 stars.
- ... and so on.
---
### Code:
```python
rows = 5
i = 1
while i <= rows:
spaces = rows - i
print(" " * spaces + "* " * (2 * i - 1))
i += 1
Explanation:
Goal: Print a triangle like this:
markdown
Copy code
*
* * *
* * * * *
1.
markdown
Copy code
2. **How it works**:
- `spaces = rows - i`: Calculates spaces to align stars at the center.
- `" " * spaces`: Prints the calculated spaces.
- `"* " * (2 * i - 1)`: Calculates the number of stars for the row.
- Stars = `(2 * i - 1)` ensures an odd number of stars on each row.
- `print(" " * spaces + "* " * (2 * i - 1))`: Combines spaces and
stars.
3. **Flow**:
- Row 1: `spaces = 4`, stars = `1`.
- Row 2: `spaces = 3`, stars = `3`.
- Row 3: `spaces = 2`, stars = `5`.
- ... and so on.
---
3. **Decide on Variables**:
- Use a variable like `i` for the current row.
- Calculate secondary elements like `spaces` or `stars` using simple
math.
6. **Combine Elements**:
- Concatenate spaces and stars into one line.