Flow control


Martin McBride, 2018-04-08
In section Python language



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

If you found this article useful, you might be interested in the book Functional Programming in Python, or other books, by the same author.

<<Prev

Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020