SlideShare a Scribd company logo
Python - Functions
• A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provides better
modularity for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These
functions are called user-defined functions.
Defining a Function
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.
• Syntax:
• def functionname( parameters ):
• "function_docstring" function_suite return [expression]
• 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.
• Example:
def printme( str ):
"This prints a passed string function"
print str
return
Calling a Function
• Following is the example to call printme() function:
def printme( str ): "This is a print function“
print str;
return;
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
• This would produce following result:
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within
a function, the change also reflects back in the calling function. For
example:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference
but inside the function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes
nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments:
A function by using the following types of formal arguments::
– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Required arguments:
• Required arguments are the arguments passed to a function in correct
positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
• This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments:
• Keyword arguments are related to the function calls. When
you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
• This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords
provided to match the values with parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
Following example gives more clear picture. Note, here order of
the parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
• This would produce following result:
Name: miki Age 50
Default arguments:
• A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument.
• Following example gives idea on default arguments, it would
print default age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
• You may need to process a function for more arguments than
you specified while defining the function. These arguments
are called variable-length arguments and are not named in
the function definition, unlike required and default
arguments.
• The general syntax for a function with non-keyword variable
arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
• An asterisk (*) is placed before the variable name that will
hold the values of all nonkeyword variable arguments. This
tuple remains empty if no additional arguments are specified
during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
10
Output is:
70
60
50
The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions.
These functions are called anonymous because they are not
declared in the standard manner by using the def keyword.
• Lambda forms can take any number of arguments but return just
one value in the form of an expression. They cannot contain
commands or multiple expressions.
• An anonymous function cannot be a direct call to print because
lambda requires an expression.
• Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.
• Although it appears that lambda's are a one-line version of a
function, they are not equivalent to inline statements in C or C++,
whose purpose is by passing function stack allocation during
invocation for performance reasons.
• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
• Following is the example to show how lembda form of
function works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
Scope of Variables:
• 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 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 variables
Local variables
• Global vs. Local variables:
• 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.
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Type Conversions
• When you put an
integer and
floating point in
an expression the
integer is
implicitly
converted to a
float
• You can control
this with the built
in functions int()
and float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
>>>
String
Conversions
• You can also
use int() and
float() to
convert between
strings and
integers
• You will get an
error if the
string does not
contain numeric
characters
>>> sval = '123'
>>> type(sval)
<type 'str'>
>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
>>> ival = int(sval)
>>> type(ival)
<type 'int'>
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Building our Own Functions
• We create a new function using the def
keyword followed by optional parameters
in parenthesis.
• We indent the body of the function
• This defines the function but does not
execute the body of the function
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print 'Yo'
x = x + 2
print x
Hello
Yo
7
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all
day.'
print_lyrics():
Definitions and Uses
• Once we have defined a function, we can
call (or invoke) it as many times as we like
• This is the store and reuse pattern
x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print 'Yo'
print_lyrics()
x = x + 2
print x
Hello
Yo
I'm a lumberjack, and I'm okay.I
sleep all night and I work all day.
7
1. Write a Python function to find the Max of three
numbers.
2.Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
3.Write a Python function to reverse a string.
4.Write a Python function that takes a list and returns a
new list with unique elements of the first list.
1)def maximum(a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
return largest
# Driven code
a = 10
b = 14
c = 12
print(maximum(a, b, c))
2)def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))
3)def reverse(string):
string = string[::-1] #Using
Slicing
return string
s = "IloveIndia"
print ("The original string is :
",end="")
print (s)
print ("The reversed string(using
extended slice syntax) is : ",end="")
print (reverse(s))
4)def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1,2,3,3,3,3,4,5]))
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
• To display a list of all available modules, use the following command in
the Python console
>>> help(‘modules’)
OS MODULE
• mkdir( ) - A new directory corresponding to the path in the string argument of
the function will be created.
• getcwd( ) - current working directory
• rmdir( ) - removes the specified directory either with an absolute or relative
path. However, we can not remove the current working directory. Also, for a
directory to be removed, it should be empty.
• listdir( ) - returns the list of all files and directories in the specified directory.
If we don't specify any directory, then list of files and directories in the
current working directory will be returned.
SYS MODULE
• sys.argv - returns a list of command line arguments passed to a Python script.
The item at index 0 in this list is always the name of the script. The rest of the
arguments are stored at the subsequent indices.
• sys.maxsize - Returns the largest integer a variable can take.
• sys.path - This is an environment variable that is a search path for all Python
modules.
• sys.version - This attribute displays a string containing the version number of the
current Python interpreter.
PYTHON MODULES
Python has a way to put definitions in a file and use them in
a script or in an interactive instance of the interpreter. Such a
file is called a module; definitions from a module can
be imported into other modules or into the main module (the
collection of variables that you have access to in a script
executed at the top level and in calculator mode).
A module is a file containing Python
definitions and statements.
The file name is the module name
with the suffix .py appended.
Within a module, the module’s name
(as a string) is available as
the value of the global variable __name__.
For instance, use your favorite text editor to
create a file called fibo.py in the
current directory with the following contents:
functions modules and exceptions handlings.ppt
Modules can import other modules.
It is customary but not required to
place all import statements at the
beginning of a module (or script, for that matter).
The imported module names are placed in the
importing module’s global symbol table.
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
# Python program to
# demonstrate date class
# import the date class
from datetime import date
# initializing constructor
# and passing arguments in the
# format year, month, date
my_date = date(1996, 12, 11)
print("Date passed as argument is", my_date)
# Uncommenting my_date = date(1996, 12, 39)
# will raise an ValueError as it is
# outside range
# uncommenting my_date = date('1996', 12, 11)
# will raise a TypeError as a string is
# passed instead of integer
Current date
To return the current local date today() function of date class is used.
today() function comes with several attributes (year, month and day). These
can be printed individually.
# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
# Printing date's components
print("Date components", today.year, today.month, today.day)
functions modules and exceptions handlings.ppt
Time class
Time object represents local time, independent of any
day.
Constructor Syntax:
class datetime.time(hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, *, fold=0)
All the arguments are optional. tzinfo can be None otherwise all the attributes
must be integer in the following range –
•0 <= hour < 24
•0 <= minute < 60
•0 <= second < 60
•0 <= microsecond < 1000000
•fold in [0, 1]
# Python program to
# demonstrate time class
from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute = 12)
print("nTime with one argument", my_time)
# Calling constructor with
# 0 argument
my_time = time()
print("nTime without argument", my_time)
# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range
# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int
from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
Output:
hour = 11
minute = 34
second = 56
microsecond = 0
functions modules and exceptions handlings.ppt
# Python program to
# demonstrate datetime object
from datetime import datetime
# Initializing constructor
a = datetime(1999, 12, 12)
print(a)
# Initializing constructor
# with time parameters as well
a = datetime(1999, 12, 12, 12, 12, 12, 342380)
print(a)
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + timedelta(days = 730)
future_date_after_2days = ini_time_for_now + timedelta(days = 2)
# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Some another datetime
new_final_time = ini_time_for_now + 
timedelta(days = 2)
# printing new final_date
print ("new_final_time", str(new_final_time))
# printing calculated past_dates
print('Time difference:', str(new_final_time - 
ini_time_for_now))
functions modules and exceptions handlings.ppt
Exception
Handling
in Python
Python
• Exceptions Exception Handling Try and
Except Nested try Block
• Handling Multiple Exceptions in single
Except Block Raising Exception
• Finally Block
• User Defined Exceptions
Exception
⚫ When writing a program, we, more often than
not, will encounter errors.
⚫ Error caused by not following the proper
structure (syntax) of the language is called
syntax error or parsing error
⚫ Errors can also occur at runtime and these are
called exceptions.
⚫ They occur, for example, when a file we try to
open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError)
⚫ Whenever these type of runtime error occur,
Python creates an exception object. If not
handled properly, it prints a traceback to that
error along with some details about why that
error occurred.
functions modules and exceptions handlings.ppt
Exception Handling
⚫To handle exceptions, and to call code
when an exception occurs, we can use
a try/except statement.
⚫The try block contains code that might
throw an exception.
⚫If that exception occurs, the code in
the try block stops being executed,
and the code in the except block is
executed.
⚫If no error occurs, the code in the
except
block doesn't execute.
functions modules and exceptions handlings.ppt
NestedTry Block
functions modules and exceptions handlings.ppt
⚫A try statement can have
multiple different except
blocks to handle different
exceptions.
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
⚫Multiple exceptions can also be put
into a single except block using
parentheses, to have the except
block handle all of them.
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Raising Exceptions
functions modules and exceptions handlings.ppt
Raising Exception from Except
Block
finally
⚫To ensure some code runs no
matter what errors occur, you can
use a finally statement.
⚫The finally statement is placed at
the bottom of a try/except
statement.
⚫Code within a finally statement
always runs after execution of the
code in the try, and possibly in the
except, blocks.
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
⚫Code in a finally statement even
runs if an uncaught exception
occurs in one of the preceding
blocks.
Raising Exception
⚫Raising exception is similar to
throwing exception in C++/Java.
⚫You can raise exceptions by using
the raise statement
User Defined Exception
Ad

More Related Content

Similar to functions modules and exceptions handlings.ppt (20)

Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
Mohammad Hassan
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Functions
FunctionsFunctions
Functions
Golda Margret Sheeba J
 
Python functions
Python   functionsPython   functions
Python functions
Learnbay Datascience
 
L14-L16 Functions.pdf
L14-L16 Functions.pdfL14-L16 Functions.pdf
L14-L16 Functions.pdf
DeepjyotiChoudhury4
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradeshFunction in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
NehaSpillai1
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradeshFunction in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 

More from Rajasekhar364622 (19)

OS Introduction Operating systems Processes and concepts
OS Introduction Operating systems Processes and conceptsOS Introduction Operating systems Processes and concepts
OS Introduction Operating systems Processes and concepts
Rajasekhar364622
 
Operating systems Processes and concepts
Operating systems Processes and conceptsOperating systems Processes and concepts
Operating systems Processes and concepts
Rajasekhar364622
 
Prompt_Engineering_ chat Presentation.pptx
Prompt_Engineering_ chat Presentation.pptxPrompt_Engineering_ chat Presentation.pptx
Prompt_Engineering_ chat Presentation.pptx
Rajasekhar364622
 
Revolutionizing ChatGPT_Presentation.pptx
Revolutionizing ChatGPT_Presentation.pptxRevolutionizing ChatGPT_Presentation.pptx
Revolutionizing ChatGPT_Presentation.pptx
Rajasekhar364622
 
