SlideShare une entreprise Scribd logo
1  sur  33
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.
Function
Defining a Function
You can define 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 code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits a function,
Maulik Borsaniya - Gardividyapith
User Defining Function
• Simple function
def my_function():
print("Hello from a function")
my_function()
• Parameterized Function
Def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
• Return Value
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Maulik Borsaniya - Gardividyapith
Built In Function
List of Built in function
Maulik Borsaniya - Gardividyapith
Maulik Borsaniya - Gardividyapith
Maulik Borsaniya - Gardividyapith
Maulik Borsaniya - Gardividyapith
Maulik Borsaniya - Gardividyapith
ABS()
integer = -20
print('Absolute value of -20 is:',abs(integer))
Chr()
print(chr(97))
print(chr(65))
Max & Min
# using max(arg1, arg2, *args)
print('Maximum is:', max(1, 3, 2, 10, 4))
# using min(iterable)
num = [1, 3, 2, 8, 5, 10, 6]
print('Maximum is:', min(num))
Maulik Borsaniya - Gardividyapith
Method
• Python has some list methods that you can use
to perform frequency occurring task (related to
list) with ease. For example, if you want to add
element to a list, you can use append() method.
Simple Example
animal = ['cat', 'dog', 'rabbit']
animal.append('pig')
#Updated Animal List
print('Updated animal list: ',
animal)
• Eg-1 Eg-2
numbers = [2.5, 3, 4, -5]
numbersSum = sum(numbers)
print(numbersSum)
Maulik Borsaniya - Gardividyapith
Maulik Borsaniya - Gardividyapith
Maulik Borsaniya - Gardividyapith
Difference Between method and function
Python Method
• Method is called by its name, but it is associated to an object (dependent).
• A method is implicitly passed the object on which it is invoked.
• It may or may not return any data.
• A method can operate on the data (instance variables) that is contained by
the corresponding class
Functions
• Function is block of code that is also called by its name. (independent)
• The function can have different parameters or may not have any at all. If any
data (parameters) are passed, they are passed explicitly.
• It may or may not return any data.
• Function does not deal with Class and its instance concept.
Maulik Borsaniya - Gardividyapith
# Basic Python method
class class_name
def method_name () :
......
# method body
#Function Syntex
def function_name ( arg1, arg2, ...) :
......
# function body
......
Maulik Borsaniya - Gardividyapith
Lambda
• A lambda function is a small anonymous
function.
• A lambda function can take any number of
arguments, but can only have one expression.
Syntax
• lambda arguments : expression
• Eg.1 x = lambda a : a + 10
print(x(5))
• Eg.2 x = lambda a, b : a * b
print(x(5, 6))
Maulik Borsaniya - Gardividyapith
Why Use Lambda Functions?
The power of lambda is better shown when you use them as
an anonymous function inside another function.
Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown
number.
• Eg.
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
print(mydoubler(10))
Maulik Borsaniya - Gardividyapith
Filter With Lambda
• The filter() function in Python takes in a function and a list
as arguments.
• The function is called with all the items in the list and a new
list is returned which contains items for which the function
evaluates to True.
• Here is an example use of filter() function to filter out only
even numbers from a list.
• Eg.1
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Maulik Borsaniya - Gardividyapith
Map With Lambda
• The map() function in Python takes in a function and
a list.
• The function is called with all the items in the list and
a new list is returned which contains items returned
by that function for each item.
• Here is an example use of map() function to double
all the items in a list.
• Eg.1
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Maulik Borsaniya - Gardividyapith
Creating our own module
1) Hello.py
# Define a function
def world():
print("Hello, World!")
2) Main.py
# Import hello module
import hello
# Call function
hello.world()
 print(hello.variable)
 variable = "Sammy"
