SlideShare a Scribd company logo
UNIT-I
FUNCTIONS
 Function is a sub program which consists of set of instructions used to perform a specific task.
 A large program is divided into basic building blocks called function
Need For Function
 When the program is too complex and large they are divided into parts. Each part is separately coded
and combined into single program. Each subprogram is called as function.
 Debugging, Testing and maintenance becomes easy when the program is divided into subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced.
Types of Functions
 Functions are classified into 2-types
 Built-in Functions (or) Pre-defined Functions
 User Defined Functions
Built in functions
 Built in functions are the functions that are already created and stored in python
 These built in functions are always available for usage and accessed by a programmer. It cannot
be modified
 Ex: Max,min,len,range,input…etc
User Defined Functions
 User defined functions are the functions that programmers create for their requirement and use.
 These functions can then be combined to form module which can be used in other programs by
importing them
 Advantages of user defined functions:
 Programmers working on large project can divide the workload by making different functions.
 If repeated code occurs in a program, function can be used to include those codes and execute when
needed by calling that function
Function definition
 def keyword is used to define a function.
 Give the function name after def keyword followed by parentheses in which arguments are given.
 End with colon (:)
 Inside the function add the program statements to be executed
 End with or without return statemen
 Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]
Example
def my_add(a,b):
c=a+b
return c
Function Calling
 Once we have defined a function, we can call it from another function, program or even the Python
prompt.
 To call a function we simply type the function name with appropriatearguments.
 Example:
x=5
y=4
my_add(x,y)
Flow of Execution
 The order in which statements are executed is called the flow of execution
 Execution always begins at the first statement of the program.
 Statements are executed one at a time, in order, from top to bottom.
 Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
 Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the
flow jumps to the first line of the called function, executes all the statements there, and then comes
back to pick up where it left off.
Function Prototypes
 Function without arguments and without return type
 Function with arguments and without return type
 Function without arguments and with return type
 Function with arguments and with return type
Function Arguments
 You can call a function by using the following types of formal arguments −
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Function without arguments and without
return type
 In this type no argument is passed through the function call and no output is return to main function
 The sub function will read the input values perform the operation and print the result in the same
block
Error and Exception
 An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions.
 When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits
Python Built-in Exceptions
 Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.
 AttributeError Raised when attribute assignment or reference fails.
 EOFError : Raised when the input() functions hits end-of-file condition.
 FloatingPointError : Raised when a floating point operation fails.
 GeneratorExit : Raise when a generator's close() method is called.
 OverflowError : Raised when result of an arithmetic operation is too large to be represented.
 ReferenceError : Raised when a weak reference proxy is used to access a garbage collected referent.
 RuntimeError : Raised when an error does not fall under any other category.
Exception Handling
 To handle the exception, python use below keywords
 try
 except
 else
 finally
 raise
 The try: block contains one or more statements which are likely to encounter an exception. If the
statements in this block are executed without an exception, the subsequent except: block is
skipped.
 Except : this code is only executed if an exception occured in the try block. The except block is
required with a try block, even if it contains only the pass statement.
 else: Code in the else block is only executed if no exceptions were raised in the try block.
 finally: The code in the finally block is always executed, regardless of if a an exception was raised
or not.
Catching Exceptions in Python
try:
x=int(input(“Enter value of x:”))
y=int(input(“Enter value of y:”))
z=x/y
print(z)
except ZeroDivisionError:
print('Divided by zero')
print('Should reach here')
Catching Generic Exceptions in Python
try:
x=int(input(“Enter value of x:”))
y=int(input(“Enter value of y:”))
z=x/y
print(z)
except :
print('Divided by zero')
print('Should reach here')
try else
try:
x = 1
except:
print('Failed to set x')
else:
print('No exception occurred')
finally:
print('We always do this')
raise
x = 110
try:
if x < 0:
raise Exception("Sorry, no numbers below zero")
except Exception as ex:
print(ex.args)
else:
print("value of X:",x)
Comprehensions in Python
 Comprehensions in Python provide us with a short and concise way to construct new sequences
(such as lists, set, dictionary etc.)
 using sequences which have been already defined.
 Python supports the following 4 types of comprehensions
 List Comprehensions
 Dictionary Comprehensions
 Set Comprehensions
 Generator Comprehensions
