Python For Loops 🎯

beginner
21 min

Python For Loops 🎯

Welcome to our comprehensive guide on Python For Loops! This tutorial is designed for both beginners and intermediates, and we'll dive deep into this powerful tool. Let's get started!

What are For Loops? 📝

For loops are a fundamental part of programming in Python. They allow you to repeat a block of code a specific number of times or until a certain condition is met.

Why do we use For Loops? 💡

For loops are essential for iterating over lists, strings, and other iterable objects, making them indispensable in many programming tasks. They help in automating repetitive tasks, saving time and reducing errors.

Syntax 📝

python
for variable in iterable: # code block to be executed
  • variable: a user-defined name to store the current element of the iterable.
  • iterable: an object (list, tuple, string, etc.) that contains elements you want to iterate over.

Example 1: Iterating over a List 🎯

python
numbers = [1, 2, 3, 4, 5] for num in numbers: print(num)

Output:

1 2 3 4 5

In this example, we're iterating over a list of numbers. Each number is assigned to the num variable, and we print the value.

Example 2: For Loops with Conditions 🎯

python
for i in range(10): if i > 5: print(i)

Output:

6 7 8 9

Here, we're using the built-in range() function to generate numbers from 0 to 9. The for loop iterates over these numbers, and we check if the number is greater than 5. If it is, we print the number.

Nested For Loops 🎯

Nested for loops allow you to iterate over multiple iterables simultaneously or iterate over an iterable multiple times.

python
for i in range(3): for j in range(3): print(f'i: {i}, j: {j}')

Output:

i: 0, j: 0 i: 0, j: 1 i: 0, j: 2 i: 1, j: 0 i: 1, j: 1 i: 1, j: 2 i: 2, j: 0 i: 2, j: 1 i: 2, j: 2

Quiz 📝

Quick Quiz
Question 1 of 1

What is the purpose of the `for` loop in Python?

By the end of this tutorial, you'll have a solid understanding of for loops in Python, and you'll be ready to use them in your own projects. Happy coding! 🚀