Exp 3
Exp 3
1
Bharati Vidyapeeth Deemed University
College of Engineering, Pune
Department of Electronics and
Communication Engineering
Aim: Develop python functions to produce given patterns such as diamond, pyramid, triangles.
Theory:
1. For loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax:
for val in sequence:
(Loop Body)
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
2. While loop
2
Bharati Vidyapeeth Deemed University
College of Engineering, Pune
Department of Electronics and
Communication Engineering
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true. We generally use this loop when we don't know the number of times to iterate
beforehand.
Syntax:
while test_expression:
(Loop Body)
In the while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation. The body starts with
indentation and the first unindented line marks the end. Python interprets any non-zero value
as True. None and 0 are interpreted as False.
3
Bharati Vidyapeeth Deemed University
College of Engineering, Pune
Department of Electronics and
Communication Engineering
Algorithm:
In the above program, let's see how the pattern is printed.
First, we get the height of the pyramid rows from the user.
In the first loop, we iterate from i = 0 to i = rows.
The second loop runs from j = 0 to i + 1. In each iteration of this loop, we print i +
1 number of * without a new line. Here, the row number gives the number of * required
to be printed on that row. For example, in the 2nd row, we print two *. Similarly, in the
3rd row, we print three *.
Once the inner loop ends, we print new line and start printing * in a new line.
Code-
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
4
Bharati Vidyapeeth Deemed University
College of Engineering, Pune
Department of Electronics and
Communication Engineering
Algorithm:
This type of pyramid is a bit more complicated than the ones we studied above.
k=0
print(end=" ")
while k!=(2*i-1):
k += 1
k=0
print()
5
Bharati Vidyapeeth Deemed University
College of Engineering, Pune
Department of Electronics and
Communication Engineering
Conclusion:
6
Bharati Vidyapeeth Deemed University
College of Engineering, Pune
Department of Electronics and
Communication Engineering