Flow control

Conditions, if statements, loops.
Conditions
True # boolean True (capitalised)
False # boolean False (capitalised)
x > 3 # True if x is greater than 3, else False
x < 3 # True if x is less than 3, else False
x == 3 # True if x is equal to 3, else False
x >= 3 # True if x is greater than or equal to 3,
# else False
x <= 3 # True if x is less than or equal to 3,
# else False
x != 3 # True if x is not equal to 3, else False
k = [2, 4, 6, 8]
x in k # True if value x is present in
# sequence k, else False
x not in k # True if value x is not present in
# sequence k, else False
a is b # True is a and b are the same object
# equivalent to id(a)==id(b)
a is not # True is a and b are not the same object
Compound conditions
not x > 3 # True if x is NOT greater than 3
# equivalent to x <= 3
x < 3 and y < 2 # True if x is less than 3 AND y is less than 2
x < 3 or y < 2 # True if x is less than 3 OR y is less than 2
5 <= z < 10 # True if z is greater than or equal to 5 AND
# z is less than 10
Falsey and truthy values
0 # 0 or 0.0 count as False
# Any non-zero number counts as True
[] # Any empty collection counts as False
# Any non-empty collection counts as True
# Collections include lists, tuples, dicts, sets
None # The value None counts as False
If statements
if x > 10:
print('big') # Only executed if x is greater than 10
if x > 10:
print('big') # Only executed if x is greater than 10
else:
print('small') # Executed if x is less than or equal to 10
if x > 10:
print('big') # Only executed if x is greater than 10
elif x > 5:
print('mid') # Only executed if x is greater than 5 but
# less than or equal to 10
else:
print('small') # Executed if x is less than or equal to 5
While loops
a = 0
while a < 3:
print(a) # prints 0 1 2
a += 1
while True:
print('.') # prints . . . forever
# useful with a break statement
For loops
for i in range(5): # from 0 up to but not including 5
print(i) # prints:
# 0
# 1
# 2
# 3
# 4
for i in range(2, 5): # from 2 up to but not including 5
print(i) # prints:
# 2
# 3
# 4
for i in range(1, 9, 2): # from up to but not including 9
print(i) # in steps of 2
# prints:
# 1
# 3
# 5
# 7
k = [20, 50, 30 10]
for x in k: # loops over each element in k
print(x) # prints:
# 20
# 30
# 50
# 10
for i, x in enumerate(k): # loops over each element in k
print(i, x) # prints:
# 0 20
# 1 30
# 2 50
# 3 10
m = ['ab', 'cd', 'ef', 'gh']
n = [10, 20, 30, 40]
for a, b in zip(m, n): # loops over each element in m, n
print(i, x) # prints:
# ab 10
# cd 20
# ef 30
# gh 40
Join the PythonInformer Newsletter
Sign up using this form to receive an email when new content is added:
Popular tags
2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest