SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados (20)

Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Namespaces
NamespacesNamespaces
Namespaces
 
NUMPY
NUMPY NUMPY
NUMPY
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
python Function
python Function python Function
python Function
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
List in Python
List in PythonList in Python
List in Python
 

Semelhante a 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
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
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
 

Semelhante a 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
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
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
 

Mais 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
 
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
 

Mais de Maulik Borsaniya (7)

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
 
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
 

Último

[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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

[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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

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