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

Lecture 13 Functions

Uploaded by

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

Lecture 13 Functions

Uploaded by

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

n=int(input("Enter value of n:"))

r=int(input("Enter value of r:"))


nfact=1
for i in range(1,n+1):
nfact*=i

nrfact=1
nr=n-r
for i in range(1,nr+1):
nrfact*=i

P=nfact/nrfact

rfact=1
for i in range(1,r+1):
rfact*=i

C=nfact/(rfact *nrfact)

print(f"The value of nPr is {P} and nCr is {C}")


Functions
Reusability is a key principle of software
engineering.

Once you’ve written some code, you’ll want to store it


so you can use it again without having to
copy and paste.
Functions
This is what functions are for! Functions are a way
to wrap up your code so it can be used
again by calling an easy shortcut.
• Functions
• Function Declaration and Definition
• Function Parts
• Calling Functions
• Function Arguments
– Pass by Value
– Pass by Reference
Function
Some definition:

“ A function is a named, independent section of python

code that performs a specific task and optionally returns a

value to the calling program or/and receives values(s)

from the calling program.”


Function
Some definition:

“ A function is a named, independent section of code

that performs a specific task and optionally returns a

value to the calling program or/and receives values(s)

from the calling program.”


Function
• A function is a group of statements that together perform a task
– Programs can define additional functions.
• We can divide a long code into separate functions
– Ensure that each function performs one task
• A function is known with various names like a method or a sub-routine or
a procedure, etc.
Function
▪ Basically there are two categories of function:
1. Predefined functions: available in Python
standard library.

2. User-defined functions: functions that


programmers create for specialized tasks
such as graphic and multimedia libraries,
implementation extensions or dependent
etc.
Function
• A function definition provides the actual body of the function.
• A function call allows the execution of the function.
Functions
▪ Basically a function has the following characteristics:
1. Named with unique name .
2. Performs a specific task - Task is a discrete job that the program must perform as
part of its overall operation, such as sending a line of text to the printer, sorting
an array into numerical order, or calculating a cube root, etc.
3. Independent - A function can perform its task without interference from or
interfering with other parts of the program.
4. May receive values from the calling program (caller) - Calling program can pass
values to function for processing whether directly or indirectly (by reference).
5. May return a value to the calling program – the called function may pass
something back to the calling program.
Function Declaration and Definition
return_type
def function_name(parameter
: list) :

body of the function


Function Name: Parameters:
• Name of the function • A parameter is like a placeholder.
• Function name and the parameter • When a function is invoked, you pass
list together constitute the function a value to the parameter. This value is
signature. referred to as actual parameter or
argument.
• The parameter list refers to the type,
Function Body: order, and number of the parameters
• The function body contains a of a function.
collection of statements that • Parameters are optional; that is, a
define what the function function may contain no parameters.
does.
Function Definition
• A function header tells the compiler about a function name and how to call the
function. The function body is defined separately.

• A function definition has the following parts:

def function_name( parameter list ):

• Function definition is required when you define a function in one source file and you
call that function in another file. In such case you should define the function at the
top of the file calling the function
Syntax of Functions

def my_function():

Name function.
Code that represents the function
MORE about Functions
Function names have to follow the same rules as variable names.
def my_function():

parentheses and a colon


Indent the body of function
Calling Functions
def hi():
print(“Hello Mr. John! How are you
today?”)

hi()
Function with Parameters
def hi(name):
print(“Hello “ + name + “! How are you today?”)

Now you can say hi to John, James, and Maggie, like so:

hi(“John”)
hi(“James”)
hi(“Maggie”)
Functions With Default Values

def hi(name=”sir”):
print(“Hello “ + name + “! How are you today?”)

hi()
hi(“James”)
Return Values

As you may have guessed, the


return statement allows you to
store the output of the function in
a variable.
Example
• A simple function that adds two numbers can be defined as follows:
Method 1:
def add(a, b):
return a+b

Method2:
def sum(a, b):
c = a+b
print ("Sum of",+a,"and",+b,"is:",+c)
Calling a Function
• While creating a function, you give a definition of what the function has
to do.
• To use a function, you have to call that function to perform the defined task.
• When a program calls a function, program control is transferred to
the called function.
– A called function performs defined task and when its return statement is executed
or when its end of function block (indented statements) is reached, it returns
program control back to the main program.
• To call a function, you simply need to pass the required parameters
along with function name, and if function returns a value, then you can
store returned value.
Function Mechanism
• C program does not execute the statements in a function until the function is
called.
• When it is called, the program can send information to the function in the form
of one or more arguments although it is not a mandatory.
• Argument is a program data needed by the function to perform its task.
• When the function finished processing, program returns to the same location
which called the function.
Function Mechanism
▪ Function can be called as many times as needed in a
program.
✓ Example: We can call add (int, int) function 10, 20, even 100
times if we need it.
▪ Functions can be called in any order provided that they
have been declared (as a prototype) and defined.
▪ Function can be called within any other function, but it can
not be defined inside any function.
Definition

Example
Function Call
Example

def add():
num1, num2 = 5, 15
num3 = num1 + num2
print(f"The addition of {num1} and {num2} results {ans}.")

add()
Function Parameters
• We might have functions that need some arguments to work
on.
– When the function is defined, the arguments are stored in placeholder
variables called formal parameters.

– The formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.
Example of Function Parameters
• Looking at the add function

