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

Functions

The document discusses various types of functions in Python including: 1) Defining functions, calling functions, passing arguments, default arguments, and variable-length arguments. 2) Anonymous or lambda functions which are single line functions without a name. 3) Fruitful functions which return a value after performing a task while void functions do not return a value. 4) Scope of variables including global and local variables in functions.

Uploaded by

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

Functions

The document discusses various types of functions in Python including: 1) Defining functions, calling functions, passing arguments, default arguments, and variable-length arguments. 2) Anonymous or lambda functions which are single line functions without a name. 3) Fruitful functions which return a value after performing a task while void functions do not return a value. 4) Scope of variables including global and local variables in functions.

Uploaded by

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

FUNCTIONS

Functions: Defining Functions, Calling Functions, Passing Arguments, Keyword Arguments,


Default Arguments, Variable-length arguments, Anonymous Functions, Fruitful Functions
(Function Returning Values), Scope of the Variables in a Function - Global and Local Variables.

Functions:
 In Python, a function is a group of related statements that performs a specific task.
 Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
 Furthermore, it avoids repetition and makes the code reusable.
 Syntax def function_name(parameters):
"""docstring"""
statement(s)
 Keyword def that marks the start of the function header.
 A function name to uniquely identify the function. 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 the function header.
 Optional documentation string (docstring) to describe what the function does.
 One or more valid python statements that make up the function body. Statements must have
the same indentation level.
 An optional return statement to return a value from the function.
 Example function
def greet(name):
""" This function greets to the person
passed in as a parameter ”””
print("Hello, " + name + ". Good morning!")
 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.
greet(‘John') # function call
Hello, John. Good morning! #output
 return statement
Syntax:
return [expression_list]
 This statement can contain an expression that gets evaluated and the value is returned. If
there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
print(greet("May")) #fun call
Hello, May. Good morning! #output
None #output
Example:
def absolute_value(num):
"""This function returns the absolute value of the entered number """
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
#output
2
4

Calling Function:
• A function definition specifies what a function can do, but it does not cause the function to
execute.
• To execute a function, you must call it. This is how we would call the “add(x,y)” function:
add(1,25) #function call
• When a function is called, the interpreter jumps to that function definition and executes the
statements in its body.
• Then, when the end of the body is reached, the interpreter jumps back to the part of the
program that called the function, and the program resumes execution at that point. When this
happens, we say that the function returns
Example:
def add(x,y): #function definition
s=0
for i in range(x,y+1):
s=s+i
print('sum of numbers from',x,' to',y,s)
#function calling
add(1,25). # here 1,25 are called Actual Parameters

Function Arguments:
 An argument is any piece of data that is passed into a function when the function is called.
 This argument is copied to the argument in the function definition.
 The arguments that are in the function call are known as “Actual Arguments or Parameters”.
 The arguments that are in function definition are called “Formal arguments or Parameters”.
 We can pass one or more number of actual arguments in the function call. The formal
argument list and their type must match with actual arguments.
 Until now, functions had a fixed number of arguments. In Python, there are other ways to
define a function that can take variable number of arguments.
 Three different forms of this type are described below

Default Arguments:
• Python allows functions to be called without or with less number of arguments than that are
defined in the function definition.
• If we define a function with three arguments and call that function with two arguments,
then the third argument is considered from the default arguments.
• The default value to an argument is provided using the assignment (=) operator.
• If the same number of arguments are passed then the default arguments are not considered,
the formal arguments are overwritten by the actual arguments.
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")
#output
Hello Kate, Good morning!
Hello Bruce, How do you do?
 Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
 Non-default arguments cannot follow default arguments.
def greet(msg = "Good morning!", name)
Syntax Error: non-default argument follows default argument

Keyword Arguments:
 When we call a function with some values, these values are passed to the formal
arguments in the function definition based on their position (in the order).
 Python also allows functions to be called using the keyword arguments in which the
position (order) of the arguments can be changed.
 The values are not copied according to their position, but based on their names.
 The actual arguments in the function call can be written as follow:
function_name(Arg_name1=value1,Arg_name2=value2)
 An argument that is written according to this syntax is known as “Keyword Argument” .

# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Bruce")
#1 positional, 1 keyword argument
greet("Bruce", msg = "How do you do?")

 As we can see, we can mix positional arguments with keyword arguments during a
function call. But we must keep in mind that keyword arguments must follow positional
arguments.

Variable-length arguments:
• In some situations, it is not known in advance how many number of arguments have to be
passed to the function.
• In such cases, Python allows programmers to make function calls with arbitrary (or any)
number of arguments.
• When we use arbitrary arguments or variable-length arguments, then the function
definition uses an asterisk ( *) before the formal parameter name.

def greet(*names):
for name in names:
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")

#output
Hello Monica
Hello Luke
Hello Steve
Hello John

Anonymous Functions:
 Lambda or anonymous functions are so called because they are not declared as other
functions using the def keyword. Rather, they are declared using the lambda keyword.
 Lambda functions are throw-away functions, because they are just used where they have
been created.
 Lambda functions contain only a single line. Its syntax will be as follows:
lambda arguments : expression
The arguments are separated by comma and the expression is an arithmetic expression that
uses these arguments. The function can be assigned to a variable to give it a name.

double = lambda x: x * 2
print(double(5))

#output
10

Which will be same as


def double(x):
return x * 2

#lambda or anonymous function

n=lambda x,y: x**y


x=int(input("Enter value of x :"))
y=int(input("Enter value of y :"))
#function call in the print() function
print(x,"power",y,"is",n(x,y))

Properties of Lambda Function


 Lambda functions have no name
 Lambda functions can take any number of arguments
 Lambda functions can just return a single value
 Lambda functions cannot access variables other than in their parameter list.
 Lambda functions cannot even access global variables.
 It is possible to call the lambda function from other function.
.
#lambda or anonymous function
def inc(y):
return(lambda x: x+1)(y)
x=int(input("Enter value of x :"))
print("the increment value of ", x , "is", inc(x)) #function call in the print() function

def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
#output 22

def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
#output 33

Fruitful Functions (Function Returning Values):


 The functions that return a value are called “Fruitful Functions”.
 Every function after performing its task it returns the program control to the caller.
 A fruitful function can return any type of value may it be string, integer, boolean, etc.
 It is not necessary for a fruitful function to return the value of one variable, can also
return multiple values.
Example:
#finding the area of a circle
def area(r):
a=3.14*r*r
return(a) #function returning a value to the caller
x=int(input("Enter the radius :"))
#calling the function
r=area(x)
print("The area of the circle is:",r)

Void Function:
 Void functions are those that do not return any value after their evaluation is complete.
 These types of functions are used when the calculations of the functions are not needed
in the actual program.
 These types of functions perform tasks that are crucial to successfully run the program
but do not give a specific value to be used in the program.
Example:
def area(r):
a=3.14*r*r
print("The area of the circle is:",a)
x=int(input("Enter the radius :"))
#calling the function
print(area(x))

Scope of the Variables in a Function:


All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable. The part of the program in which a variable can be
accessed is called its scope. The duration for which a variable exists is called its “Lifetime”.
If a variable is declared and defined inside a function its scope is limited to that function only. It
cannot be accessed to outside that function. If an attempt is made to access it outside that
function an error is raised. The scope of a variable determines the portion of the program where
you can access a particular identifier. There are two basic scopes of variables in Python:

Global Scope -variables defined outside the function


Local Scope - variables defined inside functions have local scope

Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope. This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought into
scope.

Example1:
def myfunc():
x = 300 #local scope
print(x)
myfunc()

#output 300
Example2:

x=5 #global scope


def myfunc():
print(x)
myfunc()
print(x)

# output 5 5

Example3:

x = 300 #global scope


def myfunc():
x = 200 #local scope
print(x)
myfunc()
print(x)

#output 200 300

You might also like