List Comprehensions
 List Comprehensions provide an stylish way to create new lists
 Syntax
 output_list = [output_exp for var in input_list if (var satisfies this condition)]
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
for var in input_list:
if var % 2 == 0:
output_list.append(var)
print("Output List using for loop:", output_list)
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
list_using_comp = [var for var in input_list if var % 2 == 0]
print("Output List using list comprehensions:", list_using_comp)
list_using_comp = [var**2 for var in range(1, 10)]
print("Output List using list comprehension:", list_using_comp)
Dictionary Comprehensions
 we can also create a dictionary using dictionary comprehensions
 output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
for var in input_list:
if var % 2 != 0:
output_dict[var] = var**3
print("Output Dictionary using for loop:", output_dict )
input_list = [1,2,3,4,5,6,7]
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}
print("Output Dictionary using dictionary comprehensions:", dict_using_comp)
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
output_dict = {}
for (key, value) in zip(state, capital):
output_dict[key] = value
print("Output Dictionary using for loop:", output_dict)
Note : Python zip() method takes iterable or containers and returns a single iterator object, having
mapped values from all the containers
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
dict_using_comp = {key:value for (key, value) in zip(state, capital)}
print("Output Dictionary using dictionary comprehensions:", dict_using_comp)
Set Comprehensions
 Set comprehensions are similar to list comprehensions.
 The only difference between them is that set comprehensions use curly brackets { }
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
for var in input_list:
if var % 2 == 0:
output_set.add(var)
print("Output Set using for loop:", output_set)
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp = {var for var in input_list if var % 2 == 0}
print("Output Set using set comprehensions:", set_using_comp)
Generator Comprehensions
 Generator Comprehensions are very similar to list comprehensions.
 One difference between them is that generator comprehensions use circular brackets whereas list
comprehensions use square brackets
 The major difference between them is that generators don’t allocate memory for the whole list
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_gen = (var for var in input_list if var % 2 == 0)
print("Output values using generator comprehensions:", end = ' ')
for var in output_gen:
print(var, end = ' ')
Generators and Iterators
 Iteration is the idea of repeating some process over a sequence of items. In Python, iteration is
usually related to the for loop.
 An iterable is an object that supports iteration.
Eager evaluation
 As soon as call fun(), The
Expression is evaluated and return
resulted value
Lazy evaluation
 The Main idea behind lazy evaluation is
to evaluate expression only when
needed
Iterator
 An iterator is an object which contains a countable number of values and it is used to iterate over
iterable objects like list, tuples, sets, etc
 It follows lazy evaluation where the evaluation of the expression will be on hold and stored in the
memory until the item is called specifically which helps us to avoid repeated evaluation
 Using an iterator-
 iter() keyword is used to create an iterator containing an iterable object.
 next() keyword is used to call the next element in the iterable object.
Generators
 Generators simplifies creation of iterators.
 A generator is a function that produces a sequence of results instead of a single value.
 Generators are iterables
Sorting
 Python sorted() function returns a sorted list from the iterable object.
 Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted
manner, without modifying the original sequence.
 Syntax: sorted(iterable, key, reverse)
 Iterable : sequence (list, tuple, string) or collection (dictionary, set) or any other iterator that needs to be
sorted.
 Key(optional) : A function that would server as a key or a basis of sort comparison.
 Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it
is set as false.
 X=sorted(list)
Python sorted() key
 sorted() function has an optional parameter called ‘key’ which takes a function as its value
 For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify
key = len, i.e. give len function as key, then the strings would be passed to len, and the value it
returns, i.e. the length of strings will be sorted
L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))
L=[3,8,12,15,19]
def fun(x):
return x%2
x=sorted(L,key=fun)
print(x)
Randomness
 Python can generate such random numbers by using the random module
 function random(), which generates a random float number between 0.0 and 1.0
 Methods:
 Random() :which generates a random float number between 0.0 and 1.0
 Choice(list/tuple) : The choice() is an inbuilt function in the Python programming language that returns a
random item from a list, tuple, or string
 randrange(beg, end, step) : function that can generate random numbers from a specified range
 randint(beg,end) : method generates a integer between a given range of numbers
 sample(range,no.of_numbers) : to directly generate a list of random numbers
 Ex: random.sample(range(10,50),5)
 Seed(int): The seed function is used to save the state of a random function so that it can generate
