Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

WK 3 Python Functions

Uploaded by

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

WK 3 Python Functions

Uploaded by

Ken Dexter
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

FUNCTIONS IN PYTHON

Functions are the subprograms that perform specific task. Functions are the small
modules.

3 Types of Python Functions:

1. Library Functions (Built in


functions)
2. Functions defined in modules
3. User Defined Functions
3 Types of Python Functions: Continuation

1. Library Functions: These functions are already built in the python library.
Does not require import statement.
2. Module Functions : Functions defined in modules (Built-in or User Defined).
When you want to use these functions in program, you have to import the
corresponding module of that function.
3. User Defined Functions (UDF): The functions that are defined/written by the
user are called user defined functions.
Types of Python Functions: Continuation
Library Functions in Python:
These functions are already built in the library of python.
Built-in Functions
print() min(), max()
len() abs()
type() round()
int(), float(), str() all(), any()
list(), dict(), set(), tuple() map(), filter(), reduce() (from functools)
range() open()
enumerate() input()
zip() isinstance(), issubclass()
sorted() getattr(), setattr(), hasattr()
reversed() dir()
sum() help()
Functions defined in modules (Standard Library/Built-in) :
a. Functions of random module:
To work with the functions of random module, we must import random module in
program.
Function in random module:
random module has a function randint( ).
 randint( ) function generates the random integer values including start and end
values.
 Syntax: randint(start, end)
 It has two parameters. Both parameters must have integer values
Example:
import random
n=random.randint(3,7)
*The value of n will be 3 to 7.
b. Functions of math module:
To work with the functions of math module, we must import math module in program.
Functions defined in modules (User Defined) :

A Python module is a file containing Python code that defines functions, classes, and
variables. Modules allow you to organize your code logically by grouping related code
into a single file. This helps in maintaining and reusing code efficiently. Python
modules have the .py extension.

Key Points about Python Modules:


1. File-based: A module is simply a Python file with a .py extension.
2. Namespace: Modules provide a separate namespace to avoid naming conflicts.
3. Reuse: They enable code reuse across different programs.
4. Standard Library: Python comes with a rich standard library of modules that
provide numerous functionalities out of the box.
USER DEFINED FUNCTIONS:

Where:
 Keyword def marks the start of function header.
 A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are optional.
 A colon (:) to mark the end of function header.
 One or more valid python statements that make up the function body. Statements must have same
indentation level.
 An optional return statement to return a value from the function.
Example:
def display(name):
print("Hello " + name + " How are you?")
Function Parameters:
A functions has two types of parameters:
1. Formal Parameter: Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local variables which are
assigned values from the arguments when the function is called.
2. Actual Parameter: When a function is called, the values that are passed in the call
are called actual parameters. At the time of the call each actual parameter is assigned
to the corresponding formal parameter in the function definition.
Calling the function:

Once we have defined a function, we can call it from another function, program or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.

Syntax:
function-name(parameter)

Example:
ADD(10,20)

OUTPUT:
Sum = 30.0
The return statement:
The return statement is used to exit a function and go back to the place from where
it was called.
There are two types of functions according to return statement:
a. Function returning some value (non-void function)
b. Function not returning any value (void function)
Function returning some value (non-void function) :
Syntax:
return expression/value

Example-1: Function returning one value


def my_function(x):
return 5 * x
Function not returning any value (void function) : The
function that performs some operationsbut does not return any
value, called void function.

def message():
print("Hello")
m=message()
print(m)

OUTPUT:

Hello
Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized.
Parameters and variables defined inside a function is not visible from outside. Hence,
they have a local scope.
There are two types of scope for variables:
1. Local Scope
2. Global Scope
1. Local Scope:
Variable used inside the function. It can not be accessed outside the function. In this
scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.
2. Global Scope:
Variable can be accessed outside the function. In this scope, Lifetime of a variable
is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)

OUTPUT:
Value inside function: 10
Value outside function: 20
Other Types of Python Functions :
1. Recursive Function --- A function that calls itself, is called recursion. A recursive
function breaks than the problem into smaller problems and call itself for each of the smaller problems .

Iterative solution: factorial function Using recursion: factorial function


Program: Program:
def getFactorial(n): def factorial(n):
factorial = 1 if n == 1:
for x in range(1,n): return n
factorial = factorial * x else:
return factorial
return n*factorial(n-1)
Python program to print the Fibonacci series using recursion:
Program:
def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input("How many terms you want to display: "))


for i in range(num):
print(fibonacci(i)," ", end=" ")
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
Other Types of Python Functions :
Lambda Function
lambda keyword, is used to create anonymous function which doesn’t have any name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using
the lambda keyword.
Syntax:
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is evaluated
and returned. Lambda functions can be used wherever function objects are required.
Example:

value = lambda x: x * 4
print(value(6))

Output:
24
Programs related to Functions in Python topic:
1. Write a python program to sum the sequence given below. Take
the input n from the user. 1+1/1!+1/2!+1/3!+⋯+1/𝑛!
Solution:
SAMPLE CODES/

--- Python Built-in / Standard Library Functions


Refer to default location: c:\PythonProjects\pyfunctions
--- Python Methods(User- Defined)
Refer to default location: samp1x
--- User Defined Functions
Refer to default location: sampfunction
END OF SLIDE

You might also like