Loops allow you to execute a block of code repeatedly, making your programs more efficient. In this tutorial, we will cover two main types of loops in Python: for and while.
for LoopThe for loop is used to iterate over a sequence, such as a list, tuple, or string. Here's an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherryYou can also use the range() function to loop through a sequence of numbers:
for i in range(5):
print(i)Output:
0
1
2
3
4while LoopThe while loop executes as long as the condition is True. Here's an example:
x = 5
while x > 0:
print(x)
x -= 1Output:
5
4
3
2
1break and continueThe break statement allows you to exit a loop prematurely:
for i in range(5):
if i == 3:
break
print(i)Output:
0
1
2The continue statement skips the current iteration and moves to the next one:
for i in range(5):
if i == 3:
continue
print(i)Output:
0
1
2
4Loops can also be nested inside one another. Here's an example:
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")Output:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1Try creating your own for and while loops with various conditions. Loops are essential for solving repetitive problems efficiently. Happy coding! The next step in python would be to learn about functions in python!