PROGRAMMING
Session 5
Functions
Pablo Monfort Instituto de Empresa
Function definition and syntax
A function is a block of reusable # defining functions:
code that is used to perform an def function_name(arg1, arg2) :
action. command1
command2
Functions provide better modularity command3
for your script and a high degree of …
code reusing. return variable
# using defined functions:
function_name(4,5)
function_name(1,10)
2
Defining Basic Functions
def my_function(arg1, arg2) : # defines a new function
solution = arg1 * arg2
return solution # function body (code to execute)
my_function(8, 4)
my_function(13, 2) 3
We use functions for…
Abstraction and Ease of
Reuse of existing maintenance
code encapsulation
4
Document your functions using docstrings
• Summarize function’s behaviour
- don’t include implementation details
• Document in the script the different aspects of the function:
- function’s arguments
- return value
- side effects (if any)
- exceptions raised
- restrictions on when it can be called
5
Defining input and output of a function
Arguments return
Function
# Creating a function called "sum_3_items" with 4 arguments (x,y,z,print_args):
def sum_3_items(x, y, z, print_args = False):
if print_args == True:
print(x, y, z)
return x+y+z
# Executing the created function:
sum_3_items(10, 5, 20)
sum_3_items(10, 5, 20, True)
6
Receiving and returning info
7
Programming Challenges
Programming challenge FUN.1
Define a function where 2 numbers are given and it returns the addition
if both are lower than 10 and the product in other case.
Programming challenge FUN.2
Define a function where the coefficients of a cuadratic equation are
given and the solutions are shown.
Tip: use the sqrt function from the module math
Programming challenge FUN.3
Define a function where 1 arguments is given (group) and it is shown a
random student extracted from that class group. Example of groups:
["Anne","Andrew","Sarah"] ["Mary","Paul"] ["John","Peter","Rob"]
Tip: use the command choice from random module to extract a value randomly from a list:
list1 = ["Kiko", "Justin", "Martha"]
random.choice(list1) 8
Packing / Unpacking
A function can be set up to accept any number of named or
unnamed arguments.
Accept extra unnamed arguments by including *args in the
argument list.
The unnamed arguments are accessible within the function body as
a tuple*:
def sum_many_args(*args):
print(type(args))
return (sum(args))
result = sum_many_args(1, 2, 3, 4, 5)
result
* a tuple is a Python data type similar to a vector or list 9
Encapsulation of function variables
• What is declared in a function stays in the
function
10
map() function
map() takes a function and an iterable like a list as arguments
and applies the function to each item in the iterable.
##### Example of using map() without a lambda function:
def square(x):
return x**2
my_map = map(square, [1,2,3,4,5])
my_list = list(my_map)
my_list [1,4,9,16,25]
11
Common errors
12
Common errors
13
Programming Challenges
Programming challenge FUN.4
Write a Python function to check whether a number is in a given range
[a,b].
Programming challenge FUN.5
Write a Python function that takes a number as a parameter and check
the number is prime or not.
Programming challenge FUN.6
Write a Python function that accepts a string and calculate the number
of upper case letters and lower case letters.
Tip: remember the string.islower() and string.isupper() commands
Programming challenge FUN.7
Write a Python program that accepts a hyphen-separated sequence of
words as input and prints the words in a hyphen-separated sequence
after sorting them alphabetically. 14
Programming Challenges: extra exercises
Some extra exercises proposed
by students in previous years…
15
Programming Challenges: extra exercises
Programming challenge FUN.8
Create a function that receives the name of travelling departure city and
destination city from a user and sends back the price of estimated
flight cost during this year.
- Departure city can only be selected from Madrid, Roma and New York.
- Destination city can only be chosen from Beijing and Melbourne.
Comments:
- If you depart from Europe, the basic cost would start from 300 €
- If you depart from America, the basic cost would start from 400 €
- If your destination is in Asia, the cost will add 50 € more on basic cost
- If your destination is in Australia, the cost will add 100 € more on
basic cost
16
Programming Challenges: extra exercises
Programming challenge FUN.9
Write a python function that prints the users’ life expectancy.
It should receive 3 habits:
- If user drinks more than 3 times a week
- If user is a smoker
- If user exercises
The user gets deducted 10 point if they party a lot or smoke and gains
10 point if they exercise.
Each point is worth a year. The initial count for every user in this country
is 90 years.
Hint: Think about the different number of points the user could get.
Take it further: Make sure the users inputs “yes” or “no”
17
Session Wrap-up
18
Glossary
def
return
map
math.sqrt
19