some random numbers on multiple executions of the code on the same machine or on different
machines (for a specific seed value)
 shuffle() Takes a sequence and returns the sequence in a random order
 random.shuffle(mylist)
Regular Expressions
 A Regular Expressions (RegEx) is a special sequence of characters that uses a search pattern to
find a string or set of strings.
 It can detect the presence or absence of a text by matching it with a particular pattern, and also
can split a pattern into one or more sub-patterns.
 Python provides a re module that supports the use of regex in Python
MetaCharacters
Metacharacters Description
[ ] Represent a character class
^ Matches the beginning
$ Matches the end
. Matches any character except newline
| Means OR (Matches with any of the characters separated by it.
? Matches zero or one occurrence
* Any number of occurrences (including 0 occurrences)
+ One or more occurrences
Special Sequences
 Special sequences do not match for the actual character in the string instead it tells the specific
location in the search string where the match must occur
Special Sequence Description
d Matches any decimal digit, this is equivalent to the set class [0-9]
D Matches any non-digit character, this is equivalent to the set class [^0-9]
w Matches any alphanumeric character, this is equivalent to the class [a-zA-Z0-9_].
W Matches any non-alphanumeric character.
findall()
 Return all non-overlapping
matches of pattern in string,
as a list of strings
compile()
 Regular expressions are compiled
into pattern objects, which have
methods for various operations
such as searching for pattern
matches or performing string
substitutions
split()
 Split string by the occurrences of a character or a pattern
 re.split(pattern, string, maxsplit=0, flags=0)
 The First parameter, pattern denotes the regular expression
 string is the given string in which pattern will be searched for and in which splitting occurs
 maxsplit if not provided is considered to be zero ‘0’, and if any nonzero value is provided,
then at most that many splits occur.
 If maxsplit = 1, then the string will split once only, resulting in a list of length 2.
 The flags are very useful and can help to shorten code, they are not necessary parameters,
eg: flags = re.IGNORECASE, in this split, the case, i.e. the lowercase or the uppercase will
be ignored
sub()
 The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in
the given string and upon finding the substring pattern is replaced by repl, count checks and
maintains the number of times this occurs
 Syntax:
 re.sub(pattern, repl, string, count=0, flags=0)
OOP’S
 object-oriented Programming (OOPs) is a programming model that uses objects and classes in
programming.
 It aims to implement real-world entities like inheritance, polymorphisms, encapsulation
 The main concept of OOPs is to bind the data and the functions that work on that together as a
single unit so that no other part of the code can access this data
Concepts of Object-Oriented Programming
 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction
Class
 A class is a collection of objects
 It is a logical entity that contains some attributes and methods
 Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator
Creating an empty Class in Python
class Student:
pass
Objects
 The object is an entity that has a state and behavior associated with it
 An object consists of :
 State: It is represented by the attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
 Identity: It gives a unique name to an object and enables one object to interact with other objects.
 Syntax:
Obj = Student()
__init__ method
 The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a
class is instantiated
Inheritance
 Inheritance is the capability of one class to derive or inherit the properties from another class
 The existing class is called base class or parent class or super class
 Newly created class is called derived class or child class or sub class
 Types of inheritances
 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
Polymorphism
 Polymorphism is an object-oriented programming concept that allows us to perform a single action
in different ways
Encapsulation
 Encapsulation is one of the fundamental concepts in object-oriented programming (OOP).
 It describes the idea of wrapping data and the methods that work on data within one unit
enumerate
 Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object.
This enumerated object can then be used directly for loops or converted into a list of tuples using
the list() method.
 Syntax:
 enumerate(iterable, start=0)
 Parameters:
 Iterable: any object that supports iteration
 Start: the index value from which the counter is to be started, by default it is 0
Python_UNIT-I.pptx

More Related Content

Similar to Python_UNIT-I.pptx

Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
basics of python programming5.pdf
basics of python programming5.pdfbasics of python programming5.pdf
basics of python programming5.pdf
Pushkaran3
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
P3 InfoTech Solutions Pvt. Ltd.
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
Deepak Singh
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
Hattori Sidek
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
What is storage class
What is storage classWhat is storage class
What is storage class
Isha Aggarwal
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 

Similar to Python_UNIT-I.pptx (20)

Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
basics of python programming5.pdf
basics of python programming5.pdfbasics of python programming5.pdf
basics of python programming5.pdf
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions
FunctionsFunctions
Functions
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Recently uploaded

Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 

Recently uploaded (20)

Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 

Python_UNIT-I.pptx

  • 2. FUNCTIONS  Function is a sub program which consists of set of instructions used to perform a specific task.  A large program is divided into basic building blocks called function
  • 3. Need For Function  When the program is too complex and large they are divided into parts. Each part is separately coded and combined into single program. Each subprogram is called as function.  Debugging, Testing and maintenance becomes easy when the program is divided into subprograms.  Functions are used to avoid rewriting same code again and again in a program.  Function provides code re-usability  The length of the program is reduced.
  • 4. Types of Functions  Functions are classified into 2-types  Built-in Functions (or) Pre-defined Functions  User Defined Functions
  • 5. Built in functions  Built in functions are the functions that are already created and stored in python  These built in functions are always available for usage and accessed by a programmer. It cannot be modified  Ex: Max,min,len,range,input…etc
  • 6. User Defined Functions  User defined functions are the functions that programmers create for their requirement and use.  These functions can then be combined to form module which can be used in other programs by importing them  Advantages of user defined functions:  Programmers working on large project can divide the workload by making different functions.  If repeated code occurs in a program, function can be used to include those codes and execute when needed by calling that function
  • 7. Function definition  def keyword is used to define a function.  Give the function name after def keyword followed by parentheses in which arguments are given.  End with colon (:)  Inside the function add the program statements to be executed  End with or without return statemen  Syntax: def fun_name(Parameter1,Parameter2…Parameter n): statement1 statement2… statement n return[expression]
  • 9. Function Calling  Once we have defined a function, we can call it from another function, program or even the Python prompt.  To call a function we simply type the function name with appropriatearguments.  Example: x=5 y=4 my_add(x,y)
  • 10. Flow of Execution  The order in which statements are executed is called the flow of execution  Execution always begins at the first statement of the program.  Statements are executed one at a time, in order, from top to bottom.  Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.  Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the flow jumps to the first line of the called function, executes all the statements there, and then comes back to pick up where it left off.
  • 11. Function Prototypes  Function without arguments and without return type  Function with arguments and without return type  Function without arguments and with return type  Function with arguments and with return type
  • 12. Function Arguments  You can call a function by using the following types of formal arguments −  Required arguments  Keyword arguments  Default arguments  Variable-length arguments
  • 13. Function without arguments and without return type  In this type no argument is passed through the function call and no output is return to main function  The sub function will read the input values perform the operation and print the result in the same block
  • 14. Error and Exception  An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions.  When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits
  • 15. Python Built-in Exceptions  Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur.  AttributeError Raised when attribute assignment or reference fails.  EOFError : Raised when the input() functions hits end-of-file condition.  FloatingPointError : Raised when a floating point operation fails.  GeneratorExit : Raise when a generator's close() method is called.  OverflowError : Raised when result of an arithmetic operation is too large to be represented.  ReferenceError : Raised when a weak reference proxy is used to access a garbage collected referent.  RuntimeError : Raised when an error does not fall under any other category.
  • 16. Exception Handling  To handle the exception, python use below keywords  try  except  else  finally  raise
  • 17.  The try: block contains one or more statements which are likely to encounter an exception. If the statements in this block are executed without an exception, the subsequent except: block is skipped.  Except : this code is only executed if an exception occured in the try block. The except block is required with a try block, even if it contains only the pass statement.  else: Code in the else block is only executed if no exceptions were raised in the try block.  finally: The code in the finally block is always executed, regardless of if a an exception was raised or not.
  • 18. Catching Exceptions in Python try: x=int(input(“Enter value of x:”)) y=int(input(“Enter value of y:”)) z=x/y print(z) except ZeroDivisionError: print('Divided by zero') print('Should reach here')
  • 19. Catching Generic Exceptions in Python try: x=int(input(“Enter value of x:”)) y=int(input(“Enter value of y:”)) z=x/y print(z) except : print('Divided by zero') print('Should reach here')
  • 20. try else try: x = 1 except: print('Failed to set x') else: print('No exception occurred') finally: print('We always do this')
  • 21. raise x = 110 try: if x < 0: raise Exception("Sorry, no numbers below zero") except Exception as ex: print(ex.args) else: print("value of X:",x)
  • 22. Comprehensions in Python  Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.)  using sequences which have been already defined.  Python supports the following 4 types of comprehensions  List Comprehensions  Dictionary Comprehensions  Set Comprehensions  Generator Comprehensions
  • 23. List Comprehensions  List Comprehensions provide an stylish way to create new lists  Syntax  output_list = [output_exp for var in input_list if (var satisfies this condition)]
  • 24. input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] output_list = [] for var in input_list: if var % 2 == 0: output_list.append(var) print("Output List using for loop:", output_list)
  • 25. input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] list_using_comp = [var for var in input_list if var % 2 == 0] print("Output List using list comprehensions:", list_using_comp)
  • 26. list_using_comp = [var**2 for var in range(1, 10)] print("Output List using list comprehension:", list_using_comp)
  • 27. Dictionary Comprehensions  we can also create a dictionary using dictionary comprehensions  output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}
  • 28. input_list = [1, 2, 3, 4, 5, 6, 7] output_dict = {} for var in input_list: if var % 2 != 0: output_dict[var] = var**3 print("Output Dictionary using for loop:", output_dict )
  • 29. input_list = [1,2,3,4,5,6,7] dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0} print("Output Dictionary using dictionary comprehensions:", dict_using_comp)
  • 30. state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] output_dict = {} for (key, value) in zip(state, capital): output_dict[key] = value print("Output Dictionary using for loop:", output_dict) Note : Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers
  • 31. state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] dict_using_comp = {key:value for (key, value) in zip(state, capital)} print("Output Dictionary using dictionary comprehensions:", dict_using_comp)
  • 32. Set Comprehensions  Set comprehensions are similar to list comprehensions.  The only difference between them is that set comprehensions use curly brackets { }
  • 33. input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] output_set = set() for var in input_list: if var % 2 == 0: output_set.add(var) print("Output Set using for loop:", output_set)
  • 34. input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] set_using_comp = {var for var in input_list if var % 2 == 0} print("Output Set using set comprehensions:", set_using_comp)
  • 35. Generator Comprehensions  Generator Comprehensions are very similar to list comprehensions.  One difference between them is that generator comprehensions use circular brackets whereas list comprehensions use square brackets  The major difference between them is that generators don’t allocate memory for the whole list
  • 36. input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] output_gen = (var for var in input_list if var % 2 == 0) print("Output values using generator comprehensions:", end = ' ') for var in output_gen: print(var, end = ' ')
  • 38.  Iteration is the idea of repeating some process over a sequence of items. In Python, iteration is usually related to the for loop.  An iterable is an object that supports iteration.
  • 39. Eager evaluation  As soon as call fun(), The Expression is evaluated and return resulted value
  • 40. Lazy evaluation  The Main idea behind lazy evaluation is to evaluate expression only when needed
  • 41. Iterator  An iterator is an object which contains a countable number of values and it is used to iterate over iterable objects like list, tuples, sets, etc  It follows lazy evaluation where the evaluation of the expression will be on hold and stored in the memory until the item is called specifically which helps us to avoid repeated evaluation  Using an iterator-  iter() keyword is used to create an iterator containing an iterable object.  next() keyword is used to call the next element in the iterable object.
  • 42.
  • 43. Generators  Generators simplifies creation of iterators.  A generator is a function that produces a sequence of results instead of a single value.  Generators are iterables
  • 44.
  • 45. Sorting  Python sorted() function returns a sorted list from the iterable object.  Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence.  Syntax: sorted(iterable, key, reverse)  Iterable : sequence (list, tuple, string) or collection (dictionary, set) or any other iterator that needs to be sorted.  Key(optional) : A function that would server as a key or a basis of sort comparison.  Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.  X=sorted(list)
  • 46. Python sorted() key  sorted() function has an optional parameter called ‘key’ which takes a function as its value  For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len function as key, then the strings would be passed to len, and the value it returns, i.e. the length of strings will be sorted
  • 47. L = ["cccc", "b", "dd", "aaa"] print("Normal sort :", sorted(L)) print("Sort with len :", sorted(L, key=len))
  • 50.  Python can generate such random numbers by using the random module  function random(), which generates a random float number between 0.0 and 1.0  Methods:  Random() :which generates a random float number between 0.0 and 1.0  Choice(list/tuple) : The choice() is an inbuilt function in the Python programming language that returns a random item from a list, tuple, or string  randrange(beg, end, step) : function that can generate random numbers from a specified range  randint(beg,end) : method generates a integer between a given range of numbers  sample(range,no.of_numbers) : to directly generate a list of random numbers  Ex: random.sample(range(10,50),5)
  • 51.  Seed(int): The seed function is used to save the state of a random function so that it can generate some random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value)  shuffle() Takes a sequence and returns the sequence in a random order  random.shuffle(mylist)
  • 52. Regular Expressions  A Regular Expressions (RegEx) is a special sequence of characters that uses a search pattern to find a string or set of strings.  It can detect the presence or absence of a text by matching it with a particular pattern, and also can split a pattern into one or more sub-patterns.  Python provides a re module that supports the use of regex in Python
  • 53. MetaCharacters Metacharacters Description [ ] Represent a character class ^ Matches the beginning $ Matches the end . Matches any character except newline | Means OR (Matches with any of the characters separated by it. ? Matches zero or one occurrence * Any number of occurrences (including 0 occurrences) + One or more occurrences
  • 54.
  • 55. Special Sequences  Special sequences do not match for the actual character in the string instead it tells the specific location in the search string where the match must occur
  • 56. Special Sequence Description d Matches any decimal digit, this is equivalent to the set class [0-9] D Matches any non-digit character, this is equivalent to the set class [^0-9] w Matches any alphanumeric character, this is equivalent to the class [a-zA-Z0-9_]. W Matches any non-alphanumeric character.
  • 57. findall()  Return all non-overlapping matches of pattern in string, as a list of strings
  • 58.
  • 59. compile()  Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions
  • 60.
  • 61. split()  Split string by the occurrences of a character or a pattern  re.split(pattern, string, maxsplit=0, flags=0)  The First parameter, pattern denotes the regular expression  string is the given string in which pattern will be searched for and in which splitting occurs  maxsplit if not provided is considered to be zero ‘0’, and if any nonzero value is provided, then at most that many splits occur.  If maxsplit = 1, then the string will split once only, resulting in a list of length 2.  The flags are very useful and can help to shorten code, they are not necessary parameters, eg: flags = re.IGNORECASE, in this split, the case, i.e. the lowercase or the uppercase will be ignored
  • 62.
  • 63. sub()  The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string and upon finding the substring pattern is replaced by repl, count checks and maintains the number of times this occurs  Syntax:  re.sub(pattern, repl, string, count=0, flags=0)
  • 64.
  • 66.  object-oriented Programming (OOPs) is a programming model that uses objects and classes in programming.  It aims to implement real-world entities like inheritance, polymorphisms, encapsulation  The main concept of OOPs is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data
  • 67. Concepts of Object-Oriented Programming  Class  Objects  Polymorphism  Encapsulation  Inheritance  Data Abstraction
  • 68. Class  A class is a collection of objects  It is a logical entity that contains some attributes and methods  Syntax: class ClassName: # Statement-1 . . . # Statement-N  Classes are created by keyword class.  Attributes are the variables that belong to a class.  Attributes are always public and can be accessed using the dot (.) operator
  • 69. Creating an empty Class in Python class Student: pass
  • 70. Objects  The object is an entity that has a state and behavior associated with it  An object consists of :  State: It is represented by the attributes of an object. It also reflects the properties of an object.  Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.  Identity: It gives a unique name to an object and enables one object to interact with other objects.  Syntax: Obj = Student()
  • 71. __init__ method  The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated
  • 72. Inheritance  Inheritance is the capability of one class to derive or inherit the properties from another class  The existing class is called base class or parent class or super class  Newly created class is called derived class or child class or sub class  Types of inheritances  Single Inheritance  Multilevel Inheritance  Hierarchical Inheritance  Multiple Inheritance
  • 73. Polymorphism  Polymorphism is an object-oriented programming concept that allows us to perform a single action in different ways
  • 74. Encapsulation  Encapsulation is one of the fundamental concepts in object-oriented programming (OOP).  It describes the idea of wrapping data and the methods that work on data within one unit
  • 75. enumerate  Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method.  Syntax:  enumerate(iterable, start=0)  Parameters:  Iterable: any object that supports iteration  Start: the index value from which the counter is to be started, by default it is 0