In Python, there are two main types of loops: for loops and while loops. Here are examples of how to use each type of loop:
for loop: A for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable object. The basic syntax for a for loop is as follows:
for item in iterable:
# do something with item
Here is an example of a for loop that iterates over a list of numbers and prints each one:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This would output the following:
1
2
3
4
5
while loop: A while loop is used to repeatedly execute a block of code as long as a certain condition is true. The basic syntax for a while loop is as follows:
while condition:
# do something
Here is an example of a while loop that counts from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1
This would output the following:
1
2
3
4
5
In addition to these basic loop types, Python also provides some additional control flow statements that can be used to modify loop behavior:
break: The break statement is used to exit a loop prematurely. For example, you might use break to exit a loop when a certain condition is met. Here is an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
This would output the following:
1
2
continue: The continue statement is used to skip over a certain iteration of a loop. For example, you might use continue to skip over certain values in a sequence. Here is an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
This would output the following:
1
2
4
5
These are the basic loop types and control flow statements in Python. By using loops and control flow statements, you can write powerful and flexible code that can handle a wide variety of tasks.