For Loop
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
For Loop
Definition: A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Why: The for loop is one of the most important loop types in Python. It is used when you want to execute a block of code a fixed number of times or once for every item in a collection.
Syntax
for variable in sequence:
# code to execute
Example
for i in range(1, 6):
print(i)
Explanation
- range(1, 6): This function generates a sequence of numbers starting from 1 up to (but not including) 6.
- Iterating: The loop runs once for each value in that range. In the first round,
iis 1; in the second,iis 2, and so on. - Versatility: While this example uses numbers,
forloops are widely used to "loop through" lists of names, characters in a string, or keys in a dictionary.
Key Notes
- Automatic Increment: Unlike a
whileloop, you do not need to manually increase the counter variable; Python does it for you. - The
elseKeyword: You can add anelseblock after aforloop to execute code once the loop has finished its iterations. - Nested Loops: You can place a
forloop inside anotherforloop (useful for working with grids or lists within lists).
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute