0% found this document useful (0 votes)
8 views

Lecture Unit 7

Intro to python

Uploaded by

hashimabdulatwif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture Unit 7

Intro to python

Uploaded by

hashimabdulatwif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIVERSITY OF LUSAKA

SCHOOL OF SOCIAL SCIENCES AND TECHNOLOGY

LECTURE~UNIT 7: Python - Functions 1


NAME: Longwani C Perry (Mr.)
CONTACT: +260 966589151
What are Functions?
Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.

Some Benefits of Using Functions

• Increase Code Readability


• Increase Code Reusability

2
What are Functions?
Python Function Declaration
The syntax to declare a function is:

3
What are Functions?
A top-to-down approach towards building the processing logic involves defining blocks of
independent reusable functions. A Python function may be invoked from any other function
by passing required data (called parameters or arguments). The called function returns its result
back to the calling environment.

4
What are Functions?
Types of Functions in Python
There are mainly two types of functions in Python.

• Built-in library function: These are Standard functions in Python that are available to use.
Python's standard library includes number of built-in functions. Some of Python's built-in
functions are print(), int(), len(), sum(), etc. These functions are always available, as they are
loaded into computer's memory as soon as you start Python interpreter.

The standard library also bundles a number of modules. Each module defines a group of functions.
These functions are not readily available. You need to import them into the memory from their
respective modules.

• User-defined function: We can create our own functions based on our requirements.
In addition to the built-in functions and functions in the built-in modules, you can also
create your own functions. These functions are called user-defined functions.

5
What are Functions?
Defining a Python Function
You can define custom functions to provide the required functionality. Here are simple rules to
define a function in Python.

6
What are Functions?
Example to Define a Python Function
The following example shows how to define a function greetings(). The bracket is empty so
there aren't any parameters.

The first line is the docstring. Function block ends with return statement. when this function is
called, Hello world message will be printed.

7
What are Functions?
Calling a Python Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt.

8
What are Functions?
Example to Call a Python Function
Following is the example to call printme() function −

9
What are Functions?
Pass by Reference vs Value
The function calling mechanism of Python differs from that of C and C++. There are two main
function calling mechanisms: Call by Value and Call by Reference.

When a variable is passed to a function, what does the function do to it? If any changes to
its variable does not get reflected in the actual argument, then it uses call by value mechanism.
On the other hand, if the change is reflected, then it becomes call by reference mechanism.

10
What are Functions?

11
What are Functions?
C/C++ functions are said to be called by value. When a function in C/C++ is called, the value of
actual arguments is copied to the variables representing the formal arguments. If the function
modifies the value of formal argument, it doesn't reflect the variable that was passed to it.

Python uses pass by reference mechanism. As variable in Python is a label or reference to the
object in the memory, the both the variables used as actual argument as well as formal arguments
really refer to the same object in the memory. We can verify this fact by checking the id() of the
passed variable before and after passing.

12
What are Functions?
The behaviour also depends on whether the passed object is mutable or immutable.
Python numeric object is immutable. When a numeric object is passed, and then the function
changes the value of the formal argument, it actually creates a new object in the memory,
leaving the original variable unchanged.

13
What are Functions?
Python Function Arguments
The process of a function often depends on certain data provided to it while calling it. While
defining a function, you must give a list of variables in which the data passed to it is collected.
The variables in the parentheses are called formal arguments.

When the function is called, value to each of the formal arguments must be provided. Those are
called actual arguments.

14
What are Functions?
Example
Let's modify greetings function and have name an argument. A string passed to the function as
actual argument becomes name variable inside the function.

15
What are Functions?
Types of Python Function Arguments
Based on how the arguments are declared while defining a Python function, they are classified
into the following categories −

16
What are Functions?
Python Default Arguments
Python allows to define a function with default value assigned to one or more formal arguments.
Python uses the default value for such an argument if no value is passed to it. If any value is passed,
the default value is overridden with the actual value passed.

17
What are Functions?

18
What are Functions?

19
What are Functions?
Keyword Arguments
Python allows to pass function arguments in the form of keywords which are also called
named arguments. Variables in the function definition are used as keywords. When the function
is called, you can explicitly mention the name and its value.

Order of Keyword Arguments


When using keyword arguments, it is not necessary to follow the order of formal arguments in
function definition.

Using keyword arguments is optional. You can use mixed calling. You can pass values to
some arguments without keywords, and for others with keyword.

20
What are Functions?

21
What are Functions?
Python - Positional Arguments

The list of variables declared in the parentheses at the time of defining a function are the formal
arguments. A function may be defined with any number of formal arguments.

While calling a function −

22
What are Functions?

23
What are Functions?
Here, the add() function has two formal arguments, both are numeric. When integers 10 and 20
passed to it. The variable a takes 10 and b takes 20, in the order of declaration. The add() function
displays the addition.

Python also raises error when the number of arguments don't match. Give only one argument
and check the result.

24
What are Functions?
Python - Arbitrary Arguments
You may want to define a function that is able to accept arbitrary or variable number of arguments.
Moreover, the arbitrary number of arguments might be positional or keyword arguments.

25
What are Functions?
Example
Given below is an example of arbitrary or variable length positional arguments −

26
What are Functions?
It is also possible to have a function with some required arguments before the sequence of variable
number of values.

Example
The following example has avg() function. Assume that a student can take any number of tests.
First test is mandatory. He can take as many tests as he likes to better his score. The function
calculates the average of marks in first test and his maximum score in the rest of tests.

The function has two arguments, first is the required argument and second to hold any number
of values.

27
What are Functions?

28
What are Functions?
If a variable in the argument list has two asterisks prefixed to it, the function can accept arbitrary
number of keyword arguments. The variable becomes a dictionary of keyword:value pairs.

Example
The following code is an example of a function with arbitrary keyword arguments.
The addr() function has an argument **kwargs which is able to accept any number of address
elements like name, city, phno, pin, etc. Inside the function kwargs dictionary of kw:value pairs
is traversed using items() method.

29
What are Functions?
def addr(**kwargs):
for k, v in kwargs.items():
print ("{}:{}".format(k, v))

print ("pass two keyword args")

# function call
# pass two keyword args
addr(Name="John", City="Mumbai")
print ("pass four keyword args")

# function call
# pass four keyword args
addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")

30
What are Functions?
Python Function with Return Value
The return keyword as the last statement in function definition indicates end of function block, and
the program flow goes back to the calling function. Although reduced indent after the last statement
in the block also implies return but using explicit return is a good practice.

Along with the flow control, the function can also return value of an expression to the calling function.
The value of returned expression can be stored in a variable for further processing.

31
What are Functions?
Example
Let us define the add() function. It adds the two values passed to it and returns the addition.
The returned value is stored in a variable called result.

def add(x,y):
z= x + y
return z

a=10
b=20
result = add(a, b)
print ("a = {} b = {} a+b = {}".format(a, b, result))

32
Announcements

• Go through the Lab_Work_Unit_5_1 to practice the functions


• Monday 6 May, we are starting OOP so, come with Laptops in room 6
• Tuesday 7 May, we will continue with OOP in the Lab
• Monday 13 May, First Presenation
• Tuesday 14 May, Second Presenation
• Tuesday 14 will be our meeting before final Exams.

33
Questions????

Subscribe to my YouTube Channel !!!


For more ICT lessons

Perlongs Computing

34

You might also like