Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python UNIT III-Part-1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

Python Programming

Python Programming

Unit – 3

Dr. S. P. Ponnusamy
Assistant Professor and Head

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science 1
Python Programming

Syllabus
• UNIT III
Functions – Built in functions – function definition and calling –
return statement – void function – scope and lifetime of
variables – args and kwargs – command line arguments - Tuples
– creation – basic tuple operations – tuple() function – indexing
– slicing – built-in functions used on tuples – tuple methods –
packing – unpacking – traversing of tuples – populating tuples –
zip() function - Sets – Traversing of sets – set methods –
frozenset.
–.
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science 3
Python Programming

Functions - Introduction
 A function is a named part of a program with a smaller size that is used
to perform a specific task.
 The functions may be used by other parts of the program to perform
complicated tasks.
 Any repeated component in a program can be replaced by a function,
which avoids more lines of code.
 The function gets into execution only when it is called from any place in
the program. It can be called any number of times in the program

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions - Introduction
Main Module
:
Fun1()
:
Code of Fun1()
Fun1()
:
Fun1()
:
Fun1()
:

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions - Introduction

Main Module 2

:
Fun1()
1 :
:
Fun1() #function call
3
:
:
:
:
4 :
:
:
:

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Built-in Function


 Python has a set of functions which are predefined to do specific tasks.
 These predefined functions are called as built-in functions.
 The built-in functions are ready to use in the program.

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Built-in Function


Function Description Example
Returns the absolute value of a >>> abs(-22.3)
abs()
number 22.3
Returns a readable version of an object. >>> ascii("¥")
ascii() Replaces none-ascii characters with
escape character "'\\xa5'"
Returns the boolean value of the >>> bool(32)
bool()
specified object True
>>> eval("2*3+5")
eval() Evaluates and executes an expression
11
>>>> pr= 'a = 5\nb=10\nprint(a+b)'
exec() Executes the specified code (or object) >>> exec(pr)
15

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Built-in Function


Function Description Example
>>> min(20,-
Returns the smallest item in 4,23,119,232,78)
min()
an iterable
-4
Returns the value of x to the >>> pow(4,3)
pow()
power of y 64
>>> round(8.6543)
round() Rounds a numbers
9
Sums the items of an >>> sum([1,2,3,4],10)
sum()
iterator 20

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions –Function Definition “

Function Header def function_name (arguments):


--------------
--------------
Function body (suite) --------------
--------------
return(value)

Program 5.1

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions - Arguments
 To achieve the task that is defined inside the function, some information is
needed from the calling place.
 These pieces of information can be passed into functions by a caller as
arguments.
 The arguments are specified after the function name, inside the parentheses.
 The arguments are used as input to the function to accomplish the task.
 The arguments are classified into two categories depending on the position
of the arguments : actual and formal arguments.

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions - Arguments
 The arguments which are used in the function call are referred to as
actual arguments
 The arguments which are used in the function definition are referred to
as formal arguments
Formal arguments
def func1 (a,b,c) :
--------------
--------------
--------------
func1(x,y,z)
Actual arguments

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Required Positional Arguments


 The required positional arguments are simple type of argument passing.
 These arguments are passed to a function in correct positional order not
by names and types.
 The number of arguments in the function call should match exactly with
the function definition.

Program 5.2 and 5.3

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Return
 A function may contain zero or more return statements.
 The return statement is optional and can be used only when it is necessary to
return value(s) to the caller (the programme actually calls the function).
 The return statements can be situated anywhere in the function body after
the function header.
 A return statement ends the execution of the function call and "returns" the
result, which is specified within the parenthesis to the caller.
 The return() takes zero or more values.
 Any statement after the return statement is not executed by the compiler.

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Return
 If the return statement is without a value, the special value "None" is
returned.
 If there is no return statement in the function code, the function ends,
when the control flow reaches the end of the function body and the
value None will be returned. This kind of function is called as void
functions.

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – No Return values


 These kinds of functions are used to display the values to the user and
do not return values.
 The caller does not depend on the calculation part of the function in its
successive calculations.
 Program 5.1 and 5.4

Functions – Single Return value


 The value may be any data type, like an integer, a float, a list, or a