Maulik Borsaniya - Gardividyapith
Exception Handling
• An exception is an event, which occurs during
the execution of a program that disrupts the
normal flow of the program's instructions. In
general, when a Python script encounters a
situation that it cannot cope with, it raises an
exception. An exception is a Python object
that represents an error.
• When a Python script raises an exception, it
must either handle the exception immediately
otherwise it terminates and quits.(there are
many built in exception is there)Maulik Borsaniya - Gardividyapith
Syntax
try:
You do your operations here;
......................
except Exception 1:
If there is Exception 1, then execute this block.
…………………….
except Exception 2:
If there is Exception 2, then execute this block.
......................
else:
If there is no exception then execute this block.
finally :
This would always be executed
Maulik Borsaniya - Gardividyapith
• Example
try:
fh = open("asd.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can't find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Finally:
Print “wow Yaar !! You wrotted hainn !”
Maulik Borsaniya - Gardividyapith
Exception Handling With Assert Statement
• Syntex : assert
expression, argument,
messag
Eg . assert 2 + 2 == 4
assert 2 + 3 == 3, ’’error is
here’’
Eg.2
def avg(marks):
assert len(marks) != 0,"List is
empty.“
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of
mark2:",avg(mark2))
mark1 = []
print("Average of
mark1:",avg(mark1))
• Python has built-in assert
statement to use assertion
condition in the program.
• assert statement has a
condition or expression which
is supposed to be always true.
• If the condition is
false assert halts the program
and gives an AssertionError.
Maulik Borsaniya - Gardividyapith
User Define Exception
class Error(Exception):
"""Base class for other
exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is
too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is
too large"""
pass
# our main program
# user guesses a number until
he/she gets it right
# you need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a
number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try
again!")
print()
except ValueTooLargeError:
print("This value is too large, try
again!")
print()
print("Congratulations! You guessed
it correctly.")
Maulik Borsaniya - Gardividyapith
• File Handling
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
• "r" - Read - Default value. Opens a file for reading, error if the file
does not exist
• "a" - Append - Opens a file for appending, creates the file if it does
not exist
• "w" - Write - Opens a file for writing, creates the file if it does not
exist
• "x" - Create - Creates the specified file, returns an error if the file
exists
Maulik Borsaniya - Gardividyapith
DemoFile.txt
• Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Python file read 
f = open("demofile.txt", "r")
print(f.read())
#print(f.readline())
append 
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
Write 
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
Maulik Borsaniya - Gardividyapith
Remove file
import os
if os.path.exists(“demofile"):
os.remove(“demofile")
else:
print("The file does not exist")
Maulik Borsaniya - Gardividyapith
File Positions
• The tell() method tells you the current position within
the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.
• The seek(offset[, from]) method changes the current
file position. The offset argument indicates the number
of bytes to be moved. The from argument specifies the
reference position from where the bytes are to be
moved.
• If from is set to 0, it means use the beginning of the file
as the reference position and 1 means use the current
position as the reference position and if it is set to 2
then the end of the file would be taken as the
reference position.
Maulik Borsaniya - Gardividyapith
• # Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
Maulik Borsaniya - Gardividyapith
Sr.No. Modes & Description
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is
the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the
file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file
for writing.
Maulik Borsaniya - Gardividyapith
6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and
writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
Maulik Borsaniya - Gardividyapith
Running Other Programs from Python
Program – Windows python
• import os
• command = "cmd"
• os.system(command)
Maulik Borsaniya - Gardividyapith
Python For Loops
• A for loop is used for iterating over a sequence (that is
either a list, a tuple or a string).
• This is less like the for keyword in other programming
language, and works more like an iterator method as found
in other object-orientated programming languages.
• With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
Example
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Maulik Borsaniya - Gardividyapith
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
• for x in range(2, 30, 3):
print(x)
• i = 1
while i < 6:
print(i)
i += 1
Maulik Borsaniya - Gardividyapith

Contenu connexe

Tendances

Python functional programming
Python functional programmingPython functional programming
Python functional programmingGeison Goes
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlibPiyush rai
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaEdureka!
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Edureka!
 
Generators In Python
Generators In PythonGenerators In Python
Generators In PythonSimplilearn
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabusSugantha T
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 

Tendances (20)

Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 
Python basics
Python basicsPython basics
Python basics
 
Generators In Python
Generators In PythonGenerators In Python
Generators In Python
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Python libraries
Python librariesPython libraries
Python libraries
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Python GUI
Python GUIPython GUI
Python GUI
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 

Similaire à PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BORSANIYA

Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programsGeethaPanneer
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxleavatin
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 

Similaire à PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BORSANIYA (20)

Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
Python advance
Python advancePython advance
Python advance
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
Python functions
Python functionsPython functions
Python functions
 
Advance python
Advance pythonAdvance python
Advance python
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 

Plus de Maulik Borsaniya

Dragon fruit-nutrition-facts
Dragon fruit-nutrition-factsDragon fruit-nutrition-facts
Dragon fruit-nutrition-factsMaulik Borsaniya
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAMaulik Borsaniya
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYAPYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYAMaulik Borsaniya
 
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYAPYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYAMaulik Borsaniya
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 

Plus de Maulik Borsaniya (6)

Dragon fruit-nutrition-facts
Dragon fruit-nutrition-factsDragon fruit-nutrition-facts
Dragon fruit-nutrition-facts
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYAPYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
 
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYAPYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 

Dernier

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BORSANIYA

  • 1. 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. Function Defining a Function You can define 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 code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, Maulik Borsaniya - Gardividyapith
  • 2. User Defining Function • Simple function def my_function(): print("Hello from a function") my_function() • Parameterized Function Def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") • Return Value def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9)) Maulik Borsaniya - Gardividyapith
  • 3. Built In Function List of Built in function Maulik Borsaniya - Gardividyapith
  • 4. Maulik Borsaniya - Gardividyapith
  • 5. Maulik Borsaniya - Gardividyapith
  • 6. Maulik Borsaniya - Gardividyapith
  • 7. Maulik Borsaniya - Gardividyapith
  • 8. ABS() integer = -20 print('Absolute value of -20 is:',abs(integer)) Chr() print(chr(97)) print(chr(65)) Max & Min # using max(arg1, arg2, *args) print('Maximum is:', max(1, 3, 2, 10, 4)) # using min(iterable) num = [1, 3, 2, 8, 5, 10, 6] print('Maximum is:', min(num)) Maulik Borsaniya - Gardividyapith
  • 9. Method • Python has some list methods that you can use to perform frequency occurring task (related to list) with ease. For example, if you want to add element to a list, you can use append() method. Simple Example animal = ['cat', 'dog', 'rabbit'] animal.append('pig') #Updated Animal List print('Updated animal list: ', animal) • Eg-1 Eg-2 numbers = [2.5, 3, 4, -5] numbersSum = sum(numbers) print(numbersSum) Maulik Borsaniya - Gardividyapith
  • 10. Maulik Borsaniya - Gardividyapith
  • 11. Maulik Borsaniya - Gardividyapith
  • 12. Difference Between method and function Python Method • Method is called by its name, but it is associated to an object (dependent). • A method is implicitly passed the object on which it is invoked. • It may or may not return any data. • A method can operate on the data (instance variables) that is contained by the corresponding class Functions • Function is block of code that is also called by its name. (independent) • The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly. • It may or may not return any data. • Function does not deal with Class and its instance concept. Maulik Borsaniya - Gardividyapith
  • 13. # Basic Python method class class_name def method_name () : ...... # method body #Function Syntex def function_name ( arg1, arg2, ...) : ...... # function body ...... Maulik Borsaniya - Gardividyapith
  • 14. Lambda • A lambda function is a small anonymous function. • A lambda function can take any number of arguments, but can only have one expression. Syntax • lambda arguments : expression • Eg.1 x = lambda a : a + 10 print(x(5)) • Eg.2 x = lambda a, b : a * b print(x(5, 6)) Maulik Borsaniya - Gardividyapith
  • 15. Why Use Lambda Functions? The power of lambda is better shown when you use them as an anonymous function inside another function. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number. • Eg. def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) print(mydoubler(10)) Maulik Borsaniya - Gardividyapith
  • 16. Filter With Lambda • The filter() function in Python takes in a function and a list as arguments. • The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True. • Here is an example use of filter() function to filter out only even numbers from a list. • Eg.1 my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list) Maulik Borsaniya - Gardividyapith
  • 17. Map With Lambda • The map() function in Python takes in a function and a list. • The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item. • Here is an example use of map() function to double all the items in a list. • Eg.1 my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2 , my_list)) print(new_list) Maulik Borsaniya - Gardividyapith
  • 18. Creating our own module 1) Hello.py # Define a function def world(): print("Hello, World!") 2) Main.py # Import hello module import hello # Call function hello.world()  print(hello.variable)  variable = "Sammy" Maulik Borsaniya - Gardividyapith
  • 19. Exception Handling • An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error. • When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.(there are many built in exception is there)Maulik Borsaniya - Gardividyapith
  • 20. Syntax try: You do your operations here; ...................... except Exception 1: If there is Exception 1, then execute this block. ……………………. except Exception 2: If there is Exception 2, then execute this block. ...................... else: If there is no exception then execute this block. finally : This would always be executed Maulik Borsaniya - Gardividyapith
  • 21. • Example try: fh = open("asd.txt", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" fh.close() Finally: Print “wow Yaar !! You wrotted hainn !” Maulik Borsaniya - Gardividyapith
  • 22. Exception Handling With Assert Statement • Syntex : assert expression, argument, messag Eg . assert 2 + 2 == 4 assert 2 + 3 == 3, ’’error is here’’ Eg.2 def avg(marks): assert len(marks) != 0,"List is empty.“ return sum(marks)/len(marks) mark2 = [55,88,78,90,79] print("Average of mark2:",avg(mark2)) mark1 = [] print("Average of mark1:",avg(mark1)) • Python has built-in assert statement to use assertion condition in the program. • assert statement has a condition or expression which is supposed to be always true. • If the condition is false assert halts the program and gives an AssertionError. Maulik Borsaniya - Gardividyapith
  • 23. User Define Exception class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass # our main program # user guesses a number until he/she gets it right # you need to guess this number number = 10 while True: try: i_num = int(input("Enter a number: ")) if i_num < number: raise ValueTooSmallError elif i_num > number: raise ValueTooLargeError break except ValueTooSmallError: print("This value is too small, try again!") print() except ValueTooLargeError: print("This value is too large, try again!") print() print("Congratulations! You guessed it correctly.") Maulik Borsaniya - Gardividyapith
  • 24. • File Handling The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: • "r" - Read - Default value. Opens a file for reading, error if the file does not exist • "a" - Append - Opens a file for appending, creates the file if it does not exist • "w" - Write - Opens a file for writing, creates the file if it does not exist • "x" - Create - Creates the specified file, returns an error if the file exists Maulik Borsaniya - Gardividyapith
  • 25. DemoFile.txt • Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck! Python file read  f = open("demofile.txt", "r") print(f.read()) #print(f.readline()) append  f = open("demofile.txt", "a") f.write("Now the file has one more line!") Write  f = open("demofile.txt", "w") f.write("Woops! I have deleted the content!") Maulik Borsaniya - Gardividyapith
  • 26. Remove file import os if os.path.exists(“demofile"): os.remove(“demofile") else: print("The file does not exist") Maulik Borsaniya - Gardividyapith
  • 27. File Positions • The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file. • The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. • If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position. Maulik Borsaniya - Gardividyapith
  • 28. • # Open a file fo = open("foo.txt", "r+") str = fo.read(10); print "Read String is : ", str # Check current position position = fo.tell(); print "Current file position : ", position # Reposition pointer at the beginning once again position = fo.seek(0, 0); str = fo.read(10); print "Again read String is : ", str # Close opend file fo.close() Maulik Borsaniya - Gardividyapith
  • 29. Sr.No. Modes & Description 1 r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. 2 rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. 3 r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. 4 rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. 5 w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Maulik Borsaniya - Gardividyapith
  • 30. 6 wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. 7 w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. 8 wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. 9 a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. 10 ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. 11 a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. 12 ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. Maulik Borsaniya - Gardividyapith
  • 31. Running Other Programs from Python Program – Windows python • import os • command = "cmd" • os.system(command) Maulik Borsaniya - Gardividyapith
  • 32. Python For Loops • A for loop is used for iterating over a sequence (that is either a list, a tuple or a string). • This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages. • With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. Example • fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) Maulik Borsaniya - Gardividyapith
  • 33. • fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) • for x in range(2, 30, 3): print(x) • i = 1 while i < 6: print(i) i += 1 Maulik Borsaniya - Gardividyapith