Python Loops
Loops are used in programming to repeat a specific block of code until a certain condition is met. Python has two types of loops: for
loop and while
loop.
Syntax
For loop
for variable in sequence:
# code block to be executed
While loop
while condition:
# code block to be executed
Example
For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While loop
i = 1
while i < 6:
print(i)
i += 1
Output
For loop
apple
banana
cherry
While loop
1
2
3
4
5
Explanation
- A
for
loop is used to iterate over a sequence (list, tuple, dictionary, set, or string). - A
while
loop is used to repeat a block of code as long as a certain condition is true. - In a
for
loop, a temporary variable is created to hold the current element of the sequence during each iteration. - In a
while
loop, the condition is checked before each iteration.
Use
- Loops are used to iterate over a sequence and perform some operation on each element of the sequence.
- Loops can also be used to repeat a block of code until a certain condition is met, such as validating user input.
Important Points
- Be careful to avoid infinite loops when using while loops. Make sure that the condition will eventually become false.
- Use
range()
function to generate numbers for iterations.
Summary
Loops are an essential part of programming. They allow you to repeat a block of code until a certain condition is met. Python has two types of loops: for
loop and while
loop. Use for
loop to iterate over a sequence and while
loop to repeat a block of code as long as a certain condition is true.