Skip to content

Functions

Dictionary

Functions are reusable pieces of programs.

Functions allow us to give a name to a block of statements, allowing us to run that block using the specified name anywhere in our application and any number of times.

What does it exactly mean?

Remember we have been using print() statements. It always performed a predefined task. Well, it turns out it was a function all along.

Example

Alternative print statements,

1
2
3
4
5
6
age = 25
name = "Bob"

print(name, "is", age, "years old.")
print("{} is {} years old.".format(name, age))
print(f"{name} is {age} years old.")

Result

1
2
3
Bob is 25 years old.
Bob is 25 years old.
Bob is 25 years old.

I would suggest you use line number 6 format.

Why use Functions?

Think of a function as a box that performs some operations. We give that box input and in return, it gives back an output after performing some set of operations.

Now, what we have is a box and that box can be used with different inputs, we don't have to write the same set of instructions for every other input value. This made our code simple and to the point.

Primary benefits are:

  • Reusability : A function can be used again and again.
  • Simplicity : Functions are easy to use and make code readable. We only need to know the purpose of a function and when to use it without focusing on inner working.

Info

The input to a function is OPTIONAL. You can just call a function without any input to perform a set of instructions.

Let's go through an example

Suppose the task in our hand is to find the smallest number between 2 integers.

First, let's go with the code where you don't know about functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
num1 = 100
num2 = 50
num3 = 200

minimum = num1      # define num1 as minimum

if num2<minimum:    # condition is True
    minimum = num2  # minimum has been assigned num2's value

if num3<minimum:    # condition is False 
    minimum = num3  

print(f"Minimum is: {minimum}")
Result
1
Minimum is: 50

As we see, for every defined integer, we need to write the if statement again.

Now, let's do this with help of a function. We will use in-built function min().

1
2
3
4
5
6
num1 = 100
num2 = 50
num3 = 200

minimum = min(num1, num2, num3)
print(f"Minimum is: {minimum}")
Result
1
Minimum is: 50

Now the code looks cleaner and it is easier to write.

Types of Functions

There are two basic types of functions

  • Built-in functions
  • User-defined functions

We have used built-in function such as len(), min(), and print(). We can also create our own functions that perform the tasks we require.

Creating Functions

A Function can be defined using the def keyword in the following format:

1
2
3
4
def function_name(parameters):
    """
    define a set of operations
    """
  • The function name is what we use to identify the function.
  • The parameters of a function are the inputs for that function. These inputs can be used within the functions. Parameters are optional.
  • The body contains the set of operations.

Our first function.

1
2
3
4
def greet():            # define a function using def keyword
    print("hello")      # print hello

greet()                 # calling a function
Result
1
hello

Functions Parameters

Dictionary

Parameters are the means of passing data to a function that can be used by the function to perform some meaningful task.

When creating a function, we must define the number of parameters and their names. These names are only relevant to that function block and won’t affect variable names elsewhere in the code.

Info

The names given inside the parenthesis of a function definition are called parameters, whereas the values you supply to the function are called arguments.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def get_minimum(first_num, second_num):
    if (first_num < second_num):
        print(f"{first_num} is minimum")
    elif (first_num==second_num):
        print(f"{first_num} is equal to {second_num}")
    else:
        print(f"{second_num} is minimum")

value1 = 100
value2 = 50

get_minimum(10, 12)             # directly pass literal values
get_minimum(value1, value2)     # pass variable as argument
Result
1
2
10 is minimum
50 is minimum

We are passing value1 and value2 to the function. The positions of parameters are important. In the above case, the value of value1 will be assigned to first_num and likewise, the value of value2 will be assigned to second_num.

Return Statement

Dictionary

The return statement is used to return values from a function i.e. break out of the function.

Returning a value from any function is optional. Any remaining lines of the code block after the return statement will not be executed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def get_maximum(first_num, second_num):
    if (first_num > second_num):
        return first_num

    print("OLA AMIGO")
    return second_num

