For Loops In Python- Python Tutorials For Beginners #9
Overview
Understanding For Loops In Python
A for loop is a powerful construct that allows you to repeat a block of code for each element in a sequence (like a list, tuple, or string). Here’s the basic structure:
How To Create For Loops
- Step 1: For loops are always starts with for keyword.
- Step 2: Create a variable as per your need.
- Step 3: Iterate element as per you want.
Now, let’s break it down step by step:
1. Iterating Over a List
Suppose we have a list of programming languages: languages = ['Swift', 'Python', 'Go']. We can use a for loop to access each language one by one:
Output:
2. Iterating Over a String:
You can also loop through each character in a string:
Output:
3. Using range() With For Loop:
The range() function generates a sequence of numbers. You can iterate over it using a for loop.This code is used to print the numbers as per given limit. Here, The limit is 0 to 4. Note that, The output will start from 0 and ends on 4. Here, the variable i contains numbers 0, 1, 2, and 3.
Output:
4. Else Clause With For Loop:
You can add an optional else block that executes after the loop completes:
5. For Loops Along Conditions
In this example, I used For Loops along with the If-Else statement. Here, i is List and k is a variable containing elements of list. k is used to access elements in the List. I assign conditions also with elements of the List.
1i = ['fish','cat','dog']
2
3for k in i:
4 print(k)
5 if (k=="dog"):
6 print("dogs are so loyal animals")
7
8 elif (k == 'cat'):
9 print("cats are so cute.")
10
11 elif (k=='fish'):
12 print("fish is live in the water")
13 else:
14 print(k,"is are nice animal")
15
16 for i in k:
17 print(i)
1# Output:
2
3fish
4fish is live in the water
5cat
6cats are so cute.
7dog
8dogs are so loyal animals
6. For Loop Along Pass Keyword
In this given example pass keyword works as a placeholder. Pass keyword use when we add code in Loops, Functions, etc... later, But we do not want errors now.
7. For Loops With Break Statement
In Python, the break statement is used to exit a loop prematurely. When encountered, it terminates the loop immediately. Here’s how it works:
Output:

Output:
9. Iterating Over a List
Output:
10. Iterating Over a Dictionary
Output: