
Table of Contents(目次)
What Is Python Control Flow?
A program is basically executed line by line from top to bottom. However, with this alone, it is not possible to describe complex processes.

It is necessary to create branches depending on conditions, repeat the same process, and handle errors. These mechanisms are collectively referred to as control flow (Control Flow).


Details of each topic will be explained in dedicated lectures. Here, the goal is simply to give you an overview of what you will learn in the control flow section.
Four Categories of Python Control Flow
Python control flow can be broadly divided into the following four categories:
- Conditional branching (if statements)
- Iteration (for loops)
- Functions
- Exception handling
By understanding these four mechanisms, you will be able to create the flow of processing in Python exactly as you intend.
Overview of Python Conditional Branching (if Statements)
This is the mechanism that allows a program to “change its behavior depending on the situation.” For example, you can express real-world decisions in code, such as “if it rains, bring an umbrella” or “if it’s sunny, go for a walk.”
Basics of if, elif, and else
The core syntax of conditional branching is as follows:
- if is used to write “if … then” conditions
- elif allows you to add another condition if the previous ones were not satisfied
- else specifies what happens when none of the conditions are met
You can also nest if
statements inside one another to create more detailed branching.
The detailed syntax will be explained in dedicated lectures, but for now, let’s look at a simple example. Suppose we want to branch actions depending on the weather. In that case, we combine the keywords if
, elif
, and else
as shown below:
weather = 'sunny'
if weather == 'rain':
print('Bring an umbrella!')
elif weather == 'sunny':
print('Let’s go for a walk today')
elif weather == 'cloudy':
print('Better hang the laundry indoors')
else:
print('Unfamiliar weather condition')
Comparison Operators and Other Keywords Used in Conditional Expressions (and, or, bool, None)
You will also learn in detail about comparison operators (equal, not equal, etc.) and other keywords (and, or, bool, None) used in conditional expressions.
- Comparison operators (==, !=, <, >, <=, >=)
- Used when comparing values
- Example:
==
means “equal to,”!=
means “not equal to”
- and / or
- Allow you to combine multiple conditions
- Boolean type (True / False)
- The fundamental values used in conditional branching
- None
- A special value representing “nothing,” which is treated as False in conditional expressions
score = 75
if score >= 70:
print('Excellent!')
elif score < 40:
print('Retake required')
else:
print('Pass')
Overview of Python Loops
In Python, loops are used when you need to repeat the same process. For example, you can sum up product prices, measure temperature until it reaches a target, or process unfinished tasks.
Basics of for Loops
A for
loop is used to process the elements of an iterable, such as a list or dict, in sequence. The basic form is for variable in iterable:
.
The following code adds up the total price of fruits. The loop runs for each element stored in the dict.
fruits_prices = {
'apple': 100,
'banana': 150,
'orange': 120
}
total_price = 0
# Repeat for each value (price) in the dict and add it to total_price
for price in fruits_prices.values():
total_price += price # Add the price to the total
print('Total price of fruits:', total_price)
Basics of while Loops
A while
loop continues to execute as long as the condition is satisfied. When the condition becomes False, the loop ends.
for
loops are often used when the number of iterations is predetermined. while
loops, on the other hand, are used when the number of repetitions is unknown, and the process should continue as long as a certain condition is true.
The following code is an example scenario. Suppose we want to increase the room temperature to a certain target using a heater control program. After retrieving the current temperature and the target temperature, the heater stays on as long as the current temperature is below the target. Because we don’t know when the target will be reached, the loop keeps monitoring the room temperature and repeats the process until the target is met. Once the temperature reaches the target, the loop ends and the heater is turned off.
# Note: This example uses functions that don’t actually exist,
# so it will not run as-is.
current_temp = get_current_temperature()
target_temp = 22
while current_temp < target_temp:
heater_on() # Turn on the heater
current_temp = get_current_temperature() # Get the current temperature again
heater_off() # Target temperature reached, turn off the heater
Overview of Loop Control (continue / break / else)
Within a loop, you can skip processing based on conditions or terminate the loop early.
continue
- Skips the remaining process of the current iteration and moves on to the next one
- Example: Skip processing if the condition is not met
break
- Ends the loop prematurely
- Example: Stop the loop once the target is reached
else (used together with a loop)
- Executes only when the loop finishes without being interrupted by break
- Example: Display “No issues found” after checking all elements
Here is an example using continue to build a list of unfinished tasks. The variable "tasks" holds task names and whether each task is completed. The for loop iterates through each task, and if the task is already completed, it uses continue to skip the remaining process. In this way, completed tasks are prevented from being added to the "unfinished_tasks" list.
tasks = [
{'name': 'wash dishes', 'done': True},
{'name': 'do homework', 'done': False},
{'name': 'clean room', 'done': False},
{'name': 'walk dog', 'done': True}
]
unfinished_tasks = []
for task in tasks:
if task['done']:
continue # If completed, go back to the start of the loop
unfinished_tasks.append(task['name'])
print('Unfinished tasks:', unfinished_tasks)
Overview and Role of Functions in Python
A function is a named block of code that encapsulates a specific process in a program.
By using functions, you don’t need to write the same process repeatedly. Instead, you can simply call the function name, and the process will be executed. Functions can also accept values from outside (arguments) and return results when necessary.
Basic Role of Functions
When creating a function, write the function name after def
. You can return a result using return
.
The following code retrieves the current time and changes the greeting depending on the time of day. By defining this process as a function, you can call it as greeting()
to get the appropriate greeting.
from datetime import datetime
def greeting():
hour = datetime.now().hour
if 5 <= hour < 12:
return "Good morning!"
elif 12 <= hour < 18:
return "Good afternoon!"
elif 18 <= hour < 22:
return "Good evening!"
else:
return "Good night!"
message = greeting()
print(message)
Arguments
Functions can take arguments to receive values from outside and use them within the function.
The following example adds two values received as arguments and returns their total with return
.
def add_price(price1, price2):
total = price1 + price2
return total
result = add_price(100, 250)
print("Total price:", result)
Variable Scope (Valid Range of Variables)
Variables have a valid scope. A variable created inside a function cannot be accessed from outside the function. Therefore, a variable created in Function A cannot be directly accessed from Function B. If you need data generated in Function A, you must either return it from Function A or use a global variable.
def make_discount(price):
discount = price * 0.8
return discount
print(make_discount(200)) # 160.0 is returned via return and printed
print(discount) # Cannot directly access the "discount" variable from outside the function
Basic Concept of Exception Handling in Python
During program execution, unexpected errors may occur. Exception handling is a mechanism that detects such errors and allows the program to continue running instead of crashing when an exception occurs.
In Python, exceptions are handled using try
and except
.
Basic Syntax (try / except / else / finally)
- try
- Write the code that may raise an error.
- except
- Write the handling code for the error. Multiple exceptions can be handled separately.
- else
- Executed if no exceptions occur. Optional.
- finally
- Executed regardless of whether an exception occurred. Often used for releasing resources. Optional.
try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Division by zero is not allowed")
else:
print("Result:", result)
finally:
print("Process finished")
Custom Exceptions
In addition to built-in exceptions, Python allows you to define your own. This is useful when you want to raise an error based on custom rules.
- raise
- The keyword used to raise a custom exception.
- except
- Used to catch the custom exception and safely continue processing.
# Define a custom error
class OutOfStockError(Exception):
pass
# Raise "OutOfStockError" when stock is 0
def buy_item(stock):
if stock <= 0:
raise OutOfStockError("Out of stock")
print("Purchase successful")
# If an error occurs in the try block, the except block is executed
try:
buy_item(0)
except OutOfStockError as e:
print(e)