(Lab Manual - 2) Functions in Python
(Lab Manual - 2) Functions in Python
Functions in Python
1. Functions
You may have come across functions in other computer languages, where they may have been called subroutines or procedures.
Functions reduce our future work radically and if the operation must be changed later, we only have to update one copy in the function, not many scattered copies throughout the code.
In Python, "def" creates a function object and assigns it to a name. Let’s start with a simple example of our first function!
In [6]:
# A simplest example of a function is:
def function_name(pram1):
"""
Body: Statements to execute
"""
print(pram1) # this will print the pram1 only
So, we have defined/created our first function in the above code cell with its name "function_name". Once, the function is defined, we can call that function with its name in our code.
In this case, our created function "function_name", needs a parameter "pram1". We need to pass a parameter when calling the function "function_name".
Let’s do this!
In [7]:
# function call with its name
function_name('Hello world')
Hello world
Hello world, this is Python
In [8]:
# function call without parameter
function_name()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-db13d823f65a> in <module>()
1 # function call without parameter
----> 2 function_name()
In [9]:
def function_name(pram1 = 'Default Value'):
print(pram1)
# Let's concatenate two string together with + sign.
print(pram1 +', this is Python')
Now if we don’t pass the parameter during the function call, it will print the Default Value.
In [10]:
# Function call without the parameter
function_name()
Default Value
Default Value, this is Python
In [11]:
function_name('Hi') # or function_name(pram1='Hi')
Hi
Hi, this is Python
Good to know!
The terms "parameter and argument" may have different meanings in different programming languages. Sometimes they are used interchangeably, and the context is used to
distinguish the meaning. The term parameter (sometimes called formal parameter) is often used to refer to the variable as found in the function definition, while argument (sometimes
called actual parameter) refers to the actual input supplied at function call. For example, if one defines a function as def f(x): ..., then x is the parameter, and if it is called by a = ...; f(a)
then a is the argument.
Lets create a function that takes two parameters (type number in this case) and returns the multiplication of the numbers.
In [12]:
# function returns the result
def my_func(num1, num2):
num = num1*num2
return num
# we can write "return num1**num2" in a single line as well
In [13]:
# Function call
my_func(2,3)
6
Out[13]:
We can get the results from our function in a variable and then print that variable, let’s try!
In [14]:
out = my_func(2,3)
print(out)
6
Functions can have documentation strings (docstring) enclosed b/w """doc""". I want to say, a function should have a document string, they are very useful. Let’s create a docstring for
our example function.
In [5]:
def my_func(num1, num2):
"""
These docstrings are very useful
Jupyter has a great feature for these strings
write function name, and click shift + tab
my_func -- shift + tab
You will see these doc string
"""
return num1**3
In [7]:
#my_func - then press shift+tab to see the doc string
my_func
Again, DocStrings are very useful, it is always encouraged to write a proper documentation of your custom function.
You can find the documentation of all the built-in functions very useful. If we type range and click < shift+tab > (in jupyter notebook environment), we will see the documentation of range,
we don’t need to memorize this all! We will be using this feature lots of time in this course!
In [23]:
#some built in functions
print(max(3,4,1))
print(min(2,1,5))
print(max('a','A','b','Z', 'z'))
4
1
z
In [29]:
print(round(4.764))
print(round(4.324))
print(round(4.764,1))
print(round(4.764,2))
5
4
4.8
4.76
In [38]:
#
#Let's write an if condition in a function
#
def function_1():
x,y =2,8
x is less than y
Lambda Expression
Now we know the basics about function, we can move on and learn "lambda expression".
Lambda expression is a way to create small anonymous functions, i.e. functions without a name.
These throw-away functions are created where we need them.
Lambda expressions are mainly used in combination with the filter() and map() built-in functions.
The argument_list consists of a comma separated list of arguments and expression is an arithmetic expression using these arguments.
Lets write a function, which return square of a number and then re-write that function to a lambda expression. This is easy!
In [18]:
# Function to compute square
def square(num):
return num**2
In [19]:
# Function call using its name 'square' and a required parameter
square (4)
16
Out[19]:
In [20]:
def square(num):return num**2
square (4)
16
Out[20]:
Now, let’s convert this one line function "def square(num):return num**2" into a lambda expression
The modified code in the cell below will be your lambda expression, let’s try! We will use lambda expressions a lot in our pandas library.
In [21]:
lambda num : num*2
# hold-on, we will use this expression in map and filter to understand in details
<function __main__.<lambda>>
Out[21]:
Exercise
Mass and Weight
Scientists measure an object’s mass in kilograms and its weight in newtons. If you know the amount of mass of an object in kilograms, you can calculate its weight in newtons with the
following formula:
Software Sales
A software company sells a package that retails for $99. Quantity discounts are given according to the following table:
Quantity Discount
10–19 10%
20–49 20%
50–99 30%
Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total amount of the
purchase after the discount.
Shipping Charges
The Fast Freight Shipping Company charges the following rates:
Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
where weight is measured in pounds and height is measured in inches. The program should ask the user to enter his or her weight and height and then display the user’s BMI. The
program should also display a message indicating whether the person has optimal weight, is underweight, or is overweight. A person’s weight is considered to be optimal if his or her
BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered to be underweight. If the BMI value is greater than 25, the person is considered to be overweight.
In [ ]: