Flow Control

Functions

A function in python is a group statements that perform a particular task

# This function calculates Body Mass Index
def calculateBodyMassIndex(weight_kg, height_m):

    body_mass_index = weight_kg / pow(height_m, 2)
    rounded_bmi = round(body_mass_index, 2)

    return rounded_bmi
# lets try
calculateBodyMassIndex(67, 1.6)
26.17

Creating a function

To create a function, we need the following: - The def keyword - A function name - Round brackets () and a colon : - A function body- a group of statements

def greeter():
    message = 'Hello'
    print(message)
  • To execute a function, it needs to be called
  • To call a function, use its function name with parentheses ()
greeter()
Hello

Function Parameters/Arguments

  • When calling a function, we can pass data using parameters/arguments
  • A parameter is a variable declared in the function. In the example below, number1 and number2 are parameter
  • The argument is the value passed to the function when its called. In the example below 3 and 27 are the arguments
# define the function
def addNumbers(number1, number2):
    sum = number1 + number2
    print(sum)

# Call the function
addNumbers(3, 27)
30
# setting a default argument
def greet(name='you'):
    message = 'Hello ' + name
    print(message)

greet('Tinye')
greet()
Hello Tinye
Hello you

Return Statement

The return statement is used to return a value to a function caller

def addNumbers(number1, number2):
    sum = number1 + number2
    return sum

summation = addNumbers(56, 4)
print(summation)
60

### lambda functions - Lambda functions are functions that donot have names - The body of a lambda function can only have one expression, but can have multiple arguments - The result of the expression is automatically returned

Syntax: python lambda parameters: expression

# Example of lambda function
calculateBMI = lambda weight_kg, height_m: round((weight_kg/(height_m ** 2)), 2)
# Calling a labda function
calculateBMI(67, 1.7)
23.18

Practice functions

Calculate CGPA

# Assume 4 course units
# 1. Math - A
# 2. Science - B
# 3. SST - B
# 4. English - C


def calculate_CGPA(GPs_list, CUs_list):
    length = len(GPs_list)
    product_sum = 0

    for item in range(length):
        product_sum += GPs_list[item] * CUs_list[item]

    CUs_sum = sum(CUs_list)

    CGPA = product_sum / CUs_sum

    return CGPA

# calculate_CGPA(4, 5)

Get someones age given birth month and year

def getAge(month, year):
    month_diff = 12 - month
    year_diff = 2023 - year

    return str(year_diff) + ' years ' + str(month_diff) + ' months'  
    
age = getAge(year=2000, month=10) # keyword argument
age2 = getAge(10, 2000) # positional argument

print(age)
23 years 2 months

Loops

  • Loops are used to repetitively execute a group of statements
  • we have 2 types, for and while loop

For Loop

A for loop is used to loop through or iterate over a sequence or iterable objects

Syntax:

for variable in sequence:
    statements
pets = ['cat', 'dog', 'rabbit']
# iterate through pets
for pet in pets:
    print(pet)
cat
dog
rabbit
# convert all weights in list from kg to pounds
weights_kg = [145, 100, 76, 80]
weights_pds = []

for weight in weights_kg:
    pounds = weight * 2.2
    rounded_pds = round(pounds, 2)
    weights_pds.append(rounded_pds)

print(weights_pds)
[319.0, 220.0, 167.2, 176.0]
# Display all letters in a name
name = 'Shafara'

for letter in name:
    print(letter)
S
h
a
f
a
r
a
# print 'Hello you' 5 times
for step in range(0, 5):
    print('Hello you')
Hello you
Hello you
Hello you
Hello you
Hello you

While loop

  • The while loop executes a given group of statements as long as the given expression is True

Syntax:

while expression:
    statements
counter = 0

while counter < 5:
    print('Hello you')
    counter += 1
Hello you
Hello you
Hello you
Hello you
Hello you
# Convert the weights in the list from kgs to pounds
weights_kg = [145, 100, 76, 80]
weights_pds = []

counter = 0
end = len(weights_kg)

while counter < end:

    pound = weights_kg[counter] * 2.2
    rounded_pds = round(pound, 3)
    weights_pds.append(rounded_pds)

    counter += 1

print(weights_pds)
[319.0, 220.0, 167.2, 176.0]
Back to top