Introduction to Control Flow and Functions in Python.

CONTROL FLOW

What is control Flow?
  • A program's control flow is the order in which the program's code executes.
  • The control flow of a Python program is regulated by conditional statements, loops, and function calls.
Python if Statement

You use the if statement to execute a block of code based on a specified condition.
The syntax of the if statement is as follows:

if condition:
    if-block

The if statement checks the condition first.
If the condition evaluates to True, it executes the statements in the if-block. Otherwise, it ignores the statements.
Example

marks = input('Enter your score:')
if int(marks) >= 40:
    print("You have passed")

Output

Enter your score:46
You have passed
Python if…else statement

Used when you want to perform an action when a condition is True and another action when the condition is False.
Here is the syntax

if condition:
    if-block;
else:
    else-block;
  • From the above syntax, the if...else will execute the if-block if the condition evaluates to True. Otherwise, it’ll execute the else-block.

An example to illustrate how to use the if...else statement:

marks = input('Enter your score:')
if int(age) >= 40:
    print("You have passed.")
else:
    print("You have failed.")
Python if…elif…else statement

It is used to check multiple conditions and perform an action accordingly.
The elif stands for else if.

Here is the syntax:

if if-condition:
    if-block
elif elif-condition1:
    elif-block1
elif elif-condition2:
    elif-block2
...
else:
    else-block
  • The elif statement allows you to check multiple expressions for true and execute a block of code as soon as one of the conditions evaluates to true.
  • If no condition evaluates to true, the if...elif...else statement executes the statement in the else branch.

Example

marks = input('Enter your score:')

your_marks = int(marks)

if your_marks >= 70:
    print("Your grade is A")
elif your_marks >= 60:
    print("Your grade is B")
else:
    print("null")

Output

Enter your score:70
Your grade is A
Python for Loop

To execute a block of code multiple times in programming you use for loop
Here is the syntax:

for index in range(n):
    statement
  • In this syntax, the index is called a loop counter. And n is the number of times that the loop will execute the statement.
  • The range() is a built-in function in Python that generates a sequence of numbers: 0,1, 2, …n-1. Example
for index in range(5):
    print(index)

Output

0
1
2
3
4

Specifying the starting value for the sequence
The range() function allows you to specify the starting number like this:

range(start,stop)

Example

for index in range(1, 4):
    print(index)

Output

1
2
3
4

Specifying the increment for the sequence
By default, the range(start, stop) increases the start value by one in each loop iteration.
To specify increment sequence, use the following syntax:

range(start, stop, step)

The following example shows all odd numbers from 0 to 10:

for index in range(0, 11, 2):
    print(index)

output

0
2
4
6
8
10

Using Python for loop to calculate the sum of a sequence
The following example uses the for loop statement to calculate the sum of numbers from 1 to 50:

sum = 0
for num in range(51):
    sum += num
print(sum)

Output

1275
Python while Loop

Python while statement allows you to execute a code block repeatedly as long as a condition is True
Here is the syntax:

while condition:  
   body
  • The condition is an expression that evaluates to a Boolean value, either True or False.
  • The while statement checks the condition at the beginning of each iteration and executes the body as long as the condition is True. An example that uses a while statement to show 5 numbers from 0 to 4 to the screen:
max = 5
counter = 0

while counter < max:
    print(counter)
    counter += 1

Output

0
1
2
3
4
Python break Statement
  • Break statement in python is used to terminate a for loop and a while loop prematurely regardless of the conditional results. Example:
for index in range(0, 11):
    print(index)
    if index == 3:
        break

Output

0
1
2
3

FUNCTIONS IN PYTHON

A function is a block of organized, reusable code that is used to perform a single, related action.

Defining a Function

Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]
Calling a Function

When you want to use a function, you just need to call it. A function call instructs Python to execute the code inside the function.

Returning a value

A function can perform a task like the greet() function. Or it can return a value. The value that a function returns is called a return value.
To return a value from a function, you use the return statement inside the function body.

Function Parameters and Arguments

Parameter and argument can be used for the same thing but from functions perspectives;

  • A parameter is the variable listed inside the parentheses in the function definition.

  • An argument is the value that are sent to the function when it is called.
    From this example;

def addNumbers(a, b):
    sum =a + b
    print("The sum is " ,sum)
addNumbers(2,5)
  • We have a function called addNumbers which contains two values inside the parenthesis, a, and b. These two values are called parameters.
  • We have passed two values along with the function 2 and 5. These values are called arguments.
Python functions with multiple parameters

A function can have zero, one, or multiple parameters.
The following example defines a function called sum() that calculates the sum of two numbers:

def sum(a, b):
    return a + b
total = sum(1,20)
print(total)

output

21

In the above example, the sum() function has two parameters a and b, and returns the sum of them. Use commas to separate multiple parameters.

Types of Arguments in Python Function Definition
  • Default arguments.
  • Keyword arguments.
  • Positional arguments.
  • Arbitrary positional arguments.
  • Arbitrary keyword arguments
Python Recursive Functions
  • A recursive function is a function that calls itself and always has condition that stops calling itself.
Where do we use recursive functions in programming?
  • To divide a big problem that’s difficult to solve into smaller problems that are easier-to-solve.
  • In data structures and algorithms like trees, graphs, and binary searches.

Recursive Function Examples
1.Count Down to Zero

  • countdown()takes a positive number as an argument and prints the numbers from the specified argument down to zero: def countdown(n):
def countdown(n):
    print(n)
    if n == 0:
        return  # Terminate recursion
    else:
        countdown(n - 1)  # Recursive call
countdown(5)

Output

5
4
3
2
1
0

2.Calculating the sum of a sequence
Recursive functions makes a code shorter and readable.
Suppose we want to calculate the sum of sequence from 1 to n instead of using for loop with range() function we can use recursive function.

def sum(n):
    if n > 0:
        return n + sum(n - 1)
    return 0
result = sum(100)
print(result)
Python Lambda Expressions

A lambda function is a small anonymous function that can take any number of arguments, but can only have one expression.
Syntax

lambda arguments : expression

Examples:

def times(n):
    return lambda x: x * n
double = times(2)
result = double(2)
print(result)
result = double(3)
print(result)

From the above example times() function returns a function which is a lambda expression.

Python Decorators.
  • A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure.
  • Decorators are usually called before the definition of a function you want to decorate.

Here is a simple syntax for a basic python decorator

def my_decorator_func(func):
def wrapper_func():
        # Do something before the function.
        func()
        # Do something after the function.
    return wrapper_func

To use a decorator ,you attach it to a function like you see in the code below.

@my_decorator_func
def my_func():

    pass

12