Python Interactive Guide - Step 2 Control Flow (3) - Loops (1): for Loops
- This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
- The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
- You can run and experiment with every code example.
Feel free to try things out - reloading the page will reset everything.
This is a continuation of “Step 2 Control Flow.”
2.2. Loops
Loops are control flow structures that allow you to execute the same process multiple times.
Python has two main types of loops:
forloop: Repeats a process for each element in a list or other iterablewhileloop: Repeats a process as long as a condition isTrue
2.2.1. for Loops
Basics of for Loops
The for loop sequentially executes a process for each element in an iterable object, such as a list.
- In the
for fruit in fruitsline, each element in thefruitslist is assigned to thefruitvariable in sequence - The indented block below is executed repeatedly for each element in
fruits
flowchart TD
START[Start] --> INIT["fruits = ['apple', 'banana', 'orange']"]
INIT --> FOR{"for fruit in fruits"}
FOR -->|No more elements| END["Loop ended"]
FOR -->|Next element exists| LOOP_BODY["Loop process\n(print(fruit))"]
LOOP_BODY --> FOR
linkStyle 2 stroke:red,stroke-width:2px;
linkStyle 3 stroke:green,stroke-width:2px;
Output the number of characters in each element of fruits, and then output the total number of characters.
(The length of a string, like lists, can be obtained using the len function)
Sample Solution
What are Iterables?
Objects that can be used in looping constructs like for loops are called iterables.
In Python, the following objects are treated as iterables:
- Lists:
["apple", "banana", "orange"] - Tuples:
(1, 2, 3) - Sets:
{1, 2, 3} - Dictionaries:
{"name": "Alice", "age": 25} - Strings:
"Python" - Return values of the
rangefunction:range(5)
Lists, Tuples, and Sets
Dictionaries
Dictionaries are also iterables. When used in a for loop, they return the keys.
The following dictionary methods also return iterable objects:
.keys()method: Returns the list of keys.values()method: Returns the list of values.items()method: Returns the list of key-value pairs
- In the
.items()method example above, unpacking is used to break down the key-value pair into separatekeyandvaluevariables.
Strings
Strings are also a type of iterable object.
When used in a for loop, they allow processing one character at a time.
The range Function
The range function generates a sequence of numbers in a specified range.
The range function has multiple usage patterns similar to list slicing:
| Usage | Function |
|---|---|
range(stop) |
Generate integers from 0 to (stop - 1) in sequence |
range(start, stop) |
Generate integers from start to (stop - 1) in sequence |
range(start, stop, step) |
Generate integers from start to (stop - 1) with the specified step interval |
range(stop): Generate integers from 0 to (stop - 1) in sequence
range(start, stop): Generate integers from start to (stop - 1) in sequence
range(start, stop, step): Generate integers from start to (stop - 1) with the specified step interval
Like slicing, specifying a negative number for step generates numbers in reverse order.
range function returns a “lazy evaluation” object that generates values as needed, rather than creating a list of numbers.This allows it to handle large ranges of numbers while keeping memory usage low.
Create a program that outputs numbers from 1 to 10 using a for loop and the range function.
Sample Solution
Output a multiplication table like the one below.
(Hint: Use nested for loops)
1 x 1 = 1
1 x 2 = 2
...
9 x 9 = 81
Sample Solution
Loop Control Statements
break: Terminating a Loop
The break statement allows you to terminate a loop early and exit from it.
In this example, the fruits list is processed sequentially, but when “banana” is found, the loop is terminated by the break statement. Therefore, “orange” and subsequent elements are not processed.
flowchart TD
START[Start] --> INIT["fruits = ['apple', 'banana', 'orange', 'grape', 'melon']"]
INIT --> FOR{"for fruit in fruits"}
FOR -->|No more elements| END["Loop ended"]
FOR -->|Next element exists| ELEMENT_PROCESS
subgraph ELEMENT_PROCESS[Loop Process]
LOOP_START["Loop start"] --> CHECK{"if fruit == 'banana'"}
CHECK -->|No| NEXT["Proceed to next process"]
CHECK -->|Yes| BREAK["break\n(terminate loop)"]
end
NEXT --> FOR
BREAK --> END
style BREAK fill:#ffeb3b,stroke:#333,stroke-width:2px
linkStyle 2 stroke:red,stroke-width:2px;
linkStyle 3 stroke:green,stroke-width:2px;
linkStyle 5 stroke:red,stroke-width:2px;
linkStyle 6 stroke:green,stroke-width:2px;
Create a program that finds the first even number in a list and outputs it, then terminates the process.
- Prepare a list
numbers = [15, 7, 3, 9, 4, 11, 2] - Check each value in the list sequentially and display the first even number found
- Terminate the loop when an even number is found
Sample Solution
Next, let’s improve the program to display “No even numbers exist” if no even numbers are found.
(Hint: Create a variable that becomes True if an even number exists, and False otherwise.)
Sample Solution
continue: Skipping Loop Iterations
The continue statement is a control flow statement used to skip the remaining part of the current loop iteration and move to the next iteration.
Unlike break which terminates the entire loop, continue only skips the current iteration.
In this example, each number in the list is checked, and if it’s even, the continue statement skips further processing. As a result, only odd numbers are displayed.
flowchart TD
START[Start] --> INIT["numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"]
INIT --> FOR{"for num in numbers"}
FOR -->|No more elements| END["Loop ended"]
FOR -->|Next element exists| ELEMENT_PROCESS
subgraph ELEMENT_PROCESS[Loop Process]
LOOP_START["Loop start"] --> CHECK{"if num % 2 == 0"}
CHECK -->|No| NEXT["Proceed to next process\n(print(f'Number: {num}'))"]
CHECK -->|Yes| CONTINUE["continue\n(to next iteration)"]
end
NEXT --> FOR
CONTINUE --> FOR
style CONTINUE fill:#80deea,stroke:#333,stroke-width:2px
linkStyle 2 stroke:red,stroke-width:2px;
linkStyle 3 stroke:green,stroke-width:2px;
linkStyle 5 stroke:red,stroke-width:2px;
linkStyle 6 stroke:green,stroke-width:2px;
Difference between break and continue
| Keyword | Function | Target |
|---|---|---|
break |
Completely terminates a loop | Entire loop |
continue |
Skips the current iteration and moves to the next | Current iteration |
Create a program that outputs only numbers that are neither multiples of 3 nor multiples of 5 from the numbers 1 to 20 using the continue statement.
Sample Solution
break and continue in Nested Loops
When loops are nested, break and continue statements behave as follows:
- A
breakstatement terminates only the innermost loop containing it - A
continuestatement skips only the current iteration of the innermost loop containing it
Create a multiplication table that excludes patterns with 3 x ? or ? x 3.
Example Solution
Advanced for Loops
enumerate Function: Loops with Indices
The enumerate function provides both the index (position) and value for each element in an iterable.
You can also change the starting value of the index:
zip Function: Processing Multiple Iterables Simultaneously
The zip function is useful for processing multiple iterables simultaneously.
(Unlike nested for loops, it’s used when you only need pairs at the same position)
Note that zip stops when the shortest iterable is exhausted.
for-else Statement
You can add an else clause to a for loop. The else block is executed when the loop completes normally (i.e., was not terminated by a break statement).
As shown above, the for-else statement allows you to concisely write code to search for an element in a list and handle the case when it’s not found.
Rewrite the following exercise (which we handled with break earlier) using the for-else statement to eliminate the flag variable:
- Prepare a list
numbers = [15, 7, 3, 9, 5, 11, 3] - Check each value in the list sequentially and display the first even number found
- Terminate the loop when an even number is found
- Output “No even numbers exist” if no even numbers are found
Sample Solution
Summary of for Loops
forloops perform repeated processing for each element in an iterable (list, string, tuple, dictionary, etc.)- The
rangefunction allows repeated processing over a specified range of numbers breakstatements terminate loops, whilecontinuestatements skip iterations- The
enumeratefunction lets you get both the index and element simultaneously - The
zipfunction allows parallel processing of multiple iterables - The
for-elseconstruct lets you specify what to do when a loop completes normally (without being broken)
Create a program that processes student grade data according to the following requirements:
-
Use the following student grade data:
students = [ {"name": "John", "score": 85}, {"name": "Alice", "score": 72}, {"name": "Michael", "score": 93}, {"name": "Emily", "score": 68}, {"name": "Robert", "score": 76} ] -
Calculate and display the following information:
- Average score of all students
- Highest score and the name of that student
- List of students with scores of 80 or higher (in the format “Name: Score”)
- Number of students who passed (70 or higher) and failed
-
Format the output to be easily readable