value1 = 100
value2 = 50

result = get_maximum(value1, value2)   # storing returned value into variable
print(f"{result} is maximum")
Result
1
100 is maximum

You can also return multiple values (in the form of a tuple):

1
2
3
4
5
6
def give_me_two_tens():
    return 10, 10 # Returns as tuple

first, second = give_me_two_fives()
print(first)
print(second)
Result
1
2
10
10

Tip

It is a good practice to define all our functions first and then begin the main code.

Scope of a Function

Dictionary

The scope of a function means the extent to which the data items made inside the function are accessible in code.

In Python, data created inside the function cannot be used from the outside unless it is being returned from the function.

Variables in a function block are isolated from the rest of the program. When the function ends, they are released from memory and cannot be recovered.

1
2
3
4
5
def get_name():
    name = "Natasha Romanoff"

get_name()      # returns nothing
print(name)     # this will never work
Result
1
2
3
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
NameError: name 'name' is not defined

Altering Data

When mutable data (eg. list) is passed to a function, we can modify the data inside the function. These modifications on mutable objects will stay in effect outside the function scope as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
num_list = [1, 2, 3, 4]
print(f"Original List : {num_list}")

def multiply_by_10(my_list):
    my_list[0] *= 10
    my_list[1] *= 10
    my_list[2] *= 10
    my_list[3] *= 10

multiply_by_10(num_list)
print(f"Modified List : {num_list}")  # The contents of the list have been changed
Result
1
2
Original List : [1, 2, 3, 4]
Modified List : [10, 20, 30, 40]

Example

Now look at this example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def multiply_by_10():
    num_list = [1, 2, 3, 4]
    print(f"Original List : {num_list}")

    num_list[0] *= 10
    num_list[1] *= 10
    num_list[2] *= 10
    num_list[3] *= 10

    print(f"Modified List : {num_list}")

multiply_by_10()
print(f"Print Modified List Again : {num_list}")
Result
1
2
3
4
5
6
Original List : [1, 2, 3, 4]
Modified List : [10, 20, 30, 40]
Traceback (most recent call last):
File "temp.py", line 13, in <module>
    print(f"Print Modified List Again : {num_list}")
NameError: name 'num_list' is not defined

In the above example, we did alter the data of the list by calling the function. But at line no. 13, when accessing variable num_list, the compiler threw an error because num_list was initialized inside the scope of the function and when the task of that function is completed, the variables initialized inside that scope does not have any affect outside.

In the case of immutable data (eg. numbers, strings etc), the function can modify it, but the data will remain unchanged outside the function’s scope.

1
2
3
4
5
6
7
8
9
x = 50

def func(x):
    print(f'Value of x inside function : {x}')
    x *= 2
    print(f'Changed value of x inside function : {x}')

func(x)     # passing value of x defined at line 1
print(f'Value of x outside function : {x}')
Result
1
2
3
Value of x inside function : 50
Changed value of x inside function : 100
Value of x outside function : 50

Argument Values

Default Arguments

For some functions, we may want to make some parameters optional and use default values in case the user does not want to provide values for them.

1
2
3
4
5
def say(message, times=1):
    print(message*times)

print(say("hello"))
print(say("hello", 3))
Result
1
2
hello
hellohellohello

The function named say is used to print a string as many times as specified.

If we don't supply a value, then by default, the string is printed just once, as we have assigned times variable as 1.

In line no 4, we supply only the string and it prints the string once.

In line no 5, we supply a string and an argument 3 stating that we want to print the string message 3 times.

Warning

Parameters which are at the end of the parameter list of a function can be given default argument values.

For example,

def hello(name, children=5) is valid, but def hello(name="maya", children) is not valid.

Keyword Arguments

If you have a function with many parameters and you want to specify only some of them, then you can give values for such parameters by naming them - this is called keyword arguments.

