Functions#
So far we have seen many built-in Python functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, let us learn what a function is and why we need them?
Defining a Function#
A function is a reusable block of code or programming statements designed to perform a certain task. To define or declare a function, Python provides the def keyword. The following is the syntax for defining a function. The function block of code is executed only if the function is called or invoked.
Declaring and Calling a Function#
When we make a function, we call it declaring a function. When we start using the it, we call it calling or invoking a function. Function can be declared with or without parameters.
# Declaring a function
def function_name():
codes
codes
# Calling a function
function_name()
Function without Parameters#
Function can be declared without parameters.
def generate_full_name():
first_name = "Aurora"
last_name = "Luna"
space = " "
full_name = first_name + space + last_name
print(full_name)
generate_full_name()
Aurora Luna
def add_two_numbers():
num_one = 2
num_two = 3
total = num_one + num_two
print(total)
add_two_numbers()
5
Function Returning a Value - Part 1#
Function can also return values, if a function does not have a return statement, the value of the function is None. Let us rewrite the above functions using return. From now on, we get a value from a function when we call the function and print it.
def generate_full_name():
first_name = "Aurora"
last_name = "Luna"
space = " "
full_name = first_name + space + last_name
return full_name
print(generate_full_name())
Aurora Luna
def add_two_numbers():
num_one = 2
num_two = 3
total = num_one + num_two
return total
print(add_two_numbers())
5
Function with Parameters#
In a function we can pass different data types(number, string, boolean, list, tuple, dictionary or set) as a parameter
Single Parameter: If our function takes a parameter we should call our function with an argument
# Declaring a function
def function_name(parameter):
codes
codes
# Calling function
print(function_name(argument))
def greetings(name):
message = name + ", welcome to Applied Python Training!"
return message
print(greetings("Aurora"))
Aurora, welcome to Applied Python Training!
def add_ten(num):
ten = 10
return num + ten
print(add_ten(90))
100
def square_number(x):
return x * x
print(square_number(2))
4
def area_of_circle(r):
PI = 3.14
area = PI * r**2
return area
print(area_of_circle(10))
314.0
def sum_of_numbers(n):
total = 0
for i in range(n + 1):
total += i
print(total)
print(sum_of_numbers(10))
print(sum_of_numbers(100))
55
None
5050
None
Two Parameter: A function may or may not have a parameter or parameters. A function may also have two or more parameters. If our function takes parameters we should call it with arguments. Let us check a function with two parameters:
# Declaring a function
def function_name(para1, para2):
codes
codes
# Calling function
print(function_name(arg1, arg2))
def generate_full_name(first_name, last_name):
space = " "
full_name = first_name + space + last_name
return full_name
print("Full Name:", generate_full_name("Aurora", "Luna"))
Full Name: Aurora Luna
def sum_two_numbers(num_one, num_two):
sum = num_one + num_two
return sum
print("Sum of two numbers:", sum_two_numbers(1, 9))
Sum of two numbers: 10
def calculate_age(current_year, birth_year):
age = current_year - birth_year
return age
print("Age:", calculate_age(2024, 2004))
Age: 20
def weight_of_object(mass, gravity):
weight = str(mass * gravity) + " N" # the value has to be changed to a string first
return weight
print("Weight of an object in Newtons:", weight_of_object(100, 9.81))
Weight of an object in Newtons: 981.0 N
Passing Arguments with Key and Value#
If we pass the arguments with key and value, the order of the arguments does not matter.
# Declaring a function
def function_name(para1, para2):
codes
codes
# Calling function
print(function_name(para1 = 'John', para2 = 'Doe')) # the order of arguments does not matter here
def print_fullname(firstname, lastname):
space = " "
return firstname + space + lastname
print(print_fullname(firstname="Aurora", lastname="Luna"))
Aurora Luna
def add_two_numbers(num1, num2):
total = num1 + num2
return total
print(add_two_numbers(num2=3, num1=2))
5
Function Returning a Value - Part 2#
If we do not return a value with a function, then our function is returning None
by default. To return a value with a function we use the keyword return
followed by the variable we are returning. We can return any kind of data types from a function.
Example: Returning a string#
def full_name(firstname, lastname):
space = " "
full_name = firstname + space + lastname
return full_name
full_name(firstname="Aurora", lastname="Luna")
'Aurora Luna'
Example: Returning a number#
def calculate_age(current_year, birth_year):
age = current_year - birth_year
return age
print("Age:", calculate_age(2024, 2004))
Age: 20
Example: Returning a boolean#
def is_even(n):
if n % 2 == 0:
return True # return stops further execution of the function, similar to break
return False
print(is_even(10))
True
Example: Returning a list#
def get_even_numbers(n):
evens = []
for i in range(n + 1):
if i % 2 == 0:
evens.append(i)
return evens
print(get_even_numbers(10))
[0, 2, 4, 6, 8, 10]
Function with Default Parameters#
Sometimes we pass default values to parameters, when we invoke the function. If we do not pass arguments when calling the function, their default values will be used.
# Declaring a function
def function_name(param = value):
codes
codes
# Calling function
function_name()
function_name(arg)
def greetings(name="Arief"):
message = name + ", welcome to Python for Everyone!"
return message
print(greetings())
print(greetings("Aurora"))
Arief, welcome to Python for Everyone!
Aurora, welcome to Python for Everyone!
def generate_full_name(first_name="First", last_name="Last"):
space = " "
full_name = first_name + space + last_name
return full_name
print(generate_full_name())
print(generate_full_name("Arief", "Rahmansyah"))
First Last
Arief Rahmansyah
def calculate_age(birth_year, current_year=2024):
age = current_year - birth_year
return age
print("Age:", calculate_age(2004))
Age: 20
def weight_of_object(mass, gravity=9.81):
weight = str(mass * gravity) + " N" # the value has to be changed to string first
return weight
# 9.81 - average gravity on Earth's surface
print("Weight of an object in Newtons: ", weight_of_object(100))
# gravity on the surface of the Moon
print("Weight of an object in Newtons: ", weight_of_object(100, 1.62))
Weight of an object in Newtons: 981.0 N
Weight of an object in Newtons: 162.0 N
Arbitrary Number of Arguments#
If we do not know the number of arguments we pass to our function, we can create a function which can take arbitrary number of arguments by using **args
or **kwargs
.
Using the Python args
Variable in Function Definitions#
def sum_all_nums(*args):
print(type(args)) # *args is a tuple
total = 0
for n in args:
total += n
return total
print(sum_all_nums(2, 3, 5))
<class 'tuple'>
10
In this example, you’re no longer passing a list to sum_all_nums()
. Instead, you’re passing three different positional arguments. sum_all_nums()
takes all the parameters that are provided in the input and packs them all into a single iterable object named args
.
Note that args is just a name. You’re not required to use the name args. You can choose any name that you prefer. All that matters here is that you use the unpacking operator (*).
Bear in mind that the iterable object you’ll get using the unpacking operator * is not a list but a tuple.
Using the Python kwargs
Variable in Function Definitions#
**kwargs
works just like *args
, but instead of accepting positional arguments it accepts keyword (or named) arguments.
def concatenate(**kwargs):
result = ""
# Iterating over the Python kwargs dictionary
for arg in kwargs.values():
result += arg
return result
print(concatenate(a="Applied", b="Python", c="Training", d="is", e="Great!"))
AppliedPythonTrainingisGreat!
When you execute the script above, concatenate()
will iterate through the Python kwargs dictionary and concatenate all the values it finds.
Like args
, kwargs
is just a name that can be changed to whatever you want. Again, what is important here is the use of the unpacking operator (**).
Default and Arbitrary Number of Parameters in Functions#
def generate_groups(team, *args):
print(team)
for i in args:
print(i)
print(generate_groups("Team-1", "Aurora", "Raline", "Laras", "Racca"))
Team-1
Aurora
Raline
Laras
Racca
None
Ordering Arguments in a Function#
The correct order for your parameters is:
Standard arguments
*args
arguments**kwargs
arguments
For example, this function definition is correct:
def my_function(a, b, *args, **kwargs):
pass
The *args
variable is appropriately listed before **kwargs
. But what if you try to modify the order of the arguments? For example, consider the following function:
def my_function(a, b, **kwargs, *args):
pass
Now, **kwargs
comes before *args
in the function definition. If you try to run this example, you’ll receive an error from the interpreter:
$ python wrong_function_definition.py
File "wrong_function_definition.py", line 2
def my_function(a, b, **kwargs, *args):
^
SyntaxError: invalid syntax
In this case, since *args
comes after **kwargs
, the Python interpreter throws a SyntaxError
.
Function as a Parameter of Another Function#
# You can pass functions around as parameters
def square_number(n):
return n * n
def do_something(f, x):
return f(x)
print(do_something(square_number, 3)) # 27
9
Lambda Function#
Lambda function is a small anonymous function without a name. It can take any number of arguments, but can only have one expression. Lambda function is similar to anonymous functions in JavaScript. We need it when we want to write an anonymous function inside another function.
To create a lambda function we use lambda keyword followed by a parameter(s), followed by an expression. See the syntax and the example below. Lambda function does not use return but it explicitly returns the expression.
x = lambda param1, param2, param3: param1 + param2 + param2
# Named function
def add_two_nums(a, b):
return a + b
print(add_two_nums(2, 3))
# Lets change the above function to a lambda function
add_two_nums = lambda a, b: a + b
print(add_two_nums(2, 3)) # 5
5
5
# Self invoking lambda function
(lambda a, b: a + b)(2, 3)
5
square = lambda x: x**2
print(square(3))
9
cube = lambda x: x**3
print(cube(3))
27
multiple_variable = lambda a, b, c: a**2 - 3 * b + 4 * c
print(multiple_variable(5, 5, 3))
22
Lambda Function Inside Another Function#
def power(x):
return lambda n: x**n
# function power now need 2 arguments to run, in separate rounded brackets
cube = power(2)(3)
print(cube)
two_power_of_five = power(2)(5)
print(two_power_of_five)
8
32
Exercises#
Exercises: Level 1#
Declare a function add_two_numbers. It takes two parameters and it returns a sum.
Area of a circle is calculated as follows: area = π x r x r. Write a function that calculates area_of_circle.
Write a function called add_all_nums which takes arbitrary number of arguments and sums all the arguments. Check if all the list items are number types. If not do give a reasonable feedback.
Temperature in °C can be converted to °F using this formula: °F = (°C x 9/5) + 32. Write a function which converts °C to °F, convert_celsius_to-fahrenheit.
Write a function called check-season, it takes a month parameter and returns the season: Autumn, Winter, Spring or Summer.
Write a function called calculate_slope which return the slope of a linear equation
Quadratic equation is calculated as follows: ax² + bx + c = 0. Write a function which calculates solution set of a quadratic equation, solve_quadratic_eqn.
Declare a function named print_list. It takes a list as a parameter and it prints out each element of the list.
Declare a function named reverse_list. It takes an array as a parameter and it returns the reverse of the array (use loops).
print(reverse_list([1, 2, 3, 4, 5]))
# [5, 4, 3, 2, 1]
print(reverse_list1(["A", "B", "C"]))
# ["C", "B", "A"]
Declare a function named capitalize_list_items. It takes a list as a parameter and it returns a capitalized list of items
Declare a function named add_item. It takes a list and an item parameters. It returns a list with the item added at the end.
food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
print(add_item(food_staff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat'];
numbers = [2, 3, 7, 9];
print(add_item(numbers, 5)) [2, 3, 7, 9, 5]
Declare a function named remove_item. It takes a list and an item parameters. It returns a list with the item removed from it.
food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
print(remove_item(food_staff, 'Mango')) # ['Potato', 'Tomato', 'Milk'];
numbers = [2, 3, 7, 9];
print(remove_item(numbers, 3)) # [2, 7, 9]
Declare a function named sum_of_numbers. It takes a number parameter and it adds all the numbers in that range.
print(sum_of_numbers(5)) # 15
print(sum_all_numbers(10)) # 55
print(sum_all_numbers(100)) # 5050
Declare a function named sum_of_odds. It takes a number parameter and it adds all the odd numbers in that range.
Declare a function named sum_of_even. It takes a number parameter and it adds all the even numbers in that - range.
Exercises: Level 2#
Declare a function named evens_and_odds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
print(evens_and_odds(100)) # The number of odds are 50. # The number of evens are 51.
Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number
Call your function is_empty, it takes a parameter and it checks if it is empty or not
Write different functions which take lists. They should calculate_mean, calculate_median, calculate_mode, calculate_range, calculate_variance, calculate_std (standard deviation). m
Exercises: Level 3#
Write a function called is_prime, which checks if a number is prime.
Write a functions which checks if all items are unique in the list.
Write a function which checks if all the items of the list are of the same data type.