0% found this document useful (0 votes)
1 views17 pages

3.python Functions

The document provides an overview of functions in Python, highlighting their benefits such as reusability and modularity. It explains built-in and user-defined functions, including syntax and examples for defining and calling functions, as well as concepts like global/local variables and default arguments. Additionally, it covers mathematical functions, recursion, and the use of the math module.

Uploaded by

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

3.python Functions

The document provides an overview of functions in Python, highlighting their benefits such as reusability and modularity. It explains built-in and user-defined functions, including syntax and examples for defining and calling functions, as well as concepts like global/local variables and default arguments. Additionally, it covers mathematical functions, recursion, and the use of the math module.

Uploaded by

krishnasneha98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Programming in Python

Functions
Functions in Python
• A function is a block of code(that performs a specific task) which
runs only when it is called.
Benefits :
• Reusability: Code written within a function can be called as and
when needed. Hence, the same code can be reused thereby
reducing the overall number of lines of code.
• Modular Approach: Writing a function implicitly follows a modular
approach. We can break down the entire problem that we are
trying to solve into smaller chunks, and each chunk, in turn, is
implemented via a function.
• Built-in functions: such as print to print on the standard output
device, type to check data type of an object, etc. These are the
functions that Python provides to accomplish common tasks.
• User-Defined functions: As the name suggests these are custom
functions to help/resolve/achieve a particular task.

Dr.B.Hemantha Kumar-RVRJC 2
Functions in Python
• Built-in functions:
• In addition to print function, We have learned the following built-in
functions until now in the previous sections.
• type(object) is used to check the data type of an object.
• float([value]) returns a floating point number constructed from a
number or string value.
• int([value]) returns an integer object constructed from a float or
string value, or return 0 if no arguments are given.
• round(number[, ndigits]) is used to round a float number up to
digits specified by ndigits.
• abs(value) returns the absolute value of a value provided as an
argument.
• input() to read data from the keyboard, return string value
• bool([value]) return a Boolean value, i.e. one of True or False.

Dr.B.Hemantha Kumar-RVRJC 3
Functions in Python
• User defined functions: Functions are defined using the def
keyword, followed by an identifier name along with the
parentheses, and by the final colon (:) that ends the line.
• Syntax:
def function_name(list of args):
statement 1
statement 2
statement --n

To use the function call the function with its name followed by
list of parameters

Dr.B.Hemantha Kumar-RVRJC 4
Functions in Python
• examples #to find factorial of a number
def display(): def factorial(n):
print(“RVRJC”) fact=1
print(“Guntur”) for i in range(1,n+1):
print(“Calling function”) fact=fact*i
display() print(‘facorial of ‘,n, ‘is :’ ,fact )
print(‘enter number to find factorial’)
Calling function
a=int(input())
RVRJC factorial(a)
Guntur enter number to find factorial
o/p 5
facorial of 5 is :120
o/p

Dr.B.Hemantha Kumar-RVRJC 5
Functions in Python
• examples a=10
Global and local variables b=20
def add(a,b):
a=5
b=10
print("local variable: ",a+b)
add(a,b)
print("global variable: ",a+b)
local variable: 15
globall variable: 30
o/p

