Python Basics #12 — Control Flow & Operators
A control-flow statement is a statement that changes a program’s execution order or controls which statements run depending on conditions. Python’s control-flow statements split into two groups: selection statements and iteration statements. The selection group has the if statement (with elif and else as helpers). Most languages use else if, but Python shortens it to elif — remember that. The iteration group has for and while, with continue and break as helpers. Python doesn’t provide a switch selection statement or a do while iteration statement, but if covers switch and while covers do while just fine.
Let’s build a tiny refrigerator program to see how control flow works in practice. The program will, while the fridge is on, check the inside temperature once per minute and lower it by 2 degrees below the maximum if it crosses that threshold.
Before coding, write pseudocode.
Pseudocode is a way to express the structure and algorithm of a program at the design stage using a human language (English, Korean, etc.) instead of a programming language. Think of it like sketching with a pencil before painting. Pseudocode helps you communicate your idea to people who don’t know the language and helps you spot problems with the structure or algorithm before writing real code.
The simplest pseudocode looks like this:
while the fridge is ON
do check temperature once per minute
if temperature > max
do set temperature to max - 2 degreesA more concrete version:
while fridge == ON :
do check temperature
if current_temp >= max_temp:
print 'Adjusting temperature.'
do current_temp = max_temp - 2
else:
print 'Temperature is normal.'
do wait 1 minuteLet’s walk through how the control-flow statements work in this code.
The while loop says: “while the fridge is on, repeat the block below.” The if statement compares the current temperature with the max temperature; if current_temp is greater than or equal to max_temp, run the block under it; otherwise run the block under else.
Below is a flowchart of the same pseudocode:

Flowcharts visualize the entire process and make it easier to understand and analyze. As in the pseudocode, you can see the while loop block and the if / else branches.
Writing pseudocode and drawing flowcharts is a critical, fundamental step in the design phase before coding. Get used to it.
Translating that pseudocode into Python:
import time
current_temp_list = [5, 3, 4, 6, 5, 4]
is_refrigerator_on = True
max_temp = 5
interval_in_second = 2
current_temp = 0
while is_refrigerator_on:
if len(current_temp_list):
current_temp = current_temp_list.pop(0)
else:
print('Exiting program.')
break
if current_temp >= max_temp:
print('Current temperature is {}; adjusting to {}.'.format(current_temp, max_temp - 2))
current_temp = max_temp - 2
else:
print('Current temperature is {}; normal.'.format(current_temp))
time.sleep(interval_in_second)Since this is an example, the temperature-check interval is shortened from 1 minute to 2 seconds, and the current-temperature stream is mocked as a list. The program ends when the list is empty.
Running the code:
Current temperature is 5; adjusting to 3.
Current temperature is 3; normal.
Current temperature is 4; normal.
Current temperature is 6; adjusting to 3.
Current temperature is 5; adjusting to 3.
Current temperature is 4; normal.
Exiting program.Our refrigerator program checks the temperature every 2 seconds and keeps it below the max of 5. In a real program, you’d read from an actual thermometer instead of a predefined list, and the program would be much more complex — but remember that even very complex programs are built up from small ones like this.
To use control-flow statements you need to understand operators. Operators are used to assign values to variables, perform arithmetic, and compare two or more values. Operator categories include arithmetic, assignment, comparison, and logical operators.
Let’s go through each.
1. Arithmetic Operators #
Arithmetic operators perform arithmetic on numbers. Add, subtract, multiply, and divide work just like in regular arithmetic.
| Operator | Operation | Example |
|---|---|---|
+ | Add | x + y |
- | Subtract | x - y |
* | Multiply | x * y |
/ | Divide | x / y |
% | Modulo (remainder) | x % y |
Try them:
>>> a = 5
>>> b = 10
>>> a + b # add
15
>>> b - a # subtract
5
>>> a * b # multiply
50
>>> b / a # divide
2.0The % operator returns the remainder of dividing two numbers:
>>> 10 % 3
1Operator precedence works like normal arithmetic: multiplication and division come before addition and subtraction. To force addition or subtraction first, use parentheses:
>>> 1 + 1 * 2 # multiplication first, then addition
3
>>> (1 + 1) * 2 # addition first, then multiplication
4💡 Today’s tip
In math, dividing by zero is sometimes defined as zero — but in programs you can’t divide by zero. Doing so raises a
ZeroDivisionError.
Let’s trigger the error:
>>> 10 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zeroIn real programs, the divisor is often unknown ahead of time. In those cases, always check that the divisor isn’t zero before dividing:
>>> for i in nums:
... if i != 0: # divide only if divisor is not 0
... print(10 / i)
... else: # if divisor is 0, skip dividing and print 0
... print(0)
...
10.0
5.0
0
3.33333333333333352. Assignment Operators #
Assignment operators assign a value to a variable. As covered in the variables lesson, the = sign here doesn’t mean “the two sides are equal” — it means “assign the value on the right to the variable on the left.”
The four shorthand operators below are essentially two operators combined. For example, += adds x to the variable and assigns the result back.
| Operator | Example | Equivalent |
|---|---|---|
= | x = 1 | x = 1 |
+= | x += 1 | x = x + 1 |
-= | x -= 1 | x = x - 1 |
*= | x *= 2 | x = x * 2 |
/= | x /= 2 | x = x / 2 |
Try them:
>>> x = 1
>>> x += 1 # store x + 1 back into x
>>> x
2
>>> x = 2
>>> x -= 1 # store x - 1 back into x
>>> x
1
>>> x = 2
>>> x *= 2 # store x * 2 back into x
>>> x
4
>>> x = 4
>>> x /= 2 # store x / 2 back into x
>>> x
2.03. Comparison Operators #
Comparison operators compare two values and return True or False.
First, the equal operator: returns True if both sides are equal, False otherwise.
| Operator | Description | Example |
|---|---|---|
== | Returns True if both sides are equal | x == y |
!= | Returns True if both sides are NOT equal | x != y |
> | Returns True if left is greater | x > y |
< | Returns True if left is less | x < y |
>= | Returns True if left is greater than or equal | x >= y |
<= | Returns True if left is less than or equal | x <= y |
>>> print(0 == 0)
True
>>> print(0 == 1)
False
>>> print('one' == 'one')
True
>>> print('one' == 'two')
FalseNot equal (!=) returns True if the two sides differ:
>>> print(0 != 0)
False
>>> print(0 != 1)
True
>>> print('one' != 'one')
False
>>> print('one' != 'two')
TrueLess than (<) returns True if the left side is smaller:
>>> print(0 < 1)
True
>>> print(0 < 0)
False
>>> print(1 < 0)
FalseGreater than (>) returns True if the left side is larger:
>>> print(1 > 0)
True
>>> print(0 > 0)
False
>>> print(0 > 1)
FalseLess than or equal (<=):
>>> print(0 <= 1)
True
>>> print(0 <= 0)
True
>>> print(1 <= 0)
FalseGreater than or equal (>=):
>>> print(1 >= 0)
True
>>> print(0 >= 0)
True
>>> print(0 >= 1)
False4. Logical Operators #
Logical operators also return True or False. Unlike many other languages, Python uses alphabetic keywords (and, or, not) instead of symbols.
The and operator returns True only if all values are True; if any one is False, it returns False.
>>> print(True and True and True)
True
>>> print(True and True and False)
False
>>> print(False and False and False)
FalseThe or operator returns True if at least one value is True:
>>> print(True or True or True)
True
>>> print(True or False or False)
True
>>> print(False or False or False)
FalseThe not operator returns the opposite of its operand. not True → False, not False → True.
>>> print(not True)
False
>>> print(not False)
True
>>> print(not (True and False))
True
>>> print(not (True or False))
False5. Identity Operators #
Identity operators check whether two objects are actually the same object in memory.
list_1 = [1, 2, 3]
list_2 = [1, 2, 3]These two lists have identical contents. What do == and is return for them?
>>> list_1 = [1, 2, 3]
>>> list_2 = [1, 2, 3]
>>> print(list_1 == list_2)
True
>>> print(list_1 is list_2)
False== returns True, but is returns False. Why? Let’s print the memory addresses:
>>> print(hex(id(list_1)))
0x2136d5e5400
>>> print(hex(id(list_2)))
0x2136d5e3840The reason: == compares values and returned True. is compares memory addresses, and since the two objects are different objects in memory, it returned False.
6. Membership Operators #
Membership operators check whether a value is contained in an object. They’re commonly used to check whether a string contains a substring or whether a list contains a value. For dictionaries, remember: membership tests check keys, not values.
>>> print('two' in 'one two three')
True
>>> print(2 in [1, 2, 3])
True
>>> print('key_1' in {'key_1': 'value_1', 'key_2': 'value_2'})
True
>>> print(4 not in [1, 2, 3])
True
>>> print('four' not in 'one two three')
True
>>> print('key_3' not in {'key_1': 'value_1', 'key_2': 'value_2'})
TrueIn this lesson we covered the role of control flow and operators. In the next lesson we’ll dig into the specific usage of each control-flow statement.