Lab-10 Functions in Python: Objectives
Lab-10 Functions in Python: Objectives
Lab-10
Functions in python
Objectives:
The purpose of this lab is to get you familiar with the functions in Python.
Apparatus:
Hardware Requirement
Personal computer.
Software Requirement
Anaconda, Jupyter Notebook/ Spyder
Theory:
Functions
Functions are useful for breaking up a large program to make it easier to read and
maintain. A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree of
code reusing.
They are also useful if find yourself writing the same code at several different
points in your program. You can put that code in a function and call the function whenever you
want to execute that code. You can also use functions to create your own utilities, math
functions, etc.
Python gives you many built-in functions like print(), etc. but you can also create
your own functions. These functions are called user-defined functions.
The first two lines define the function. In the last three lines we call the function
twice.
One use for functions is if you are using the same code over and over again in
various parts of your program, you can make your program shorter and easier to understand by
putting the code in a function. For instance, suppose for some reason you need to print a box of
stars at several points in your program.
Put the code into a function, and then whenever you need a box, just call the
function rather than typing several lines of redundant code. Here is the function.
One benefit of this is that if you decide to change the size of the box, you just have
to modify the code in the function, whereas if you had copied and pasted the box-drawing code
everywhere you needed it, you would have to change all of them.
Arguments
We can pass values to functions. Here is an example:
When we call the print_hello function with the value 3, that value gets stored in the
variable n. We can then refer to that variable n in our function’s code.
You can pass more than one value to a function:
Returning values
We can write functions that perform calculations and return a result.
Example 1
Here is a simple function that converts temperatures from Celsius to Fahrenheit.
The return statement is used to send the result of a function’s calculations back to
the caller. Notice that the function itself does not do any printing. The printing is done outside of
the function.
That way, we can do math with the result, like below.
If we had just printed the result in the function instead of returning it, the result
would have been printed to the screen and forgotten about, and we would never be able to do
anything with it.
Example 2
A function can return multiple values as a list.
Say we want to write a function that solves the system of equations ax + b y = e
and c x + d y = f. It turns out that if there is a unique solution, then it is given by x = (de-bf)/(ad -
bc) and y = (a f - ce)/(ad- bc). We need our function to return both the x and y solutions.
Example 3
A return statement by itself can be used to end a function early.
The same effect can be achieved with an if/else statement, but in some cases, using
return can make your code simpler and more readable.
Default arguments need to come at the end of the function definition, after all of
the non-default arguments.
Keyword arguments
A related concept to default arguments is keyword arguments. Say we have the
following function definition:
def fancy_print(text, color, background, style, justify):
Every time you call this function, you have to remember the correct order of the
arguments. Fortunately, Python allows you to name the arguments when calling the function, as
shown below:
fancy_print(text='Hi', color='yellow', background='black', style='bold',
justify='left')
fancy_print(text='Hi', style='bold', justify='left', background='black',
color='yellow')
As we can see, the order of the arguments does not matter when you use keyword
arguments. When defining the function, it would be a good idea to give defaults. For instance,
most of the time, the caller would want left justification, a white background, etc. Using these
values as defaults means the caller does not have to specify every single argument every time
they call the function.
Local variables
Let’s say we have two functions like the ones below that each use a variable i:
A problem that could arise here is that when we call func1, we might mess up the
value of I in func2. In a large program it would be a nightmare trying to make sure that we don’t
repeat variable names in different functions, and, fortunately, we don’t have to worry about this.
When a variable is defined inside a function, it is local to that function, which means it
essentially does not exist outside that function. This way each function can define its own
variables and not have to worry about if those variable names are used in other functions.
Global variables
On the other hand, sometimes you actually do want the same variable to be
available to multiple functions. Such a variable is called a global variable. You have to be careful
using global variables, especially in larger programs, but a few global variables used judiciously
are fine in smaller programs. Here is a short example:
Syntax
The syntax of lambda functions contains only a single statement, which is as
follows:
lambda [arg1 [,arg2,.....argn]]:expression
Following is an example to show how lambda form of function works −
Exercises
1. Write a function called rectangle that takes two integers m and n as arguments and prints
out an mxn box consisting of asterisks. Shown below is the output of rectangle(2,4)
****
****
2. Write a function called add_excitement that takes a list of strings and adds an
exclamation point (!) to the end of each string in the list. The program should modify the
original list and not return anything.
3. Write the same function except that it should not modify the original list and should
instead return a new list.
4. Write a function called sum_digits that is given an integer num and returns the sum of the
digits of num.
5. The digital root of a number n is obtained as follows: Add up the digits n to get a new
number. Add up the digits of that to get another new number. Keep doing this until you
get a number that has only one digit. That number is the digital root.
For example, if n = 45893, we add up the digits to get 4 + 5 + 8 + 9 + 3 = 29. We then
add up the digits of 29 to get 2 + 9 = 11. We then add up the digits of 11 to get 1 + 1 = 2.
Since 2 has only one digit, 2 is our digital root.
Write a function that returns the digital root of an integer n. [Note: there is a shortcut,
where the digital root is equal to n mod 9, but do not use that here.]