Dr.B.Hemantha Kumar-RVRJC 6
Functions in Python
• Function return value
#to find factorial of a number # Arithmetic operations
def factorial(n): def add(a,b):
fact=1 return (a+b)
for i in range(1,n+1): def mult(a,b):
return a*b
fact=fact*i print(‘enter two numbers’)
return fact a=int(input())
print(‘enter number to find factorial’) b=int(input())
a=int(input()) print(“Sum is :", add(a,b))
print("factorial of ",a,"is :" ,factorial(a)) print(“product is :", mult(a,b))
enter number to find factorial
enter two numbers
5
5
facorial of 5 is :120
6
Sum is :11 o/p
o/p
Dr.B.Hemantha Kumar-RVRJC
product is :30 7
Functions in Python
• In python a Function can return multiple values
# return multiple values
def arith(a,b):
s=a+b
p=a*b
d=a/b enter two numbers
return s,p,d 15
print('enter two numbers') 3
Sum is :18
a=int(input()) product is :45
b=int(input()) division is : 5.0
sum,prod,div=arith(a,b)
o/p
print("Sum is :", sum)
print("product is :", prod)
print("division is :", div)
Dr.B.Hemantha Kumar-RVRJC 8
Functions in Python
• Functions with default arguments : we would like to have
some parameters with default values that will be used when
they are not specified in the function call.
• To define a function with a default argument value, we need
to assign a value to the parameter of interest while defining a
function.

# default values
def power(n, pow=2):
return n**pow
print(power(5)) # n=5, pow=2
print(power(2,3)) # n=2, pow=3
25
8
o/p Dr.B.Hemantha Kumar-RVRJC 9
Functions in Python
• Functions with default arguments : assign default values for
formal parameters from left to right
• We can have any number of default value parameters in a
function. Note however that they must follow non-default
value parameters in the definition. Otherwise, Python will
throw an error as shown below:
SyntaxError: non-default argument follows default argument

# default values def abc(a, b=3,c=4): (valid)


def power(pow=2, number): def abc(a, b, c=4): (valid)
return number**pow def abc(a=5, b=3,c=4): (valid)
print(power(5)) def abc(a=5, b,c): (in valid)
print(power(2,3)) def abc(a=5, b,c=4): (in valid)

SyntaxError: non-default argument follows default argument


o/p Dr.B.Hemantha Kumar-RVRJC 10
Functions in Python
• Functions with default arguments : Keyword Parameters
• A keyword argument is specified by explicitly assigning an
actual parameter to a formal parameter by name.
# default values Keyword Parameters
def add(a=10, b=20, c=30): x=add(c=5) # a=10,b=20,c=5
return(a+b+c) x value is 35

Calling:
x=add() # a=10,b=20,c=30
x value is 60
x=add(5) # a=5,b=20,c=30
x value is 55

Dr.B.Hemantha Kumar-RVRJC 11
Functions in Python
If you type a function definition in interactive mode, the interpreter prints
dots (...) to let you know that the definition isn’t complete:
>>> def print_message():
... print(“Hai ! Welcome ")
... print(" This is python group.")
...
To end the function, you have to enter an empty line.
Defining a function creates a function object, which has type function:
>>> print(print_message)
<function print_message at 0xb7e99e9c>
>>> type(print_message)
<class 'function'>
calling the new function in interactive mode :
>>> print_message()
Hai ! Welcome
This is python group.

Dr.B.Hemantha Kumar-RVRJC 12
Functions in Python
• Variables and Parameters Are Local: When you create a
variable inside a function, it is local, which means that it only
exists inside the function
• For eample: def add(n1,n2):
sum= n1+n2
def display(value): display(sum)
print(value)
variable sum is local to add
Parameters value is Parameters n1,n2 are local to add
local to display
a=10
b=20
add(a,b)

Dr.B.Hemantha Kumar-RVRJC 13
Math Functions
• Python has a math module that provides most of the familiar
mathematical functions.
• A module is a file that contains a collection of related
functions.
• Before we can use the functions in a module, we have to
import it with an import statement:
>>> math.pi >>> print(math)
Traceback (most recent call last): <module 'math' (built-in)>
File "<stdin>", line 1, in <module> >>> math
NameError: name 'math' is not <module 'math' (built-in)>
defined >>> type(math)
>>> import math <class 'module'>
>>> math.pi >>>
3.141592653589793
>>> Dr.B.Hemantha Kumar-RVRJC 14
Math Functions
• math functions.
math.sqrt( x ):Return the square root of x
math.ceil(x): Return the ceiling of x, the smallest integer greater
than or equal to x.
math.floor(x): Return the floor of x, the greatest integer smaller
than or equal to x.
math.factorial(x) :Return x factorial as an integer. Raises ValueError
if x is not integer or is negative
math.exp(x): Return e raised to the power x, where e = 2.718281… is
the base of natural logarithms
math.log10(x):Return the base-10 logarithm of x.
math.pow(x, y): Return x raised to the power y
math.sin(x)Return the sine of x radians.
math.cos (x)Return the cos of x radians.
math.tan(x),math.cosh(x),math.sinh(x),math.tanh(x)
Dr.B.Hemantha Kumar-RVRJC 15
Recursive functions
• It is legal for one function to call another; it is also legal for a
function to call itself.
• Recursive: A function that calls itself is recursive; the process
of executing it is called recursion.

#a function that prints a string n


def countdown(n): times:
if n <= 0: def print_n(s, n):
print(n) if n <= 0:
else: return
print(n) print(s)
countdown(n-1) print_n(s, n-1)

Dr.B.Hemantha Kumar-RVRJC 16
Recursive functions
• Examples
#to find factorial of a number(recursive) #to find sum of n numbers(recursive)
def factorial(n): def sumn(n):
if n==0 or n==1: if n==1:
return 1 return 1
else: else:
return n*factorial (n-1) return n+sumn(n-1)
print("enter number to find fact") print("enter number to find sum")
a=int(input()) a=int(input())
fact=factorial (a) s=sumn(a)
print(“factorial of ",a,"is :" ,fact) print("sum of ",a,"numbers is :" ,s)
factn.py sumno.py

Dr.B.Hemantha Kumar-RVRJC 17

You might also like