Control Flow
Listing the fundamental and commonly used control flow structures in Python.
if
if.py
>>> x = 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
More
Short hand if
short_if.py
>>> a = 25
>>> b = 15
>>> if a > b: print("A is greater than B")
>>> print("B") if a <= b else print("A")
A is greater than B
A
while
for
for.py
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
cat 3
window 6
defenestrate 12
range
range.py
>>> for i in range(3):
... print(i)
... print("range(3)--------->")
>>> for i in range(5, 10):
... print(i)
... print("range(5, 10)--------->")
>>> for i in range(0, 10, 2):
... print(i)
... print("range(0, 10, 2)--------->")
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
... print("range(len(a))--------->")
0
1
2
range(3)--------->
5
6
7
8
9
range(5, 10)--------->
0
2
4
6
8
range(0, 10, 2)--------->
0 Mary
1 had
2 a
3 little
4 lamb
range(len(a))--------->
try
try.py
>>> try:
... zero_division = 10 / 0
... except ZeroDivisionError as zero_error:
... print(f"ERROR: {zero_error}")
... except:
... print("Global except clause")
... finally:
... print("Justing print the finally")
ERROR: division by zero
Justing print the finally
break, continue and else on loops
- The break statement breaks out the innermost enclosing for or while loop.
- The else statement in loops is executed when the loop terminates through exhaustion, but not when the loop is terminated by a break statement.
break_else.py
>>> for n in range(2, 10):
>>> for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
- The continue statement continues with the next iteration of the loop.
continue.py
>>> for num in range(2, 10):
>>> if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
match
- A match statement takes an exmpression and compares its value to sucessive patterns using the case blocks.
- This is similar to a switch statement but it's more similiar to patter matching.
- Only the first pattern that matches gets executed.
- There are many use cases that will be explorer more in this documentation.
match.py
>>> def http_error(status):
>>> match status:
... case 400:
... return "Bad request"
... case 404:
... return "Not found"
... case 418:
... return "I'm a teapot"
... case _:
... return "Something's wrong with the internet"