digital computer present situations.pptx
digital computer present situations.pptxdigital computer present situations.pptx
digital computer present situations.pptx
Rajasekhar364622
 
Python variables in the computer science.pptx
Python variables in the computer science.pptxPython variables in the computer science.pptx
Python variables in the computer science.pptx
Rajasekhar364622
 
Python for the data science most in cse.pptx
Python for the data science most in cse.pptxPython for the data science most in cse.pptx
Python for the data science most in cse.pptx
Rajasekhar364622
 
Unit 2 chapter notes for the student1-1.ppt
Unit 2 chapter  notes for the student1-1.pptUnit 2 chapter  notes for the student1-1.ppt
Unit 2 chapter notes for the student1-1.ppt
Rajasekhar364622
 
MACHINE LEARNING TECHNOLOGY for the topic
MACHINE LEARNING TECHNOLOGY for the topicMACHINE LEARNING TECHNOLOGY for the topic
MACHINE LEARNING TECHNOLOGY for the topic
Rajasekhar364622
 
Touchscreen Technology used now -1.pptx
Touchscreen Technology  used now -1.pptxTouchscreen Technology  used now -1.pptx
Touchscreen Technology used now -1.pptx
Rajasekhar364622
 
Presentation on present trending technologys
Presentation on present trending  technologysPresentation on present trending  technologys
Presentation on present trending technologys
Rajasekhar364622
 