1
2
3
4
5
6
def func(a, b=5, c=10):
    print(f'a is {a} and b is {b} and c is {c}')

print(func(3, 7))
print(func(25, c=24))
print(func(c=50, a=100))
Result
1
2
3
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50 

The function named func argument values has one parameter without a default argument value, followed by two parameters with default

  • At line no 4, func(3, 7), the parameter a gets the value 3 , the parameter b gets the value 7 and c gets the default value 10.
  • At line no 5, func(25, c=24), the parameter a gets the value 25 due to it's position, b get default value and c gets value of 24 due to naming.
  • At line no 6, func(c=50, a=100), we are specifying value for parameter c before a.

Variable Length Arguments

Sometimes we might want to define a function that can take any number of parameters, i.e. n number of arguments, this can be achieved by using the *.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def total(a=5, *numbers, **age):
    print(f'a {a}')

    #iterate through all the items in tuple
    for single_item in numbers:
        print(f'single_item {single_item}')

    #iterate through all the items in dictionary
    for first_part, second_part in age.items():
        print(first_part,second_part)

total(10, 1, 2, 3, Bob=11, Samantha=25, Steve=30)
Result
1
2
3
4
5
6
7
a 10
single_item 1
single_item 2
single_item 3
Bob 11
Samantha 25
Steve 30

When we declare single starred parameter *param, then all the positional arguments from that point till the end are collected as a tuple.

Similarly, when we declare a double-starred parameter such as **param , then all the keyword arguments from that point till the end are collected as a dictionary.

Info

More on tuples and dictionaries in later series.

Built-in Functions

Python has a huge library of built-in functions. Let's look at some simple functions.

Info

Functions that are properties of a particular entity are known as methods. These methods are accessed using . operator.

A method in python is similar to a function, except that it is associated with object and classes. When we talk about classes and objects we generally use methods instead of functions.

More on this in the OOPs module.

One way to find a substring in a string is by using find() method which returns the first index at which a substring occurs. If no instance is found it returns -1.

1
2
3
4
quote = "Your time is limited, so don't waste it living someone else's life."

print(quote.find("waste"))        # first instance of word waste occurs at index 31
print(quote.find("waste", 9, 20)) # word waste not in range of [9-20) 
Result
1
2
31
-1

Let's check out another method replace,

1
2
3
4
5
6
dialogue = "Loki fell for Sylvie."

new_dialogue = dialogue.replace("Sylvie", "himself")

print(dialogue)
print(new_dialogue)
Result
1
2
Loki fell for Sylvie.
Loki fell for himself.

Uppercasing and lowercasing a string.

1
2
3
print("loki".upper())
print("LOKi".lower())
print("loki : god of mischief".title())
Result
1
2
3
LOKI
loki
Loki : God Of Mischief

Lambda Functions

Dictionary

A lambda is an anonymous function that returns some form of data.

These are defined using the lambda keyword. The lambda keyword creates an inline function that contains a single expression.

SYNTAX:

Let's return the cube of the number using a lambda expression,

1
2
3
cube_num = lambda num : num ** 3  # Assign the lambda to a variable

print(cube_num(10))  # Calling the lambda and giving it a parameter
Result
1
1000

The parameters in the lambda function are optional. We can define it using,

1
2
3
greet_me = lambda : "Hello"

print(greet_me())
Result
1
Hello

We can also define lambda function with more than 1 parameter,

1
2
3
concat_strings = lambda a, b, c: a[0] + b[0] + c[0]

print(concat_strings("Be", "Right", "Back"))
Result
1
BRB

Lambdas are simpler and a lambda cannot have a multi-line expression. We can use conditional statement with lambda,

1
2
3
signal = lambda light: "STOP" if light == 'red' else ( "GO" if light=="green" else "warning" )

print(signal('green'))
Result
1
GO

In the next section, we will start with Loops.

Back to top