def add(a, b):


return a+b

• In the above function, a and b are formal parameters.

• The values that are passed to the function when the function
is called are known as function arguments.
Passing Arguments to a Function
▪ In order function to interact with another functions or codes, the
function passes arguments.
▪ The called function receives the values passed to it and stores them
in its parameters.
▪ List them in parentheses following the function name.
▪ The number of arguments and the type of each argument must
match the parameters in the function header and call.
Passing Arguments to a Function
▪ If the function takes multiple arguments, the arguments listed in the function
call are assigned to the function parameters in order.
▪ The first argument to the first parameter, the second argument to the second
parameter and so on as illustrated below.
Definition
(Parameters)
def

Function Call
(Arguments)
FUNCTIONS
Do not pass argument Do pass arguments

No return

With a return
Parameters vs Arguments
• Parameter: a declaration of an identifier within the '()' of a
function declaration.
✓Used within the body of the function as a variable of that function.

✓Initialized to the value of the corresponding argument.

• Argument: an expression passed when a function is called; becomes


the initial value of the corresponding parameter.

Introduction to Functions 32
Using Functions (continued)
This is a parameter
• Let def func( x, a): be a function.

• Then func(expr1, expr2) can be used in any expression e.g.,

N = func(pi*pow(r,2), b+c) + d;
This is an argument

This is also an argument

Introduction to Functions 33
Using Functions (continued)
• Let def func(x, a) be (the beginning of) a declaration of a
function.

• Then func(expr1, expr2) can be used in any expression where


a value of type int can be used – e.g.,
N = func(pi*pow(r,2), b+c) + d;
def factorial(x):
fact=1
for i in range(1,x+1):
fact*=i
return fact

def nPr(n,r):
P = factorial(n)/factorial(n-r)
print(f"The value of nPr for n={n} and r={r} is {P}")

def nCr(n,r):
C = factorial(n)/(factorial(r)* factorial(n-r))
print(f"The value of nCr for n={n} and r={r} is {C}")

n=int(input("Enter value of n:"))


r=int(input("Enter value of r:"))
nPr(n,r)
nCr(n,r)
Flowchart
What is Scope?
• Region of the program where a defined variable can have its
existence and beyond that variable can not be accessed
• There are three places where variables can be declared in
Python:
– Inside a function or a block which is called local variable.
– Outside of all functions which is called global variable. A Global variable
can be defined using the global Keyword.
– In the definition of function parameters which is called formal
parameters.
Local Variables
• Variables that are declared inside a function or block are called local variables
– They can be used only by statements that are inside that function or
block of code
– Local variables are not known outside the function or scope where they are
defined.
– Local variables are created when the function starts its execution and are
lost when the function ends.
– Local variables are created when the function starts its execution and are
lost when the function ends.
Global Variables
• Global variables are defined outside of a function, usually on top of
the program
• The global variables will hold their value throughout the lifetime of
program.
• A global variable can be accessed by any function.
• Global variables are not very reliable because any function in the
program can alter its value.
• A global variable is useful when many functions are using the same
set of data.
Local Variable Vs. Global Variables
Comparison Basis Global Variable Local Variable
Global variables are declared outside Local variables are declared within the
Definition the functions functions
Global variables are created as the Local variables are created when the
Lifetime execution of the program begins and are function starts its execution and are lost
lost when the program is ended when the function ends

Data Sharing Global Variables Offers Data Sharing Local Variables don't offer Data Sharing

Scope Accessible throughout the code Accessible inside the function

Global variables are kept in a fixed


Storage location selected by the compiler
Local variables are kept on the stack

For global variables, parameter passing is For local variables, parameter passing is
Parameter Passing not necessary necessary

Changes in a global variable are reflected Changes in a local variable don't affect
Changes in a variable value throughout the code other functions of the program
Example (Global Variables)
Example (global Variables)
a=10
def func():
global a
a+=10
print("Value inside the function:",a)
func()
print("Value Outside the function:",a)
Formal Parameters
• Function parameters (formal parameters) are treated as local variables
with-in that function.

• If we have a global variable with the same name as function parameter,


then function parameter takes preference over the global variable.
Concatenation again
There are 4 ways to concatenate:
Import Statements

If you want to use functionality


stored in another package you must use
an import Statement.
Modules

A module is a file containing Python


definitions and statements.
Tons of Builtins in Python
Module
Consider a module to be the same as a code
library.

A file containing a set of functions you


want to include in your application.
Help

To know the functionality of any


function, we can use built in
function help.
Random Module
Random Module
MATH MODULE
MATH MODULE
MATH MODULE
MATH MODULE
Id
Id
Copy In List
a = [1,2,3]
b = a
a[0] = 4
print(b)

See:
https://stackoverflow.com/questions/2612802/
list-changes-unexpectedly-after-assignment-
Copy In List
Lambda Function

It creates an inline function and returns it as a


result.

A lambda function is a lightweight anonymous function. It can accept any


number of arguments but can only have a single expression.
Syntax Of Lambda Functions
Map

The map() function lets us call a function on a collection or group of


iterables.
Map
Filter

The filter() function selects an iterable’s (a list, dictionary, etc.) items


based on a test function.
Filter
Reduce

The reduce method continuously applies a function on an iterable (such


as a list) until there are no items left in the list. It produces a non-iterable
result, i.e., returns a single value.
Reduce

You might also like