Open In Colab

colab

5. Control Structures#

Let’s take a look at a few ways to control our code:

  • if elif else

  • Ternary expressions

  • while

  • for

5.1. If statements and loops#

If statements

if statements are very readable in Python. Remember to indent!

x = -11

# A simple if-else block
if x % 2 == 0:
    print("{0:d} is even".format(x))
else:
    print("{0:d} is odd".format(x))

A block with multiple cases

if x < 0:
    print("negative")
elif x > 0:
    print("positive")
else:
    print("zero")

Ternary expressions combine an if-else block into a single expression. This is useful syntactic sugar when the expression is simple but can sacrifice readability when the conditionals are more involved.

x = 11
print("Even" if x % 2 == 0 else "Odd")

While loops

# A simple while loop
x = 10
count = 0

while x != 1:
    x = x // 2
    count += 1

print(str(count) + "\n")

You can also ‘break’ out of a while loop or ‘continue’ to the next iteration.

# Continue demonstration
x = 10
while x > 0:
    x -= 1
    if x % 2 == 0:
        continue
    print(x)

print("\n")    
# Break demonstration
x = 10
while x > 0:
    x-=1
    print(x)
    if x <= 5:
        break

colab

Try the two loops above with and without break/continue. Does it make sense?

For loops

For loops in Python are sophisticated and powerful as they allow you to iterate over a collection or an iterator.

Let’s look at how we can use the built in ‘range’ command with loops.

#range returns a sequence of integers within a specified range
seq = range(10)
print(seq)
for i in seq:
    print(i)

Let’s look at a nested example

seq = range(4)

for i in seq:
    for j in seq:
        if i <= j:
            print(f"({i},{j})")

Let’s see how we can iterate over dictionaries. Remember dictionaries are collections that hold keys and values, where keys are mapped to specific values.

# create a dictionary
ages = {'susan':23, 'brian':25, 'joe':28, 'al':21} 

# Iterating over elements in a dictionary
for k in ages:
    print( (k, ages[k]) )
('susan', 23)
('brian', 25)
('joe', 28)
('al', 21)

5.2. Local functions#

Like many other programming languages, functions in Python provide and important way of organizing and reusing code. If you find yourself reusing bits of code, you might want to think about creating your own function!

Functions are packed with useful high-level features.

  • Arguments can be positional or specified via keywords.

  • Keyword arguments can be optional and one can also specify default values for them.

  • Order of keyword arguments can be changed.

  • Functions can return multiple values.

  • Use the def keyword to define a function, and the return keyword to return the result.

  • Functions parameters and any variables declared within the body of the function have local scope.

  • You have access to variables in the enclosing scope.

  • An optional string literal can be used as the very first statement. This is the function’s docstring.

  • Arguments are passed by reference. This has implications for mutable objects.

  • If return is used by itself or if the function falls off the end, None is returned.

Let’s take a look at building our own functions.

# Function definitions and scope.

def factorial2(n):
    "Returns n!, the factorial of a non-negative integer n"
    # The variables n and result have local scope.
    
    result = 1
    while n > 0:
        result *= n
        n -= 1
    return result

Let’s now use the function we created above.

num = 10

factorial2(num)

Let’s create another function, this time let’s use more than one input. This will help us learn positional and keyword arguments, and how to set default values.

#Simple exponential function
def func2(x, y=0, z=0):
    return x**2 + y**2 - z**2
# we can call func2 with 1, 2 or 3 arguments.
print(func2(2))
print(func2(2,2))
print(func2(2,2,2))
# We can also use keywords when invoking func2. 
print(func2(1,y=2, z=3))
print(func2(1, z=3, y=2))
print(func2(x=1, y=2, z=3)) 

Note: keyword arguments must follow positional arguments

Thus the following is not allowed. func2(y=2, z=3, 1)

Keywords also need to match the parameters.

The following is not allowed. func2(a=1,b=2,c=3)

colab

Let’s try out what we’ve learnt. Try to complete the following:

  • Write a function that takes three integers as input and returns the largest of the three.

  • Write a function that takes three integers as input and returns True if either all three integers are even or all three integers are odd, and False otherwise.

  • Write a function that takes a list as an input and returns a new list that contains the items in the input list reversed.

5.3. Further reading#

Automate the Boring Stuff with Python by Al Sweigart.

For additional practice, try solving practice problems available at the following web sites.

  • edabit - (look at problems rated ‘Easy’ and ‘Medium’)

  • PRACTICE PYTHON - (look at problems rated ‘one’ and ‘two’ chillies)