Statement
Solution
Exercise 3.4: Pattern Printing
Use Nested Loops (a loop inside another loop) to print a right-angled triangle of stars.
Your program should:
- Take the number of rows as input (use
5for the standard pattern). - Use an Outer Loop to handle the rows (1 to N).
- Use an Inner Loop to handle the columns. The number of stars should equal the current row number.
- Print
*without moving to a new line inside the inner loop. - Print a new line after the inner loop finishes.
Sample Interaction:
Input
Output
5
Enter rows: 5
*
**
***
****
*****
Solution
To keep the cursor on the same line while printing, use end="" inside the print function.
# 1. Get User Input
rows = int(input("Enter rows: "))
print() # Important: Force new line after input
# 2. Outer loop for rows (1 to rows)
for i in range(1, rows + 1):
# 3. Inner loop for columns (1 to current row number)
for j in range(i):
print("*", end="")
# 4. Move to new line after inner loop
print()
Key Concepts:
range(1, rows + 1)ensures we get exactly N rows.print("*", end="")suppresses the default newline character, allowing stars to appear side-by-side.- The empty
print()handles the line break after each row is finished.
Test Console
Run code to see output...