Print Star Pattern In Python Using For Loop
Chapter:
Python
Last Updated:
17-04-2023 13:28:50 UTC
Program:
/* ............... START ............... */
# Print a star pattern with 5 rows
for i in range(5):
for j in range(i + 1):
print('*', end='')
print()
/* ............... END ............... */
Output
Notes:
-
We start by defining a for loop that iterates over the range from 0 to 4. This will give us 5 iterations, which will correspond to the 5 rows of the star pattern that we want to print.
- Within the outer loop, we define another for loop that iterates over the range from 0 to the current value of i. For example, on the first iteration of the outer loop, i will be 0, so the inner loop will iterate over the range from 0 to 0 (i.e., it will run once). On the second iteration of the outer loop, i will be 1, so the inner loop will iterate over the range from 0 to 1 (i.e., it will run twice).
- Within the inner loop, we print a single asterisk (*) character for each iteration of the loop, using the print function. We also set the end parameter to an empty string, so that the asterisks are printed on the same line.
- After the inner loop completes, we print a newline character (\n) using the print function. This causes the next iteration of the outer loop to start on a new line.
- Finally, after all iterations of the outer loop have completed, the program exits.
- This program uses nested for loops to generate the star pattern, by iterating over the rows and columns of the pattern and printing a single asterisk character for each position in the pattern. The output of the program is a simple but elegant star pattern, which is a common programming exercise for beginners to practice using loops and basic programming constructs.
Tags
Python Pattern Programs #Print Star Pattern In Python Using For Loop