python and web for data science prfrograminh
python and web for data science prfrograminhpython and web for data science prfrograminh
python and web for data science prfrograminh
Rajasekhar364622
 
Machine learning how are things going on
Machine learning how are things going onMachine learning how are things going on
Machine learning how are things going on
Rajasekhar364622
 
Using Tree algorithms on machine learning
Using Tree algorithms on machine learningUsing Tree algorithms on machine learning
Using Tree algorithms on machine learning
Rajasekhar364622
 
DBMS-material for b.tech students to learn
DBMS-material for b.tech students to learnDBMS-material for b.tech students to learn
DBMS-material for b.tech students to learn
Rajasekhar364622
 
unit5-academic writing human intraction.ppt
unit5-academic writing human intraction.pptunit5-academic writing human intraction.ppt
unit5-academic writing human intraction.ppt
Rajasekhar364622
 
Advantages and disadvantages of ML .PPTX
Advantages and disadvantages of ML .PPTXAdvantages and disadvantages of ML .PPTX
Advantages and disadvantages of ML .PPTX
Rajasekhar364622
 
BLOCK CHAIN technology for the students.
BLOCK CHAIN technology for the students.BLOCK CHAIN technology for the students.
BLOCK CHAIN technology for the students.
Rajasekhar364622
 
wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...
wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...
wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...
Rajasekhar364622
 
OS Introduction Operating systems Processes and concepts
OS Introduction Operating systems Processes and conceptsOS Introduction Operating systems Processes and concepts
OS Introduction Operating systems Processes and concepts
Rajasekhar364622
 
Operating systems Processes and concepts
Operating systems Processes and conceptsOperating systems Processes and concepts
Operating systems Processes and concepts
Rajasekhar364622
 
Prompt_Engineering_ chat Presentation.pptx
Prompt_Engineering_ chat Presentation.pptxPrompt_Engineering_ chat Presentation.pptx
Prompt_Engineering_ chat Presentation.pptx
Rajasekhar364622
 
Revolutionizing ChatGPT_Presentation.pptx
Revolutionizing ChatGPT_Presentation.pptxRevolutionizing ChatGPT_Presentation.pptx
Revolutionizing ChatGPT_Presentation.pptx
Rajasekhar364622
 
digital computer present situations.pptx
digital computer present situations.pptxdigital computer present situations.pptx
digital computer present situations.pptx
Rajasekhar364622
 
Python variables in the computer science.pptx
Python variables in the computer science.pptxPython variables in the computer science.pptx
Python variables in the computer science.pptx
Rajasekhar364622
 
Python for the data science most in cse.pptx
Python for the data science most in cse.pptxPython for the data science most in cse.pptx
Python for the data science most in cse.pptx
Rajasekhar364622
 
Unit 2 chapter notes for the student1-1.ppt
Unit 2 chapter  notes for the student1-1.pptUnit 2 chapter  notes for the student1-1.ppt
Unit 2 chapter notes for the student1-1.ppt
Rajasekhar364622
 
MACHINE LEARNING TECHNOLOGY for the topic
MACHINE LEARNING TECHNOLOGY for the topicMACHINE LEARNING TECHNOLOGY for the topic
MACHINE LEARNING TECHNOLOGY for the topic
Rajasekhar364622
 
Touchscreen Technology used now -1.pptx
Touchscreen Technology  used now -1.pptxTouchscreen Technology  used now -1.pptx
Touchscreen Technology used now -1.pptx
Rajasekhar364622
 