dictionary.
 Program 5.5
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

Functions – Multiple Return values


 If we want to return multiple values, like two integer or float values, it
can be done using the return() statement by separating the values with
commas.
 The return values are received as an object or as a tuple in the calling
place.

 Program 5.6

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope and Life of Variables

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science 18
Python Programming

Scope of Variable
 A program can contain multiple identifiers to refer to different types of
objects.
 A single object can be referred to by many identifiers.
 A single identifier name can be used to refer to different objects.
 To maintain the mapping between objects and identifiers, Python uses
namespaces.
 The location and lifetime of the identifier/variable is determined by
variable scope.

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Types and search Hierarchy


 Variable scope is a determination of the lifetime of the variable.
 The scope determines the accessibility and visibility of a variable, i.e., in
which part or area the variable can be accessed.
1. Local scope
2. Enclosing scope
3. Global scope
4. Built-in scope

UnboundLocalError: local variable 'a' referenced before assignment

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Local


 A variable defined inside a function belongs to the local scope of that
function (from the definition to the end), and can only be used inside
that function.

 Program 5.7
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Local

 Program 5.8
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Enclosed


 For the enclosed scope, we need to define an outer function enclosing
the inner function.
 In the enclosed scope, a variable defined and used in the outer function
cannot be used directly in the inner function in the same name.
 If you define the same variable in an inner function which also exists in
the outer function after the use of the variable, the Python will generate
an error message.

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Enclosed

 Program 5.9
UnboundLocalError: local variable 'a' referenced before assignment

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Enclosed – Non Local


 If you want to override the enclosed scope of an inner function, Python
uses the keyword nonlocal.
 The keyword nonlocal is used to declare a variable, which is already a
bound variable in the closest enclosing scope, in the current function
scope as a nonlocal variable.

 Program 5.10, 5.11

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Global


 A variable defined or created in the main body of the Python program is
called a global variable and belongs to the global scope.
 The global variables are available for the entire program.

 Program 5.12

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Global with ‘global’ keyword


 The global variable can be accessed and used in any expression anywhere in the
program but the modification is restricted inside the function at local scopes.
 Program 5.13

 Python allows the modification of the global variable in a function by using the
global keyword.
 It informs the interpreter that the variable defined with the global keyword is
referred to as a global variable in the main body of the program.
 The content of the global variable is allowed for modification in the function. It is
not a local variable.
 Program 5.14

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

Scope of Variable - Built-in


 The built-in scope is the widest scope in Python.
 All the reserved names defined in the Python built-in modules have a built-
in scope.
 When Python doesn’t find an identifier in its local, enclosing, or global
scope, it then looks in the built-in scope to see if it’s defined there.
 Even though the identifier does not exist in the built-in scope, the python
generates the error message.
 The built-in functions are also referred to as identifiers, and the use of
them is searched in the LEGB order.
 Program 5.15
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

args and kwargs

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science 29
Python Programming

args parameters
 Python allows us to handle the variable-length, non-keyworded
arguments.
 In the function definition, we use an asterisk (*) before the argument name
to indicate variable length arguments in the order.
 The variable length argument holds all the non-keyword variable
arguments as a tuple.
 This tuple remains empty if no additional arguments are specified during
the function call.

 Program 5.16
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

args parameters

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science
Python Programming

kwargs parameters
 Python allows us to handle variable-length, keyworded arguments.
 In the function definition, we use a double asterisk (**) before the
argument name to indicate keyworded variable length arguments in the
order.
 The variable length argument holds all the keyworded arguments as a
dictionary.
 This dictionary remains empty if no arguments are specified for the kwargs
during the function call.

 Program 5.17
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

Command Line Arguments


 Command Line Arguments are the arguments that are supplied after the
name of the program in the operating system's command line shell.
 The command line arguments are received as a list.
 To achieve the command line arguments, we need to import the sys
module.
 The command line arguments are received through the sys.argv list
structure.
 It is a simple variable. The first element in the argv structure (argv[0]) is the
program name which is provided in the command line.
 Program 5.18
Government Arts and Science College
Tittagudi – 606 106
Department of Computer Science
Python Programming

End

Government Arts and Science College


Tittagudi – 606 106
Department of Computer Science 34

You might also like