Loops are used to execute a block of code repeatedly.
The main types are,
- For loops
- While loops.
Syntax:
While loop:
while (condition):
# code block
For loop:
for (variable) in (sequence):
# code block
While loop:
While loop repeatedly executes a block of code as long as the given condition remains true. When the condition becomes false, it will terminate the loop and print the remaining.
Example: While Loop
1).
i= 1
while i<= 5:
print("Number:", i)
i+= 1
This code is used to print the numbers from 1 to 5.
2).
i= 1
while i<= 10:
print("Number:", i*2)
i+= 1
This code is used to print multiples of 2.
3).
i= 1
fact = 1
while i<=5:
fact = fact * i
i= i + 1
print("Factorial of 5 is:", fact)
This code is used to print factorial of a number.
For loop:
A for loop is used to repeat a block of code for a fixed number of times
for (variable) in (sequence):
# code block
Example: For Loop
n = [1,2,3,4,5]
for x in n:
print(x)
Data Structure problem:
Binary search:














