KEMBAR78
Python Functions | PDF | Parameter (Computer Programming) | Python (Programming Language)
0% found this document useful (0 votes)
30 views25 pages

Python Functions

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

Python Functions

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

Name of the School: School of computer science and engineering

Course Code: Course Name : PROGRAMMING FOR PROBLEM-SOLVING

Topic:
• Python – Functions
• Types of Python Functions
• Defining a Function
• Calling a Function
• Function Arguments

Faculty Name: R.MUTHU GANESH Programe Name:


Prerequisite/Recapitulations

We assume that the Students have a reasonable exposure to any


programming environment and knowledge of basic concepts such as
variables, commands, syntax, etc.
Objectives

Prepared for the beginners to help them understand the basics to


advanced concepts of Python programming language.

After completing this topic you will find yourself at a expertise


functions concepts and Exception Handling in Python programming,
from where you can take yourself to the next levels.
Introduction

Python Functions:
A function is a block of organized, reusable code that is used to perform a single,
related action.

Functions provide better modularity for your application and a high degree of code
reusing.

A top-to-down approach towards building the processing logic involves defining


blocks of independent reusable functions.

A function may be invoked from any other function by passing required data
(called parameters or arguments).

The called function returns its result back to the calling environment.
Python Functions
Types of Python Functions

Types of Python Functions

• Built-in functions
• Functions defined in built-in modules
• User-defined functions
Types of Python Functions

Python's standard library includes number of built-in functions. Some of Python's


built-in functions are print(), int(), len(), sum(), etc.

These functions are always available, as they are loaded into computer's memory as
soon as you start Python interpreter.

The standard library also bundles a number of modules. Each module defines a
group of functions. These functions are not readily available.

You need to import them into the memory from their respective modules.

In addition to the built-in functions and functions in the built-in modules, you can
also create your own functions. These functions are called user-defined functions.
Python Defining a Function

Python Defining a Function


You can define custom functions to provide the required functionality. Here are simple rules to define a
function in Python.
•Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

•Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.

•The first statement of a function can be an optional statement; the documentation string of the
function or docstring.

•The code block within every function starts with a colon (:) and is indented.

•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.
Python Defining a Function

Syntax :

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in
the same order that they were defined.
Once the function is defined, you can execute it by calling it from another function
or directly from the Python prompt.
Python Defining a Function

Example
The following example shows how to define a function greetings(). The bracket is empty so there
aren't any parameters.
The first line is the docstring. Function block ends with return statement. when this function is
called, Hello world message will be printed.

def greetings():
"This is docstring of greetings function"
print ("Hello Galgotias")
return

greetings()
Calling a Function

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme() function −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
output −
I'm first call to user defined function!
Again second call to the same function
Pass by Reference or Value

Pass by Reference vs Value


The function calling mechanism of Python differs from that of C and C++. There are two main
function calling mechanisms: Call by Value and Call by Reference.

When a variable is passed to a function, what does the function do to it? If any changes to its variable
does not get reflected in the actual argument, then it uses call by value mechanism. On the other hand,
if the change is reflected, then it becomes call by reference mechanism.
C functions are said to be called by value. When a function in C is called, the
value of actual arguments is copied to the variables representing the formal
arguments. If the function modifies the value of formal argument, it doesn't reflect
the variable that was passed to it.
Python uses pass by reference mechanism. As variable in Python is a label or
reference to the object in the memory, the both the variables used as actual argument
as well as formal arguments really refer to the same object in the memory.
We can verify this fact by checking the id() of the passed variable before and after
passing.
def testfunction(arg):
print ("ID inside the function:", id(arg))
var="Hello"
print ("ID before passing:", id(var))
testfunction(var)

If the above code is executed, the id() before passing and inside the function is
same.

ID before passing: 1996838294128


ID inside the function: 1996838294128
The behavior also depends on whether the passed object is mutable or immutable. Python numeric object is
immutable. When a numeric object is passed, and then the function changes the value of the formal argument, it
actually creates a new object in the memory, leaving the original variable unchanged.

def testfunction(arg):
print ("ID inside the function:", id(arg))
arg=arg+1
print ("new object after increment", arg, id(arg))

var=10
print ("ID before passing:", id(var))
testfunction(var)
print ("value after function call", var)
output −
ID before passing: 140719550297160
ID inside the function: 140719550297160
new object after increment 11 140719550297192
value after function call 10
Function Arguments
Function Arguments:
The process of a function often depends on certain data provided to it while calling it. While defining
a function, you must give a list of variables in which the data passed to it is collected. The variables in
the parentheses are called formal arguments.
When the function is called, value to each of the formal arguments must be provided. Those are called
actual arguments.
Function Arguments
Example:
def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return

greetings("Samay")
greetings("Pratima")
greetings("Steven")

output −
Hello Samay
Hello Pratima
Hello Steven
Function with Return Value

The return keyword as the last statement in function definition indicates end of function block, and
the program flow goes back to the calling function. Although reduced indent after the last statement
in the block also implies return but using explicit return is a good practice.
Along with the flow control, the function can also return value of an expression to the calling
function. The value of returned expression can be stored in a variable for further processing.
Example
def add(x,y):
z=x+y
return z

a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))
output −
a = 10 b = 20 a+b = 30
Types of Function Arguments

Based on how the arguments are declared while defining a Python function, there are classified
into the following categories −

•Positional or required arguments


•Keyword arguments
•Default arguments
•Positional-only arguments
•Keyword-only arguments
•Arbitrary or variable-length arguments

Order of Arguments
A function can have arguments of any of the types defined above. However, the
arguments must be declared in the following order −
Order of Arguments

A function can have arguments of any of the types defined above. However, the
arguments must be declared in the following order −
•The argument list begins with the positional-only args, followed by the slash (/)
symbol.
•It is followed by regular positional args that may or may not be called as keyword
arguments.
•Then there may be one or more args with default values.
•Next, arbitrary positional arguments represented by a variable prefixed with single
asterisk, that is treated as tuple. It is the next.
•If the function has any keyword-only arguments, put an asterisk before their names
start. Some of the keyword-only arguments may have a default value.
•Last in the bracket is argument with two asterisks ** to accept arbitrary number of
keyword arguments.
The following shows the order of formal arguments
Python - Default Arguments

You can define a function with default value assigned to one or more formal arguments. Python uses
the default value for such an argument if no value is passed to it.
If any value is passed, the default is overridden.
Example:
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return output −
# Now you can call printinfo function
printinfo( age=50, name="miki" ) Name: miki
printinfo( name="miki" ) Age 50
Name: miki
Age 35
Python - Keyword Arguments

Keyword argument are also called named arguments. Variables in the function definition
are used as keywords. When the function is called, you can explicitly mention the name
and its value.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this
function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


# by positional arguments output −
printinfo ("Naveen", 29) Name: Naveen
Age 29
# by keyword arguments Name: miki
printinfo(name="miki", age = 30) Age 30
Practice Questions

1. Write a Python code to find the Maximum of these two numbers.

Input: a = 2, b = 4
Output: 4

Input: a = -1, b = -4
Output: -1

2. Find the Factorial of a Number Using Recursive approach.


References

The Complete Reference python Martin. C Brown, McGraw Hill

Introduction to computing in problem-solving using python E. Balagurusamy McGraw


Hill.

You might also like