Python programming provide various Loops, in this post we will see all the types of loops here. Loops in Python are used to execute a block of code repeatedly as long as a certain condition is met. There are two types of loops in Python for
loops and while loops.
For Loop in Python
The for
loop in Python is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a block of code for each item in the sequence.
The basic syntax for a for loop in Python is:
for item in sequence:
# execute code
For example, the following code uses a for loop to iterate over a list of numbers and print each number:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
1 2 3 4 5
While Loop in Python
The while
loop in Python is used to execute a block of code repeatedly as long as a certain condition is met.
The basic syntax for a while loop in Python is:
while condition:
# execute code
For example, the following code uses a while
loop to print the numbers from 1 to 5:
i = 1
while i <= 5:
print(i)
i += 1
1 2 3 4 5
You Can Read How to give Indentation in Python
Find The Difference between two numbers Tutorial
2 thoughts on “Loops in Python”