Presentation on present trending technologys
Presentation on present trending  technologysPresentation on present trending  technologys
Presentation on present trending technologys
Rajasekhar364622
 
python and web for data science prfrograminh
python and web for data science prfrograminhpython and web for data science prfrograminh
python and web for data science prfrograminh
Rajasekhar364622
 
Machine learning how are things going on
Machine learning how are things going onMachine learning how are things going on
Machine learning how are things going on
Rajasekhar364622
 
Using Tree algorithms on machine learning
Using Tree algorithms on machine learningUsing Tree algorithms on machine learning
Using Tree algorithms on machine learning
Rajasekhar364622
 
DBMS-material for b.tech students to learn
DBMS-material for b.tech students to learnDBMS-material for b.tech students to learn
DBMS-material for b.tech students to learn
Rajasekhar364622
 
unit5-academic writing human intraction.ppt
unit5-academic writing human intraction.pptunit5-academic writing human intraction.ppt
unit5-academic writing human intraction.ppt
Rajasekhar364622
 
Advantages and disadvantages of ML .PPTX
Advantages and disadvantages of ML .PPTXAdvantages and disadvantages of ML .PPTX
Advantages and disadvantages of ML .PPTX
Rajasekhar364622
 
BLOCK CHAIN technology for the students.
BLOCK CHAIN technology for the students.BLOCK CHAIN technology for the students.
BLOCK CHAIN technology for the students.
Rajasekhar364622
 
wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...
wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...
wepik-green-innovations-paving-the-way-for-a-sustainable-future-2023120414035...
Rajasekhar364622
 
Ad

Recently uploaded (20)

To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Ad

