0% found this document useful (0 votes)
19 views22 pages

Python User Defined Functions Guide

The document explains user-defined functions in Python, detailing their purpose, types, and advantages. It covers the syntax for defining and calling functions, as well as the distinction between formal and actual parameters. Additionally, it provides examples of built-in functions and how to use them effectively in programming.

Uploaded by

financialstupid
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views22 pages

Python User Defined Functions Guide

The document explains user-defined functions in Python, detailing their purpose, types, and advantages. It covers the syntax for defining and calling functions, as well as the distinction between formal and actual parameters. Additionally, it provides examples of built-in functions and how to use them effectively in programming.

Uploaded by

financialstupid
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Python:

User Defined
Functions
PART - 1
Functions

• A function is a block of program statements which can be

used repetitively in a program. For example we have different

buttons on remote control each one of which have different

functionality in the same way function is used for different

functionalities and that particular button of remote works

when we press it.

• Functions may or may not return a value.


Function
A program can be divided into small
subprograms called functions as shown
below:
Program

Function 1 Function 2 Function N


Example

Calculator
Program

Addition Subtraction Multiplication Multiplication


Functions are of three types
• Built in functions: Predefined and no
need to import.
• Functions defined in modules:
Functions which are already defined in
the language library eg. All the string
function, date time functions etc.
• User Defined Functions: Functions
which are defined by the user.
Advantages of User Defined Functions
• User-defined functions help to decompose a
large program into small segments which makes
program easy to understand, maintain and
debug.
• If repeated code occurs in a program. Function
can be used to include those codes and execute
when needed by calling that function.
• Programmers working on large project can divide
the workload by making different functions.
Built in Functions
Programming code output Function used
a=int(input("enter intval")) enter int value Input ()– used for text input
b=str(20) 30 Type conversion :- int, str, float
int() used to convert text into
int
print (eval(b+”30”)) 2030 print()- displays on the screen
eval()-adds two string and
returns result as integer
li=[1,2,3,4] 4 max()- gives maximum element
print (max(li), min(li)) 1 in list
min()-gives minimum element
in list
for i in range(0, len(li)): 1234 range()-used in loops
print (li[i]),
x,y=20.25,-30 20.0 round()-rounds up argument to
print(round(x,0)) give no. of places
Built in Functions
Programming code output Function used
a=int(input("enter enter int value Input ()– used for text input
intval")) 30 Type conversion :- int, str,
b=str(20) float
int() used to convert text into
int
print (eval(b+”30”)) 2030 print()- displays on the screen
eval()-adds two string and
returns result as integer
li=[1,2,3,4] 4 max()- gives maximum
print (max(li), min(li)) 1 element in list
min()-gives minimum element
in list
for i in range(0, len(li)): 1 2 3 4 range()-used in loops
print (li[i]),
Built in Functions
Programming code output Function used
x,y=20.25,-30 20.0 round()-rounds up argument
print(round(x,0)) to give no. of places
print (abs(y)) 30 abs()-gives absolute value
print (type(x)) float type()-gives data type of
arguement
print (id(x)) Id()-gives identity of object
Functions defined in modules
Name of What it does Name of What it does
Function Function
ceil(n) It returns the smallest capitalize() Converts the first character
integer greater than or to upper case
equal to n.
It returns the largest count() Returns the number of
floor(n) integer less than or equal times a specified value
to n occurs in a string
find() Searches the string for a
It returns the factorial of specified value and returns
factorial(n)
value n the position of where it was
found
isalnum() Returns True if all
exp(n) It returns exp characters in the string are
alphanumeric
isalpha() Returns True if all
It returns the base-2
1og2(n) characters in the string are
logarithm of n
in the alphabet
Functions defined in modules
Name of What it does Name of What it does
Function Function
isdigit() Returns True if all
It returns the base-10
1og10(n) characters in the string are
logarithm of n
digits
title() Converts the first
It returns n raised to the
pow(n, y) character of each word to
power y
upper case
islower() Returns True if all
sqrt(n) It returns the square root of n characters in the string are
lower case
isnumeric() Returns True if all
It returns the remainder when
fmod(x, y) characters in the string are
n is divided by y
numeric
isspace() Returns True if all
sin(n) It returns the sine of n characters in the string are
whitespaces
Functions defined in modules
Name of Function What it does Name of Function What it does
istitle() Returns True if the
It returns the tangent
tan(n) string follows the
of n
rules of a title
isupper() Returns True if all
It is pi value (3
pi characters in the
14159)
string are upper case
It is lower() Converts a string into
e mathernaticalconstant lower case
e (2 71828
It returns the cosine lstrip() Returns a left trim
cos(n)
of n version of the string
User Defined Functions

We can define our own functions depending


on our needs. We can do this by performing
following two steps:

1. Defining a function

2. Calling a Function
Defining a Function
We can define a function by using def keyword
Syntax :
def <function_name> ( [argument1],[argument2],…):
# function body
For Example:
def greet():
print (“ Hello welcome to Python”)

Note: Make sure the indentation is correct


Explaination of Syntax
• To define your own Python function, you use the ‘def’ keyword
before its name. And its name is to be followed by parentheses,
before a colon(:)
For example def cal():
• Any input parameters or arguments should be placed within these
parentheses. You can also define
For example def cal(a, b): parameters inside these parentheses.
• The code block within every function starts after a colon (:) and is
indented.
For example def cal(a, b):
print (a*b)
• The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with
no arguments is the same as return None.
For example def cal(a, b):
return a*b
Rules for naming python function

• It can begin with either of the following: A-Z,


a-z, and underscore(_).
• The rest of it can contain either of the
following: A-Z, a-z, digits(0-9), and
underscore(_).
• A reserved keyword may not be chosen as an
identifier.
• (It is good practice to name a Python function
according to what it does)
How function Executes
Execution of function output
def my_own_function(): hello before calling
(3) print("Hello from a function") Hello from a function
hello after calling
(1)print("hello before calling ")
(2)my_own_function() #function call
(4)print("hello after calling")

Explaination
When function call occurs, program control transfers to function
block and when last statement of function block is executed,
then control is transferred again to calling block of code
Adding two numbers

def add(): def add(a,b):


a=5 sum=a+b
b=3 print(sum)
sum=a+b
print(sum)
def add(a,b): def add(a,b):
sum=a+b sum=a+b
print(sum) return(sum)

Note: This function is


Note: This function is
returning the computed
printing the computed
value using return
value using print()
statement
statement
Calling a function
We can call a function by using the following S
Syntax:
<function name>(arg1,arg2,…)
def add(a,b): def add(a,b):
sum=a+b sum=a+b
print(sum) return(sum)
x= int(input()) x= int(input())
y= int(input()) y= int(input())
sum(x,y) # function calling S=sum(x,y) # function calling
print(“sum = “ ,S)
Types of arguments
Arguments are also called parameters .
Depending on the arguments whether passed
to a function definition or during the function
call.
These are of two types
[Link] Parameters
[Link] Parameters
Formal Parameters

def add(a,b):
sum=a+b
return(sum)
x= int(input())
Actual Parameters
y= int(input())
S=sum(x,y)
print(“sum = “ ,S)

You might also like