Python for Loops
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python for Loops

Kishore V


Python for Loops

A for loop in Python is used to iterate over a sequence such as a list, tuple, set, dictionary, or string. It allows you to execute a block of code once for each element in the sequence.

Unlike traditional for loops in languages like C or Java, Python’s for loop works more like an iterator, automatically moving through each item without requiring an index variable.

Basic for Loop Example

Example: Loop Through a List

Delhi Mumbai Chennai

Python automatically assigns each item in the list to the variable city during every iteration.

Note: You do not need to create or manage an index variable manually.

Looping Through a String

Strings are also iterable, meaning you can loop through each character one by one.

Example: Iterating Over Characters

P y t h o n

Each character in the string is accessed sequentially.

The break Statement

The break statement stops the loop immediately, even if there are items left to iterate over.

Example: Stop When a Condition Is Met

10 20

Here, the loop exits as soon as the value 30 is found.

break Before Output

Placing break before a print statement prevents the current value from being displayed.

Example

red

The continue Statement

The continue statement skips the current iteration and moves to the next one.

Example: Skip a Specific Value

dog cow horse

The loop ignores "cat" and continues with the remaining items.

The range() Function

The range() function is used to repeat a block of code a specific number of times.

Example: Basic range()

0 1 2 3 4

This prints numbers from 0 to 4.

range() with Start Value

You can define where the sequence should begin.

Example

3 4 5 6 7

This generates numbers from 3 to 7.

range() with Step Value

You can also control the increment value.

Example: Custom Step

2 6 10 14 18

This increases the number by 4 each time.

else with for Loop

The else block executes only when the loop completes normally (without hitting break).

Example: Loop Completion

0 1 2 3 Loop completed successfully

else Skipped When break Is Used

0 1 2 3

Since the loop ends with break, the else block is skipped.

Nested for Loops

A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.

Example: Nested Loop

small shirt small jacket medium shirt medium jacket

The pass Statement

A for loop cannot be empty. If you need a loop structure without logic (for future implementation), use pass.

Example

# No output (loop passes successfully)

Our website uses cookies to enhance your experience. Learn More
Accept !