functions modules and exceptions handlings.ppt

  • 1. Python - Functions • A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. • As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions.
  • 2. Defining a Function 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. • Syntax: • def functionname( parameters ): • "function_docstring" function_suite return [expression]
  • 3. • 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. • Example: def printme( str ): "This prints a passed string function" print str return
  • 4. Calling a Function • Following is the example to call printme() function: def printme( str ): "This is a print function“ print str; return; printme("I'm first call to user defined function!"); printme("Again second call to the same function"); • This would produce following result: I'm first call to user defined function! Again second call to the same function
  • 5. Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: def changeme( mylist ): "This changes a passed list“ mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist • So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
  • 6. There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): "This changes a passed list" mylist = [1,2,3,4]; print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist • The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 7. Function Arguments: A function by using the following types of formal arguments:: – Required arguments – Keyword arguments – Default arguments – Variable-length arguments Required arguments: • Required arguments are the arguments passed to a function in correct positional order. def printme( str ): "This prints a passed string" print str; return; printme(); • This would produce following result: Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)
  • 8. Keyword arguments: • Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. • This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. def printme( str ): "This prints a passed string" print str; return; printme( str = "My string"); • This would produce following result: My string
  • 9. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); • This would produce following result: Name: miki Age 50
  • 10. Default arguments: • A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. • Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): “Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); printinfo( name="miki" ); • This would produce following result: Name: miki Age 50 Name: miki Age 35
  • 11. Variable-length arguments: • You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. • The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]
  • 12. • An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" print "Output is: " print arg1 for var in vartuple: print var return; printinfo( 10 ); printinfo( 70, 60, 50 ); • This would produce following result: Output is: 10 Output is: 70 60 50
  • 13. The Anonymous Functions: You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. • An anonymous function cannot be a direct call to print because lambda requires an expression. • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. • Syntax: lambda [arg1 [,arg2,.....argn]]:expression
  • 14. Example: • Following is the example to show how lembda form of function works: sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40
  • 15. Scope of Variables: • 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 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 variables Local variables • Global vs. Local variables: • 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.
  • 16. • Example: total = 0; # This is global variable. def sum( arg1, arg2 ): "Add both the parameters" total = arg1 + arg2; print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total • This would produce following result: Inside the function local total : 30 Outside the function global total : 0
  • 17. Type Conversions • When you put an integer and floating point in an expression the integer is implicitly converted to a float • You can control this with the built in functions int() and float() >>> print float(99) / 100 0.99 >>> i = 42 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 * float(3) / 4 - 5 -2.5 >>>
  • 18. String Conversions • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <type 'str'> >>> print sval + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) <type 'int'> >>> print ival + 1 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int()
  • 19. Building our Own Functions • We create a new function using the def keyword followed by optional parameters in parenthesis. • We indent the body of the function • This defines the function but does not execute the body of the function def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.'
  • 20. x = 5 print 'Hello' def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.' print 'Yo' x = x + 2 print x Hello Yo 7 print "I'm a lumberjack, and I'm okay." print 'I sleep all night and I work all day.' print_lyrics():
  • 21. Definitions and Uses • Once we have defined a function, we can call (or invoke) it as many times as we like • This is the store and reuse pattern
  • 22. x = 5 print 'Hello' def print_lyrics(): print "I'm a lumberjack, and I'm okay.” print 'I sleep all night and I work all day.' print 'Yo' print_lyrics() x = x + 2 print x Hello Yo I'm a lumberjack, and I'm okay.I sleep all night and I work all day. 7
  • 23. 1. Write a Python function to find the Max of three numbers. 2.Write a Python function to sum all the numbers in a list. Sample List : (8, 2, 3, 0, 7) 3.Write a Python function to reverse a string. 4.Write a Python function that takes a list and returns a new list with unique elements of the first list.
  • 24. 1)def maximum(a, b, c): if (a >= b) and (a >= c): largest = a elif (b >= a) and (b >= c): largest = b else: largest = c return largest # Driven code a = 10 b = 14 c = 12 print(maximum(a, b, c))
  • 25. 2)def sum(numbers): total = 0 for x in numbers: total += x return total print(sum((8, 2, 3, 0, 7)))
  • 26. 3)def reverse(string): string = string[::-1] #Using Slicing return string s = "IloveIndia" print ("The original string is : ",end="") print (s) print ("The reversed string(using extended slice syntax) is : ",end="") print (reverse(s))
  • 27. 4)def unique_list(l): x = [] for a in l: if a not in x: x.append(a) return x print(unique_list([1,2,3,3,3,3,4,5]))
  • 30. • To display a list of all available modules, use the following command in the Python console >>> help(‘modules’)
  • 31. OS MODULE • mkdir( ) - A new directory corresponding to the path in the string argument of the function will be created. • getcwd( ) - current working directory • rmdir( ) - removes the specified directory either with an absolute or relative path. However, we can not remove the current working directory. Also, for a directory to be removed, it should be empty. • listdir( ) - returns the list of all files and directories in the specified directory. If we don't specify any directory, then list of files and directories in the current working directory will be returned.
  • 32. SYS MODULE • sys.argv - returns a list of command line arguments passed to a Python script. The item at index 0 in this list is always the name of the script. The rest of the arguments are stored at the subsequent indices. • sys.maxsize - Returns the largest integer a variable can take. • sys.path - This is an environment variable that is a search path for all Python modules. • sys.version - This attribute displays a string containing the version number of the current Python interpreter.
  • 33. PYTHON MODULES Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
  • 34. A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:
  • 36. Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.
  • 43. # Python program to # demonstrate date class # import the date class from datetime import date # initializing constructor # and passing arguments in the # format year, month, date my_date = date(1996, 12, 11) print("Date passed as argument is", my_date) # Uncommenting my_date = date(1996, 12, 39) # will raise an ValueError as it is # outside range # uncommenting my_date = date('1996', 12, 11) # will raise a TypeError as a string is # passed instead of integer
  • 44. Current date To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually. # Python program to # print current date from datetime import date # calling the today # function of date class today = date.today() print("Today's date is", today) # Printing date's components print("Date components", today.year, today.month, today.day)
  • 46. Time class Time object represents local time, independent of any day. Constructor Syntax: class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the following range – •0 <= hour < 24 •0 <= minute < 60 •0 <= second < 60 •0 <= microsecond < 1000000 •fold in [0, 1]
  • 47. # Python program to # demonstrate time class from datetime import time # calling the constructor my_time = time(13, 24, 56) print("Entered time", my_time) # calling constructor with 1 # argument my_time = time(minute = 12) print("nTime with one argument", my_time) # Calling constructor with # 0 argument my_time = time() print("nTime without argument", my_time) # Uncommenting time(hour = 26) # will rase an ValueError as # it is out of range # uncommenting time(hour ='23') # will raise TypeError as # string is passed instead of int
  • 48. from datetime import time Time = time(11, 34, 56) print("hour =", Time.hour) print("minute =", Time.minute) print("second =", Time.second) print("microsecond =", Time.microsecond) Output: hour = 11 minute = 34 second = 56 microsecond = 0
  • 50. # Python program to # demonstrate datetime object from datetime import datetime # Initializing constructor a = datetime(1999, 12, 12) print(a) # Initializing constructor # with time parameters as well a = datetime(1999, 12, 12, 12, 12, 12, 342380) print(a)
  • 53. # Timedelta function demonstration from datetime import datetime, timedelta # Using current time ini_time_for_now = datetime.now() # printing initial_date print ("initial_date", str(ini_time_for_now)) # Calculating future dates # for two years future_date_after_2yrs = ini_time_for_now + timedelta(days = 730) future_date_after_2days = ini_time_for_now + timedelta(days = 2) # printing calculated future_dates print('future_date_after_2yrs:', str(future_date_after_2yrs)) print('future_date_after_2days:', str(future_date_after_2days))
  • 54. # Timedelta function demonstration from datetime import datetime, timedelta # Using current time ini_time_for_now = datetime.now() # printing initial_date print ("initial_date", str(ini_time_for_now)) # Some another datetime new_final_time = ini_time_for_now + timedelta(days = 2) # printing new final_date print ("new_final_time", str(new_final_time)) # printing calculated past_dates print('Time difference:', str(new_final_time - ini_time_for_now))
  • 57. Python • Exceptions Exception Handling Try and Except Nested try Block • Handling Multiple Exceptions in single Except Block Raising Exception • Finally Block • User Defined Exceptions
  • 58. Exception ⚫ When writing a program, we, more often than not, will encounter errors. ⚫ Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error ⚫ Errors can also occur at runtime and these are called exceptions. ⚫ They occur, for example, when a file we try to open does not exist (FileNotFoundError), dividing a number by zero (ZeroDivisionError) ⚫ Whenever these type of runtime error occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred.
  • 60. Exception Handling ⚫To handle exceptions, and to call code when an exception occurs, we can use a try/except statement. ⚫The try block contains code that might throw an exception. ⚫If that exception occurs, the code in the try block stops being executed, and the code in the except block is executed. ⚫If no error occurs, the code in the except block doesn't execute.
  • 64. ⚫A try statement can have multiple different except blocks to handle different exceptions.
  • 67. ⚫Multiple exceptions can also be put into a single except block using parentheses, to have the except block handle all of them.
  • 72. Raising Exception from Except Block
  • 73. finally ⚫To ensure some code runs no matter what errors occur, you can use a finally statement. ⚫The finally statement is placed at the bottom of a try/except statement. ⚫Code within a finally statement always runs after execution of the code in the try, and possibly in the except, blocks.
  • 76. ⚫Code in a finally statement even runs if an uncaught exception occurs in one of the preceding blocks.
  • 77. Raising Exception ⚫Raising exception is similar to throwing exception in C++/Java. ⚫You can raise exceptions by using the raise statement