2. Python Overview
• Unique and simple interpreted language
• High level data structures
• Developers can use for RAD
• Connects existing components – glue language
3. Introduction
Python is a
• high-level language
• Interpreted language
• Interactive language
• object-oriented scripting language.
• Python is designed to be highly readable.
• It uses English keywords frequently whereas the other
languages use punctuations.
• It has fewer syntactical constructions than other
languages.
4. Advantages and Disadvantages
• Clearly defined syntax
• Own IDLE
• Most appropriate for
mathematical problem
solving
• Slow in speed
• Weak in mobile
computing
• Requires more testing
time
5. Why Python is preferred?
• Python is Interpreted
• Python is Interactive
• Python is Object-Oriented
• Python is a Beginner's Language
6. Why Python
Easy to read Python scripts have clear syntax, simple structure and very few
protocols to remember before programming.
Easy to Maintain Python code is easily to write and debug. Python's success is that its source code is fairly
easy-to-maintain.
Portable Python can run on a wide variety of Operating systems and platforms and providing the
similar interface on all platforms.
Broad Standard Libraries Python comes with many prebuilt libraries apx. 21K
High Level programming Python is intended to make complex programming simpler. Python deals with
memory addresses, garbage collection etc internally.
Interactive Python provide an interactive shell to test the things before implementation. It
provide the user the direct interface with Python.
Database Interfaces Python provides interfaces to all major commercial databases. These interfaces
are pretty easy to use.
GUI programming Python supports GUI applications and has framework for Web.Interface to
tkinter, WXPython, DJango in Python make it .
7. History of Python
Python was conceptualized by Guido Van Rossum in
the late 1980s.
Rossum published the first version of Python code
(0.9.0) in February 1991 at the CWI (Centrum Wiskunde
& Informatica) in the Netherlands , Amsterdam.
Python is derived from ABC programming language,
which is a general-purpose programming language that
had been developed at the CWI.
Rossum chose the name "Python", since he was a big
fan of Monty Python's Flying Circus.
Python is now maintained by a core development team
at the institute, although Rossum still holds a vital role
in directing its progress.
8. Python Versions
Release dates for the major and minor versions:
Python 1.0 - January 1994
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000
Python 2.0 - October 16, 2000
Python 2.1 - April 17, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
9. Python Versions
Release dates for the major and minor versions:
Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python 3.6 – December 23, 2016
Python 3.7 – June 27, 2018
Python 3.8 – October 14, 2019
Python 3.8.5 – July 20, 2020
10. Python Versions
Python 3.8.6 - September 8, 2020
Python 3.9 - September 24, 2020
Python 3.9.1 - October 5, 2020
.
.
.
Python 3.10.6 - August 2, 2022
16. The Magic of Python
When you start Python, you will see something like:
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19)
[MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more
information.
>>>
17. The Magic of Python
• The “>>>” is a Python prompt indicating that
Python is ready for us to give it a command. These
commands are called statements.
• Commands can be like
Print(“Hello World”)
2 + 3
2 / 3
5 – 2
2 * 3
18. Inside a Python Program
# File: chaos.py
# A simple program illustrating chaotic behavior
• Lines that start with # are called comments
• Intended for human readers and ignored by Python
• Python skips text from # to end of line
19. Basic Syntax
• The Python language has many similarities to Perl,
C, and Java.
• However, there are some definite differences
between the languages.
Mode of Execution
Interactive Mode Programming
- Direct Mode
Script Mode Programming
- File Mode
20. Python Identifiers
• We can use a sequence of letters [lowercase (a to z) or
uppercase (A to Z)], and we can also mix up digits (0 to
9) or an underscore (_) while defining an identifier.
• We can’t use digits to begin an identifier’s name.
• We should not use Reserved Keywords to define an
identifier.
• Other than underscore (_), we are not allowed to use
any other special characters.
• Even though python doc says that we can name an
identifier with unlimited length, it is not entirely true.
Using a large name (more than 79 chars) would lead to
the violation of a rule set by the PEP8(Python
Enhancement Proposal) standard.
21. Python Identifiers
• A Python identifier is a name used to identify a
variable, function, class, module or other object.
• An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
• Python does not allow punctuation characters such
as @, $, and % within identifiers.
• Python is a case sensitive programming language.
• Thus, Manpower and manpower are two different
identifiers in Python.
22. Here are naming conventions for Python identifiers-
• Class names start with an uppercase letter. All
other identifiers start with a lowercase letter.
• Starting an identifier with a single leading
underscore indicates that the identifier is private.
• Starting an identifier with two leading underscores
indicates a strong private identifier.
• If the identifier also ends with two trailing
underscores, the identifier is a language defined
special name.
23. Reserved Words
• The following list shows the Python keywords.
• These are reserved words and you cannot use
them as constants or variables or any other
identifier names.
• All the Python keywords contain lowercase letters
only.
24.
25. Data Types in Python
• To understand how data is stored and manipulated in
that language.
• ease of use and the number of versatile features it
provides.
• /* C code block */ /* Python Code Block */
• int sum = 0
• for (int i=0;i<10;i++)
• {
• sum += i;
• }
26. Standard Data Types in Python
• a data type is the classification of the type of values
that can be assigned to variables.
• To understand the different types of values that can
be assigned to variables in Python.
Python data types are categorized into two as
follows:
• Mutable Data Types: Data types in python where
the value assigned to a variable can be changed
• Immutable Data Types: Data types in python
where the value assigned to a variable cannot be
changed
27.
28. • Numbers: The number data type in Python is used
to store numerical values. It is used to carry out the
normal mathematical operations.
• Strings: Strings in Python are used to store textual
information. They are used to carry out operations
that perform positional ordering among items.
• Lists: The list data type is the most generic Python
data type. Lists can consist of a collection of mixed
data types, stored by relative positions.
29. • Tuples: Tuples are one among the immutable
Python data types that can store values of mixed
data types. They are basically a list that cannot be
changed.
• Sets: Sets in Python are a data type that can be
considered as an unordered collection of data
without any duplicate items.
• Dictionaries: Dictionaries in Python can store
multiple objects, but unlike lists, in dictionaries, the
objects are stored by keys and not by positions.
30. What Is a Variable in Python?
• A variable is a memory address that can change,
and when the memory address cannot change then
that variable is known as a constant.
• Variable is a name of the memory location where
data is stored.
• Once a variable is stored, the space is allocated in
memory.
• It defines a variable using a combination of
numbers, letters, and the underscore character.
31. Creating and Declaring Python
Variables
• Python does not have a specific command just to
declare or create a variable;
• there are some rules that we need to keep in mind
while creating Python variables.
• Name of a variable cannot start with a number. It
should start with either an alphabet or the underscore
character.
• Variable names are always case sensitive and can
contain alphanumeric characters and the underscore
character.
• Reserved words cannot be used as variable names.
• Python Variables are always assigned using the equal to
sign followed by the value of the variable.
32. Example:
• a = 10
• b = “Intellipaat”
• print (a) # a is an int type variable because it has an
int value in it
• print (b) # b is a string type variable as it has a
string value in it
33. Multiple Variable Assignment
• We can assign a single value to multiple variables as follows:
• a = b = c = 5
• Also, we can assign multiple values to multiple variables as
follows:
• a, b, c = 2, 25, ‘abc’
• Note: Python is a type inferred language, i.e., it automatically
detects the type of the assigned variable.
• Example 1:
• test=1
• type(test)
• Output:
• int
35. Re-declaring a Variable in Python
• After we have declared a variable, we can again
declare it and assign a new value to it.
• Python interpreter discards the old value and only
considers the new value.
• The type of the new value can be different than the
type of the old value.
Example:
• a = 1
• print (a)
• a = ‘intellipaat’
• print(a)
36. Local Variables in Python
• A variable that is declared inside a python function or a Example:
• a=100
• print (f)
• def some_function()
• f = ‘Intellipaat’
• print(f)
• some_function()
• print(f)module can only be used in that specific function or Python Module.
• This kind of variable is known as a local variable.
• Python interpreter will not recognize that variable outside that specific function
or module
• It will throw an error if that variable is not declared outside of that function.
38. Global Variables In Python
• global variable in Python is a variable that can be used globally
anywhere in the program.
• It can be used in any function or module, and even outside the
functions, without having to re-declare it.
Example:
• a = 100
• print (a)
• def som_function():
• global a
• print (a)
• a = ‘Intellipaat’
• some_function()
• print (a)
39. Deleting Python Variables
• Python provides a feature to delete a variable when it is
not in use so as to free up space.
• Using the command del ‘variable name’, we can delete
any specific variable.
Example:
• a = 10
• print (a)
• del a
• print (a)
40. Concatenating Python Variables
• We can concatenate Python variables of different
data types
Example:
• a = ‘Intellipaat’
• b = 100
• print a+b
Example:
• a = ‘Intellipaat’
• b = 100
• print(a + str(b))
41. Constants
• A constant is a type of variable that holds values, which
cannot be changed.
Example:
• #Declare constants in a separate file called constant.py
• PI = 3.14
• GRAVITY = 9.8
• Then, they are imported to the main file.
• #inside main.py we import the constants
• import constant
• print(constant.PI)
• print(constant.GRAVITY)
42. Numbers in Python
• the number data type is used to store numeric
values.
• immutable data type.
• Being an immutable data type means that if we
change the value of an already allocated number
data type, then that would result in a newly
allocated object.
43. Categories of Number Data Type
• The number data type is further categorized based
on the type of numeric value that can be stored in
it
The number data type is divided into the following
five data types:
• Integer
• Long Integer
• Octal and Hexadecimal
• Floating-point Numbers
• Complex Numbers
44. Integers in Python
• Python integers are nothing but whole numbers
• Integers can be of different types such as positive,
negative, zero, and long.
• Example:
• I = 123 #Positive Integer
• J = -20 #Negative Integer
• K = 0 #Zero Integer
• Long Integers
• L suffix is used for the representation of long
integers.
• I = 99999999999L
45. Octal and Hexadecimal in Python
• another number data type called octal and hexadecimal
numbers.
• To represent the octal number which has base 8 in
Python, add a preceding 0 (zero) so that the Python
interpreter can recognize that we want the value to be
in base 8 and not in base 10.
Example:
• I = 11
• #Then in Octal we will write –
• I = 011
• print (I)
46. • To represent the hexadecimal number (base 16) in
Python, add a preceding 0x so that the interpreter
can recognize that we want the value to be in base
16 and not in base 10.
Example:
• I = 0x11
• print (I)
47. Floating-point Numbers in Python
• Floating-point numbers symbolize the real numbers
that are written with a decimal point dividing the
integer and fractional parts.
• Floating-point numbers may also come with
scientific notation with E or e, indicating the power
of 10.
• Example:
• 5.6e2 that means 5.6 * 102.
• I = 2.5
• J = 7.5e4
48. Complex Numbers in Python
• Complex numbers are of the form, ‘a + bj’, where a
is real part floating value and b is the imaginary
part floating value, and j represents the square root
of −1.
• Example:
• 2.5 + 2j
49. Number Type Conversion in
Python
• There are a few built-in Python functions that let us
convert numbers explicitly from one type to
another.
• This process is called coercion.
• The conversion of one type of number to another
becomes essential when performing certain
operations that require parameters of the same
type.
• For example, programmers may need to perform
mathematical operations like addition and
subtraction between values of different number
types such as integer and float.
50. • We can use the following built-in functions to
convert one number type into another:
• int(x), to convert x into an integer value
• long(x), to convert x into a long integer value
• float(x), to convert x into a floating-point number
• complex(x), to convert x into a complex number
where the imaginary part stays 0 and x becomes
the real part
• complex(x,y), to convert x and y to a complex
number where x becomes the real part and y
becomes the imaginary part
51. • Example:
• a = 3.5
• b = 2
• c = -3.5
• a = int(a)
• print (a)
• b = float(b)
• print (b)
• c = int(c)
• print (c)
52. What is a Python String and String
Function in Python?
• Python string is an ordered collection of characters
which is used to represent and store the text-based
information.
• Strings are stored as individual characters in a
contiguous memory location.
• It can be accessed from both directions: forward
and backward.
• Strings are immutable Data Types in Python, which
means that once a string is created, they cannot be
changed.
53. Creating a String in Python
• In Python, strings are created using either single
quotes or double quotes.
• We can also use triple quotes, multi-line strings.
#creating a string with single quotes
• String1 = ‘Intellipaat’
• print (String1)
#creating a string with double quotes
• String2 = “Python tutorial”
• Print (Strings2)
54. Accessing Python String Characters
• In Python, the characters of string can be individually accessed using a
method called indexing.
• Characters can be accessed from both directions: forward and
backward.
• Forward indexing starts form 0, 1, 2….
• backward indexing starts form −1, −2, −3…, where −1 is the last element
in a string, −2 is the second last, and so on.
• We can only use the integer number type for indexing; otherwise, the
TypeError will be raised.
Example:
• String1 = ‘intellipaat’
• print (String1)
• print (String1[0])
• print (String1[1])
• print (String1[-1])
55. Updating or Deleting a String in Python
• strings in Python are immutable and thus updating or
deleting an individual character in a string is not allowed,
• means that changing a particular character in a string is not
supported in Python.
• the whole string can be updated and deleted.
• The whole string is deleted using a built-in ‘del’ keyword.
Example:
• #Python code to update an entire string
• String1 = ‘Intellipaat Python Tutorial’
• print (“original string: “)
• print (String1)String1 = ‘Welcome to Intellipaat’
• print (“Updated String: “)
• print (String1)
57. Python Operators for Strings
• There are three types of operators supported by a
string, which are:
• Basic Operators (+, *)
• Relational Operators (<, ><=, >=, ==, !=)
• Membership Operators (in, not in)
62. List in Python
• Lists are Python’s most flexible ordered collection
object type.
• It can also be referred to as a sequence that is an
ordered collection of objects
Creating a Lists in python
• A list can be created
• putting the value inside the square bracket
• values are separated by commas.
• List_name = [value1, value2, …, value n]
63. Python lists are
• Ordered collections of arbitrary objects
• Accessed by offset
• Arrays of object references
• Of variable length, heterogeneous, and arbitrarily
nestable
• Of the category, mutable sequence
• Data types in which elements are stored in the index
basis with starting index as 0
• Enclosed between square brackets ‘[]’
• Example:
• list1 = [1,2,3,4,5]
• list2 = [“hello”, “Welcome”]
64. Creating Multi-dimensional Lists
in Python
• A list can hold other lists as well which can result in
multi-dimensional lists
One-dimensional Lists in Python:
• init_list = [0]*3
• print(init_list)
• Output:
• [0, 0, 0]
66. Python List Comprehension
• Python List comprehension helps in constructing
lists in a completely natural and easy way.
• List = [1,2,3,4,5]
• List1 = [ i for i in range(5)]
• print(List1)
• Output:
• [0, 1, 2, 3, 4]
67. Complicated Python List Comprehension
Examples
Example 1:
• print ([a+b for a in ‘mug’ for b in ‘lid’])
• Output:
• [‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’]
Example 2:
• list_fruit = [“Apple”,”Mango”,”Banana”,”Avocado”]
• first_letters = [ fruits[0] for fruits in list_fruit ]
• print(first_letters)
• Output:
• [‘A’, ‘M’, ‘B’, ‘A’]
68. List Extension
• Python allows lists to resize in many ways.
• Example:
• two_dim = [[0]*3 for i in range(3)]print(two_dim)
• [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
• two_dim[0][2] = 1
• print(two_dim)
• Output:
• [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
69. extend():
• Alternately, we can do extension by using the
extend() method
• L1 = [‘a’, ‘b’]
• L2 = [‘c’, ‘d’]
• L1.extend(L2)
• print(L1)
• Output:
• [‘a’, ‘b’, ‘c’, ‘d’]
70. append():
• we can append a value to a list by calling the
append() method.
• L1 = [‘a’, ‘b’]
• L2 = [‘c’, ‘d’]
• L1.extend(L2)
• print(L1)
• Output:
• [‘a’, ‘b’, ‘c’, ‘d’]
71. Accessing Lists in Python
• we can use the index number to access items in lists
Example:
• List1 = [1,2,3,4,5]
• Accessing a List Using Reverse Indexing
• To access a list in reverse order, we have to use indexing
from −1, −2…. Here, −1 represents the last item in the
list.
• print(list1[-1])
• print(list1[-3])
• Output:
• 5
• 3
72. Common List Operations in Python
• Slicing Python Lists
• Slicing operation is used to print a list up to a specific range.
• We can use slice operation by including the starting index and ending
index of the range that we want to print separated by a colon
• list1[2:4]
• output:
• [3, 4]
• list1[2:-1]
• output:
• [3, 4]
• list1[:2]
• output:
• [1, 2]
73. Iterating through Python Lists
• Iterating is quite simple in lists.
• list1 = [1,2,3,4,5]
• for element in list1:
• print(element)
• Output:
• 1
• 2
• 3
• 4
• 5
74. Update or Add Elements in a Python List
• We can update a particular item or multiple items of a list
by using the slice operation
• add an element using the append () method
• Example:
• list1[4] = 'number'
• print(list1)
• list1[4:7] = ["Apple","Mango","Banana"]
• print(list1)
• list1.insert(0,33)
• print(list1)
• list1.insert(6,29)
• print(list1)
75. Remove elements from list
• There are three ways of removing elements from
lists
• del keyword
• remove () method
• pop () method
Output:
• [1, 2, 4, 5][1, 2, 3, 5]
• 2
• [1, 3, 4, 5]
77. Remove duplicates from lists in
python
• we can remove duplicates from list
• mylist = ["a", "b", "c", "d", "c"]
• mylist = list(dict.fromkeys(mylist))
output:
• [“a”, “b”,”c”,”d”]
Reverse a list in python
• lst = [10, 11, 12, 13, 14, 15]
• lst.reverse()
• print(lst)
• output:
• [15, 14, 13, 12, 11, 10]
78. Sorting Lists in Python
• Python list implements the sort() method for ordering (in
both ascending and descending order) its elements in place.
• list1.sort()
Sorting in ascending order:
• list1 = [1,3,2,4,5,9,6]
• list1.sort()
• print(list1)
• output:
• [1, 2, 3, 4, 5, 6, 9]
81. • # This program prints Hello, world!
• print('Hello, world!')
82. Example 1: Add Two Numbers
• # This program adds two numbers
• num1 = 1.5
• num2 = 6.3
• # Add two numbers
• sum = num1 + num2
• # Display the sum
• print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
83. Example 2: Add Two Numbers With
User Input
• # Store input numbers
• num1 = input('Enter first number: ')
• num2 = input('Enter second number: ')
• # Add two numbers
• sum = float(num1) + float(num2)
• # Display the sum
• print('The sum of {0} and {1} is {2}'.format(num1,
num2, sum))
84. • # Python Program to calculate the square root
• # Note: change this value for a different result
• num = 8
• # To take the input from the user
• #num = float(input('Enter a number: '))
• num_sqrt = num ** 0.5
• print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
• Run Code
85. s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
• # Python Program to find the area of triangle
• a = 5
• b = 6
• c = 7
• # Uncomment below to take inputs from the user
• # a = float(input('Enter first side: '))
• # b = float(input('Enter second side: '))
• # c = float(input('Enter third side: '))
86. • # calculate the semi-perimeter
• s = (a + b + c) / 2
• # calculate the area
• area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
• print('The area of the triangle is %0.2f' %area)
87. • # Store input numbers:
• num1 = input('Enter first number: ')
• num2 = input('Enter second number: ')
•
• # Add two numbers
• sum = float(num1) + float(num2)
• # Subtract two numbers
• min = float(num1) - float(num2)
• # Multiply two numbers
• mul = float(num1) * float(num2)
• #Divide two numbers
• div = float(num1) / float(num2)
88. • # Display the sum
• print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
•
• # Display the subtraction
• print('The subtraction of {0} and {1} is
{2}'.format(num1, num2, min))
• # Display the multiplication
• print('The multiplication of {0} and {1} is
{2}'.format(num1, num2, mul))
• # Display the division
• print('The division of {0} and {1} is {2}'.format(num1,
num2, div))
89. What is Tuple in Python
• collection of various immutable Python objects
separated by commas
• Tuples are much similar to Python Lists
• In lists we use square brackets while in tuples we
use parentheses
90. Advantages of Tuples in Python over
Lists
• Elements of a tuple cannot be changed once they
are assigned
• Elements of a list can be changed.
• Iteration is faster
• Used for different data types
• List used for similar data types
• Data remains unchanged and write protected
91. Creating a Tuple in Python
• Created using parentheses around the elements in
the tuple
• Elements in the tuple can be of different data types
or of the same data type.
• A tuple in Python can have any number of
elements.
Eg.
• tup1 = (‘Welcome', 'Python', 'tutorial')
• tup2 = 1,2,3,4
• print (tup1)
• print (tup2)
92. Accessing Python Tuple Elements
• Three different ways of accessing elements in a
tuple
1. Indexing
2. Reverse indexing
3. Slice operator.
Indexing of Tuples in Python
tup1 = (‘Welcome', 'Python', 'tutorial')
print (tup1[0])
93. Reverse Indexing of Tuples in Python
tup1 = (‘Welcome', 'Python', 'tutorial')
print (tup1[-1])
Slicing Operator of Tuples in Python
• Extract some elements from the tuple and display them
• we use a colon between the index from where we want
to start slicing and the index till where we want to
perform it.
Eg.
tup3 = (1,2,3,4,5,6)
print(tup3[1:])
print(tup3[2:4])
print(tup3)
94. Performing Operations in Tuples in
Python
Deleting Python Tuple Elements
• Tuple – Immutable data type
• Deleting a particular element is not possible
• Entire tuple can be deleted
Eg.
tup1 = (‘Welcome', 'Python', 'tutorial')
print (tup1)
del tup1
95. Modifying Elements in a Python Tuple
• we can take some portion of an existing tuple and
create a new tuple using the concatenating
operator
tup1 = (‘Welcome', 'Python', 'tutorial')
tup2 = (1,2,3)
tup3 = tup1 + tup2
print (tup3)
96. Set in Python
• A set in Python is mutable, iterable, and does not
have any duplicate elements
• Unordered collection of elements
• Doesn’t index the elements in a particular order
• Usually used to perform some mathematical
functions such as union, intersection, etc
97. Features
• In Python sets, elements don’t have a specific
order.
• Sets in Python can’t have duplicates. Each item is
unique.
• The elements of a set in Python are immutable.
They can’t accept changes once added.
• Python sets allow addition and deletion operations.
98. Instantiate a Set in Python
1. Using commas to separate and curly braces to
group elements
Eg.
myset = {"apple", "banana", "cherry"}
print(myset)
2. Using the in-built set() method with the elements
that we want to add as the parameters
Eg.
myset = set (("apple", "banana", "cherry"))# note the
double round-brackets
print(myset)
99. Python Set operations
Adding Elements to a Set in Python
1. Using the add() method with the element as the
parameter
Eg.
myset = {"apple", "banana", "cherry"}
myset.add("organge")
print(myset)
101. Removing elements from sets in
Python
1. Using the remove() method
Eg.
myset = {"apple", "banana", "cherry"}
myset.remove("banana")
print(myset)
102. 2. Using discard() method
Eg.
myset = {"apple", "banana", "cherry"}
myset.discard("apple")
print(myset)
3. Using pop() method
• pop() will remove the last item of a set.
• We should avoid performing pop() in sets.
104. Printing the Length of a Set in Python
Printing the Length of a Set in Python
myset = {"apple", "banana", "cherry"}
print(len(myset))
105. Emptying a Python Set Completely
1. Using clear() method
Eg.
myset = {"apple", "banana", "cherry"}
myset.clear()
print(myset)
2. Using del() method
Eg.
myset = {"apple", "banana", "cherry"}
del myset
print(myset)
106. 1. Sets Union
• we use “|” operator
• in-built method called union()
Eg.
Set_A = {1,2,3,4,5}
Set_B = {4,5,6,7}
print(Set_A | Set_B)
107. 2. Set Intersection
• we use ‘&’ operator
• in-built Python Function named as intersection()
Eg.
Set_A = {1,2,3,4,5}
Set_B = {4,5,6,7}
print (Set_A & Set_B)
109. Dictionary in Python
• Another unordered collection of elements
• Unlike sets, a dictionary contains keys and values
rather than just elements
• Python dictionaries can also be changed and
modified
• The values in dictionaries are accessed using keys
and not by their positions
• All the keys in a dictionary are mapped to their
respective values.
• The value can be of any data type in Python
110. Create a Dictionary in Python
Rules for creating Python Dictionary
• The keys are separated from their respective values
by a colon (:) between them, and each key–value
pair is separated using commas (,).
• All items are enclosed in curly braces.
• While the values in dictionaries may repeat, the
keys are always unique.
• The value can be of any data type, but the keys
should be of immutable data type, that is, (Python
Strings, Python Numbers, Python Tuples).
112. Access Items in Dictionary in Python
1. Using the key inside square brackets like
use the index inside square brackets.
dict1 =
print(dict1['year’])
2. Using the get() method and passing the
parameter inside this method.
dict1 =
print(dict1.get('year’))
114. Delete Dictionary Elements
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
115.
116.
117. While Loop in Python
• Loops are used when we want to repeat a block of
code a number of times.
• used to repeatedly execute a certain statement as
long as the condition provided in the while loop
statement stays true.
Syntax of While Loop in Python:
while test_expression:
body of while
118. Steps
• The program first evaluates the while loop
condition.
• If it’s true, then the program enters the loop and
executes the body of the while loop.
• It continues to execute the body of the while loop
as long as the condition is true.
• When it is false, the program comes out of the loop
and stops repeating the body of the while loop.
• Ex:
• Simple print statement
119. Infinite Loop
• Refers to a while loop that never becomes false
• Ex:
a = 1
while a == 1:
b = input(“What is your name?”)
print(“Hi”, b, “Welcome to SJC”)
120. Else with the While Loop in
Python
• else statement can be used with while loop in
python
• It will get executed only if the while condition is
false
• ex:
• simple print statement
121. While Loop Interruptions
Break: The break keyword terminates the loop and
transfers the control to the end of the loop.
• Ex
• a = 1
• while a <5:
• a += 1
• if a == 3:
• break
• print(a)
122. Continue: The continue keyword terminates the ongoing iteration and
transfers the control to the top of the loop and the loop condition is
evaluated again.
If the condition is true, then the next iteration takes place.
• Ex:
• a = 1
• while a <5:
• a += 1
• if a == 3:
• continue
• print(a)
123. for loop
• execute the body of for loop for a fixed number of
times
• iteration and incrementing value are controlled by
generating a sequence
• Iterations on the sequences in Python are called
traversals
Syntax of for loop
for a in sequence:
body of for
124.
125. • the loop will continue to execute until the last item
in the sequence is reached.
ex:
to find the square of number in the given sequence
initialization
sequence or list
for loop
computation
print statement
126. The range() Function
• We can specify a particular range using an inbuilt
Python function, named range()
• will iterate the loop a specified number of times
through that range.
syntax
range(10)
range(3,7)
for i in range(10)
print i
127. Loop Interruptions in Python For
Loop
Break Statement
• The break statement will immediately terminate
the execution of the loop
• transfer the control of the program to the end of
the loop
Continue Statement
• terminate the ongoing iteration and transfer the
control to the beginning of the loop to continue the
next iteration
128. Functions in Python
• Functions are used to group together a certain
number of related instructions
• These are reusable blocks of codes written to carry
out a specific task.
• A function might or might not require inputs.
• Functions are only executed when they are
specifically called.
• Depending on the task a function is supposed to
carry out, it might or might not return a value.
129. • much more organized and manageable
• increase the readability of the code along with
providing it reusability
Types of functions
1. Python Built-in functions (an already created, or
predefined, function)
2. User-defined function (a function created by users
as per the requirements)
3. Anonymous function (a function having no name)
130. Defining a Function in Python
• The def keyword is used to start the function definition.
• The def keyword is followed by a function-name which
is followed by parentheses containing the arguments
passed by the user and a colon at the end.
• After adding the colon, the body of the function starts
with an indented block in a new line.
• The return statement sends a result object back to the
caller.
• A return statement with no argument is equivalent to
return none statement.
131. Syntax for writing a function in Python:
• def (arg1, arg2, … argn):
• Return
• Syntax
• def functionname( parameters ):
• "function_docstring“ // short description
• function_suite
• return [expression]
132. Defining a Function
• Ex:
• def printme( str ):
• "This prints a passed string into this function"
• print (str)
• return
• Defining a function
• name
• specifies the parameters
• structures the blocks of code
133. Calling a Function
• # Function definition is here
• def printme( str ):
• "This prints a passed string into this function"
• print (str)
• return
• # Now you can call printme function
• printme("This is first call to the user defined
function!")
• printme("Again second call to the same function")
134. Pass by Reference
• Pass means to provide an argument to a function.
• By reference means that the argument you’re
passing to the function is a reference to a variable
that already exists in memory rather than an
independent copy of that variable.
• all operations performed on this reference will
directly affect the variable to which it refers.
135. Contrasting Pass by Reference and
Pass by Value
• When you pass function arguments by reference,
those arguments are only references to existing
values.
• In contrast, when you pass arguments by value,
those arguments become independent copies of
the original values.
136. Pass by Reference vs Value
• All parameters (arguments) are passed by reference
• if we change what a parameter refers to within a
function, the change also reflects back in the calling
function
137.
138. • # Function definition is here
• def changeme( mylist ):
• "This changes a passed list into this function"
• print ("Values inside the function before change: ",
mylist)
• mylist[2]=50
• print ("Values inside the function after change: ", mylist)
• return
• # Now you can call changeme function
• mylist = [10,20,30]
• changeme( mylist )
• print ("Values outside the function: ", mylist)
139. argument is being passed by reference and the
reference is being overwritten inside the called
function.
• # Function definition is
here
• def changeme( mylist ):
• "This changes a passed
list into this function"
• mylist = [1,2,3,4] # This
would assi new
reference in mylist
• print ("Values inside the
function: ", mylist)
• return
# Now you can call changeme
function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function:
", mylist)
140. Function Arguments
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
1. Required Arguments
• arguments passed to a function in correct
positional order
• arguments in the function call should match exactly
with the function definition
141. • def printme( str ):
• printme() // can’t call the function w/o argument
2. Keyword Arguments
• related to the function calls
• When we use keyword arguments in a function call,
the caller identifies the arguments by the
parameter name
• def printme( str ):
• printme( str = "My string")
142. • Ex:
• # Function definition is here
• def printinfo( name, age ):
• "This prints a passed info into this function"
• print ("Name: ", name)
• print ("Age ", age)
• return
• # Now you can call printinfo function
• printinfo( age=50, name="miki" )
143. 3. Default Arguments
• A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument
• # Function definition is here
• def printinfo( name, age = 35 ):
• "This prints a passed info into this function"
• print ("Name: ", name)
• print ("Age ", age)
• return
• # Now you can call printinfo function
• printinfo( age=50, name="miki" )
• printinfo( name="miki" )
144. 4. Variable-length Arguments
• need to process a function for more arguments
than you specified while defining the function
• are not named in the function definition
• Syntax:
• def functionname([formal_args,] *var_args_tuple ):
• "function_docstring"
• function_suite
• return [expression]
145. • # Function definition is here
• def printinfo( arg1, *vartuple ):
• "This prints a variable passed arguments"
• print ("Output is: ")
• print (arg1)
• for var in vartuple:
• print (var)
• return
• # Now you can call printinfo function
• printinfo( 10 )
• printinfo( 70, 60, 50 )
146. The Anonymous Functions
• These functions are called anonymous because
they are not declared in the standard manner by
using the def keyword
• lambda keyword to create small anonymous
functions
• Lambda forms can take any number of arguments
but return just one value in the form of an
expression
• cannot be a direct call to print because lambda
requires an expression
147. • Syntax:
• lambda[arg1 [,arg2,.....argn]]:expression
• # Function definition is here
• sum = lambda arg1, arg2: arg1 + arg2
• # Now you can call sum as a function
• print ("Value of total : ", sum( 10, 20 ))
• print ("Value of total : ", sum( 20, 20 ))
148. The return Statement
• exits a function
• A return statement with no arguments is the same as return
None
• # Function definition is here
• def sum( arg1, arg2 ):
• # Add both the parameters and return them."
• total = arg1 + arg2
• print ("Inside the function : ", total)
• return total
• # Now you can call sum function
• total = sum( 10, 20 )
• print ("Outside the function : ", total )
149. Modules
• A module allows you to logically organize your
Python code
• Grouping related code into a module makes the
code easier to understand and use
• named attributes that you can bind and reference
• a module is a file consisting of Python code
• A module can define functions, classes and
variables. A module can also include runnable code
150. • Import: Lets a client obtain a module as a whole
• From: Permits a client to fetch particular names
from a module
• Reload: Gives a way to reload a code of module
without stopping Python
151. Ex.
• def print_func( par ):
• print "Hello : ", par
• return
• Python source file as a module by executing an
import statement in some other Python source file
• Syntax:
• import module1, module2 ……module n
• Interpreter – import statement – search path (list of
directories – before importing)
152. Ex
• # Import module support
• import support
• # Now you can call defined function that module as
follows
• support.print_func(“Francis")
• A module is loaded only once, regardless of the
number of times it is imported.
• This prevents the module execution from
happening repeatedly, if multiple imports occur
153. Reloading a module
• The Python interpreter imports a module only once
during a session.
• This makes things more efficient
• # This module shows the effect of
• # multiple imports and reload
• print("This code got executed")
• Now if our module changed during the course of
the program, we would have to reload it.
• One way to do this is to restart the interpreter
154. • We can use the reload() function inside the imp
module to reload a module
• Import imp
• Import my_module
• Imp.reload(my_module)
155. • What does the if __name__ == “__main__”:
• Before executing code, Python interpreter reads
source file and define few special variables/global
variables.
• If the python interpreter is running that module
(the source file) as the main program, it sets the
special __name__ variable to have a value
“__main__”.
• If this file is being imported from another module,
__name__ will be set to the module’s name.
• Module’s name is available as value to __name__
global variable.
156. • # Python program to execute
• # main directly
• print "Always executed"
• if __name__ == "__main__":
• print "Executed when invoked directly"
• else:
• print "Executed when imported"
157. • All of the code that is at indentation level 0 [Block
1] gets executed. Functions and classes that are
defined are well defined, but none of their code
runs.
• Here, as we executed script.py directly __name__
variable will be __main__. So, code in this if
block[Block 2] will only run if that module is the
entry point to your program.
• Thus, you can test whether your script is being run
directly or being imported by something else by
testing __name__ variable.
• If script is getting imported by some other module
at that time __name__ will be module name.
158. The dir() built-in function
• We can use the dir() function to find out names that are
defined inside a module
• Syntax:
• dir(module_name)
• Will get list of names
• Names start with _ are default python attributes
associated with the module
• ex:
• import example
• example _name_ // contains the name of the attribute
159. Python Package
• We don't usually store all of our files on our
computer in the same location.
• We use a well-organized hierarchy of directories for
easier access.
• Similar files are kept in the same directory, for
example, we may keep all the songs in the "music"
directory.
• Analogous to this, Python has packages for
directories and modules for files.
160. • As our application program grows larger in size with
a lot of modules, we place similar modules in one
package and different modules in different
packages.
• This makes a project (program) easy to manage and
conceptually clear
• Similarly, as a directory can contain subdirectories
and files, a Python package can have sub-packages
and modules
161.
162. Importing module from a package
• We can import modules from packages using the
dot (.) operator
• import Game.Level.start
• Now, if this module contains a function named
select_difficulty(), we must use the full name to
reference it.
• Game.Level.start.select_difficulty(2)
163. • If this construct seems lengthy, we can import the
module without the package prefix as follows:
• from Game.Level import start
• We can now call the function simply as follows:
• start.select_difficulty(2)
164. • Another way of importing just the required
function (or class or variable) from a module within
a package would be as follows:
• from Game.Level.start import select_difficulty
• Now we can directly call this function.
• select_difficulty(2)
165. Python - Packages
• We organize a large number of files in different folders
and subfolders based on some criteria
• we can find and manage them easily.
• In the same way, a package in Python takes the concept
of the modular approach to next logical level.
• a module can contain multiple objects, such as classes,
functions, etc.
• A package can contain one or more relevant modules.
• Physically, a package is actually a folder containing one
or more module files.
166. How to create a Package
• Create a new folder named D:MyApp.
• Inside MyApp, create a subfolder with the name
'mypackage'.
• Create an empty __init__.py file in the mypackage
folder.
167. Importing a Module from a
Package
• To test our package, invoke the Python prompt
from the MyApp folder.
• Import the functions module from the mypackage
package and call its power() function.
• It is also possible to import specific functions from
a module in the package
168. __init__.py
• The package folder contains a special file called __init__.py,
which stores the package's content.
It serves two purposes:
• The Python interpreter recognizes a folder as the package if
it contains __init__.py file.
• __init__.py exposes specified resources from its modules to
be imported.
• An empty __init__.py file makes all functions from above
modules available when this package is imported.
Note:
• __init__.py is essential for the folder to be recognized by
Python as a package..
169. • The __init__.py file is normally kept empty.
• However, it can also be used to choose specific
functions from modules in the package folder and
make them available for import.
__init__.py
• from .functions import average, power
• from .greet import SayHello
• The specified functions can now be imported in the
interpreter session or another executable script.
170. Install a Package Globally
• Once a package is created, it can be installed for
system wide use by running the setup script.
• The script calls setup() function from setuptools
module.
• Let's install mypackage for system-wide use by
running a setup script.
171. • Save the following code as setup.py in the parent
folder 'MyApp’.
• The script calls the setup() function from the
setuptools module.
• The setup() function takes various arguments such
as name, version, author, list of dependencies etc.
• The zip_safe argument defines whether the
package is installed in compressed mode or regular
mode.
172. Handling Files I/O
• A location on the disk, which can be used to store
data or information in the memory.
• Handling a file is another kind of input/output
• Common operations:
• Read()
• Write()
• Non Volatile Memory – Hard disk
• Sequence – open, perform an operation (read or write),
close
173. Types of Files
• Windows – User and Operating System can create,
modify or manipulate any item.
• These editable items are referred to as files.
• Python
• Text files
• Binary Files
Text file – A sequence of lines
EOF – terminates each line
Binary file – Any file other than text file is referred to binary
file.
Applications which interpret and read only, can process them.
174. Files I/O
Opening and Closing Files
• reading and writing to the standard input and
output
• how to use actual data files
• basic functions and methods necessary to
manipulate files by default.
• file manipulation using a file object
175. The open Function
• Before we can read or write a file, we have to open
it using Python's built-in open() function.
• This function creates a file object, which would be
utilized to call other support methods associated
with it.
• Syntax
• file object = open(file_name ,[ access_mode],[
buffering])
176. file_name:
• The file_name argument is a string value that contains the name
of the file that you want to access.
access_mode:
The access_mode determines the mode in which the file must be
opened, i.e., read, write, append, etc. This is an optional parameter,
and the default file access mode is read (r).
buffering:
• If the buffering value is set to 0, no buffering takes place.
• If the buffering value is 1, line buffering is performed while
accessing a file.
• If you specify the buffering value as an integer greater than 1,
then buffering action is performed with the indicated buffer size.
• The buffer size is the system default(default behavior), specified
with negative value.
177.
178.
179. The file Object Attributes
• Once a file is opened and you have one file object, you
can get various information related to that file
1. file.closed – returns true if file is closed or false
2. file.mode – returns access mode with which file was
opened
3. file.name – returns name of the file
The close() Method
The close() method of a file object flushes any unwritten
information and closes the file object, after which no
more writing can be done
Syntax
• fileObject.close();
180. Reading and Writing Files
• The file object provides a set of access methods -
read() and write() methods
• The write() Method
• The write() method writes any string to an open
file.
• It is important to note that Python strings can have
binary data and not just text
• The write() method does not add a newline
character ('n') to the end of the string
181. Syntax
• fileObject.write(string);
The read() Method
The read() method reads a string from an open file.
Syntax
fileObject.read([count]);
• Here, passed parameter is the number of bytes to be read
from the opened file.
• This method starts reading from the beginning of the file
• if count is missing, then it tries to read as much as possible,
maybe until the end of file
182. File Positions
• We can check and change the current position of
file object with the help tell(() and seek() function.
• Tell() function – to know the current position in the
file.
• Returns in the form of integer
• Binary mode – no of bytes from beginning of the
file
• Text mode- opaque number
• Syntax:
• Filename.tell()
183. Seek() function
• Current position of the file can be changed
• Indicates the no. of bytes to be moved and point
where the bytes must move
• Syntax:
• Filename.seek(offset,[from])
• Offset – specifies the no of bytes to be moved
• From – indicates the reference position from where
the bytes are to be moved
• 0 – file beginning is used as the reference position
184. • 1 – current file position used as reference position
• 2 – file end used as reference position
• Other file processing operations can be done with
the help of the OS module of python.
• Import OS module
185. Renaming and Deleting Files
• file processing operations such as renaming and
deleting files.
• The rename() Method
• The rename() method takes two arguments, the
current filename and the new filename
• Syntax
• os.rename(current_file_name, new_file_name)
• The remove() Method
• remove() method to delete files by supplying the name
of the file to be deleted as the argument
• Syntax
• os.remove(file_name)
186. Directories in Python
• The mkdir() Method
• to create directories in the current directory
• We need to supply an argument to this method, which
contains the name of the directory to be created
• Syntax
• os.mkdir("newdir")
• The chdir() Method
• chdir() method to change the current directory
• Syntax
• os.chdir("newdir")
187. • The getcwd() Method
• The getcwd() method displays the current working
directory
• Syntax
• os.getcwd()
• The rmdir() Method
• The rmdir() method deletes the directory, which is
passed as an argument in the method.
• Before removing a directory, all the contents in it
should be removed
• Syntax
• os.rmdir('dirname')
188. File & Directory Related Methods
• There are three important sources, which provide a
wide range of utility methods to handle and manipulate
files & directories on Windows and Unix operating
systems.
• They are as follows-
• File Object Methods: The file object provides functions
to manipulate files.
• OS Object Methods: This provides methods to process
files as well as directories
• File Methods
• A file object is created using open function and here is
a list of functions which can be called on this object
189.
190.
191. File close() Method
• The method close() closes the opened file.
• A closed file cannot be read or written anymore.
• Any operation, which requires that the file be
opened will raise a ValueError after the file has
been closed.
• Calling close() more than once is allowed
• Syntax
• fileobject.close()
192. File flush() Method
• The method flush() flushes the internal buffer, like
stdio's fflush
• Python automatically flushes the files when closing
them.
• But you may want to flush the data before closing
any file
• Syntax
• fileobject.flush()
193. File fileno() Method
• The method fileno() returns the integer file
descriptor that is used by the underlying
implementation to request I/O operations from the
operating system.
• Syntax
• fileobject.fileno()
194. File next() Method
• This method can be used to read the next input
line, from the file object
• Syntax
• next(iterator[,default])
• Parameters
• iterator : file object from which lines are to be read
• default : returned if iterator exhausted. If not
given, Stop Iteration is raised
195. OS File/Directory Methods
• The os module provides a big range of useful
methods to manipulate files and directories.
196. Exception Handling
• Python provides two very important features
• to handle any unexpected error in our programs
• to add debugging capabilities in them
• Exception Handling.
• Assertions.
203. Assertions in Python
• An assertion is a check that you can turn on or turn
off when you are done with your testing of the
program.
• The easiest way to think of an assertion is to liken it
to a raise-if statement (or to be more accurate, a
raise-if-not statement).
• An expression is tested, and if the result comes up
false, an exception is raised.
• Programmers often place assertions at the start of
a function to check for valid input, and after a
function call to check for valid output.
204. The assert Statement
• When it encounters an assert statement, Python
evaluates the accompanying expression, which is
hopefully true.
• If the expression is false, Python raises an
AssertionError exception
• Syntax:
• assert Expression[, Arguments]
205. • If the assertion fails, Python uses
ArgumentExpression as the argument for the
AssertionError.
• AssertionError exceptions can be caught and
handled like any other exception, using the try-
except statement.
• If they are not handled, they will terminate the
program and produce a traceback
206. What is Exception?
• 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.
207. Handling an Exception
• Exceptions are handled by the try-except block
• The Suspicious code is placed inside the try block,
where the exception is caught
• Except block is responsible for handling the caught
exception
• Syntax:
• Try:
• <suspicious code>
• Except <Type of exception>:
• <exception handling code>
208. Points to Remember
• A single try statement can have multiple except
statements. This is useful when the try block
contains statements that may throw different types
of exceptions.
• We can also provide a generic except clause, which
handles any exception.
• After the except clause(s), we can include an else-
clause. The code in the else block executes if the
code in the try: block does not raise an exception.
209.
210. • First, the try block is executed
• Case 1:If no Python exception occurs, except blocks
are skipped and the else block gets executed
• Case 2:If a Python exception occurs during the
execution of the try block, the rest of the execution
is stopped. Then, a matching Python exception
handling block is looked for.
• If found: Execute that exception block, and after
the exception in Python is handled, execute the rest
of the try block
• If not found: Stop the whole execution with an
error message
211. Ex:
try:
fh = open("testfile", "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()
212. The except Clause with No
Exceptions
• try:
• You do your operations here
• ......................
• except:
• If there is any exception, then execute this block.
• ......................
• else:
• If there is no exception then execute this block.
• This kind of a try-except statement catches all the
exceptions that occur
213. The except Clause with Multiple
Exceptions
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
214. The try-finally Clause
• You can use a finally: block along with a try: block. The
finally: block is a place to put any code that must
execute, whether the try-block raised an exception or
not.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
215. • You can provide except clause(s), or a finally clause, but
not both.
• You cannot use else clause as well along with a finally
clause
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can't find file or read data")
fh.close()
216. Ex
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can't find file or read data")
217. • When an exception is thrown in the try block, the
execution immediately passes to the finally block.
• After all the statements in the finally block are
executed, the exception is raised again
• It is handled in the except statements if present in
the next higher layer of the try-except statement.
218. Argument of an Exception
• An exception can have an argument, which is a
value that gives additional information about the
problem.
• The contents of the argument vary by exception.
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
219. Raising Exceptions
• Exceptions can be deliberately raised by the
programmer.
• This is useful in situations where programmer
wants the user to enter specific values for a given
input type.
• E.g.
• Game level
• Syntax:
• Raise<Exception name>
220. User defined Exceptions
• We can create our own exception that handle
exceptions specific to a program
221. Classes And Objects – Object
Oriented Programming
• A class in python is the blueprint from which specific
objects are created
• It lets you structure your software in a particular way
• A logical entity that behaves as a prototype or a
template to create objects
• an object is just a collection of variables and Python
functions
• Variables and functions are defined inside the class and
are accessed using objects
• These variables and functions are collectively known as
attributes.
222.
223. • In the first image (A), it represents a blueprint of a
house that can be considered as Class.
• With the same blueprint, we can create several houses
and these can be considered as Objects.
• Class variable is a variable that is shared by all the
different objects/instances of a class.
• Instance variables are variables which are unique to
each instance. It is defined inside a method and
belongs only to the current instance of a class.
• Methods are also called as functions which are defined
in a class and describes the behavior of an object.
224.
225. Defining a Class in Python
• Like a function in Python is defined using the def
keyword, a class in Python is also defined using the
class keyword, followed by the class name.
• As soon as the class is created, a class object is also
created which is used to access the attributes in the
class
• Syntax:
class Class_name:
statement-1
.
.
statement-N
226. • Positional arguments refer to data that is passed into a
function.
• In a class, every function must be given the value “self”.
• “self” represents the data stored in an object of a class.
• When you call a class method without first instantiating an
object of that class, you get an error.
• This is because “self” has no value until an object has been
instantiated.
• The most common mistakes that are made that cause the
“missing 1 required positional argument: ‘self’” error are:
• Forgetting to instantiate an object of a class
• Using the incorrect syntax to instantiate a class
227. Creating an Object in Python
• class object of the same name as the class is used
to access attributes.
• it can also be used to create new objects, and then
those objects can be used to access the attributes
228. Self - parameter
• we are using a parameter named self while defining
the function in the class
• we’re not really passing any value while calling the
function
• when a function is called using an object, the
object itself is passed automatically to the function
as an argument
• object1.function1()
• object1.function1(object1)
229. • The very first argument in the function must be the
object itself, which is conventionally called ‘self’
• It can be named something too, but naming it ‘self’
is a convention.
230. Constructors and Destructors
• Special type of method that is used to initialize instance
variables
• The task of constructors is to initialize(assign values) to
the data members of the class when an object of class
is created
• This special method is called whenever a class is
instantiated ( Even not defined explicitly)
• Responsible for allocating memory
• Hence it is the very first method to be called in a class
• When the programmer explicitly defines a constructor,
it hides the default constructor
231. • Default and parameterized
• It may take arguments or not take arguments
• By default one argument will be taken by the
constructor
232. The _init_() Function in Python
• The __init__ function is a reserved function in
classes in Python which is automatically called
whenever a new object of the class is instantiated
• As a regular function, the init function is also
defined using the def keyword
• According to OOP’s paradigm, these types of
functions are called constructors
• We use constructors to initialize variables.
• We can pass any number of arguments while
creating the class object as per the definition of the
init function
233. • Syntax:
• Class myclass:
• Def __init__(self, parameter list):
• Body of the constructor
234. Destructors
• Called explicitly using del(object)
• If any attempt to made to call the methods, it will
fail.
• Need – Problem with automatic garbage collector
• To ensure destruction of objects take place at
certain stage.
235. Class and Instance Variables
• Class variable – shared among all the instances of
the class
• Instance variable – unique to every instance of the
class that is created
• A class variable is defined outside any class
methods and an instance variable is defined inside
the class methods using ‘self’ keyword.
• Class variables are called by the name of the class
they belong to and instance variables are called by
the name of the instance.
236. Privacy in Python
• Python does not implement strict security
• Access modifiers – that can be defeated
• Python will not forcefully stop the programmer to
get access to a certain method or variable
• A method or an attribute in python is public by
default
• Using a singe underscore before the name of the
attribute or method makes it protected (_)
• Using a double underscore before the name of the
attribute or method makes it private (_)
237. Inheritance
• The capability of one class to use the properties of
some other class is termed as inheritance in OOP.
• The class that derives the properties is called
derived or sub class.
• The class from which the properties are derived is
called a base class or super class.
• Feature – code reusability
• Child or sub class – not only use the code of its
base class but can define its own methods.
241. Single Inheritance
• Only two classes share a parent child relationship
• Many classes may be there – But as far as
inheritance is concerned only two classes will
involve
• E.g.
• Classes A, B, C, D
• A – B , C - D
242. Multilevel Inheritance
• When a class inherits
another class, which in
turn inherits some
other class, it is called
multilevel inheritance
• Each class can be
treated as a level
• Need a minimum of
three classes
• 2 levels – 1 derived
243. Hierarchical Inheritance
• Two or more classes inherit a single base class
• The derived class can further derive their own child
classes, which creates a hierarchy
245. Syntax
• Class base1:
• Class definition
• Class base2:
• Class definition
• Class derived(base1,base2):
• Class definition
246. Hybrid Inheritance
• Hybrid inheritance is a combination of multiple
inheritance and multilevel inheritance.
• The class is derived from the two classes as in the
multiple inheritance.
• However, one of the parent classes is not the base
class. It is a derived class.
• Hybrid Inheritance combines more than one form
of inheritance.
• It is a blend of more than one type of inheritance.
247. Polymorphism
• The word polymorphism is comprised of two Greek
words ‘poly’ which means many and ‘morph’ which
means forms.
• OOPS – it means that a single entity, a method or
an operator, can perform different functions when
used in different situations.
• Eg:
• Human Hands
248. • Likewise in OOP, different situations demand
different functionalities from a single entity.
• method overloading
• method overriding
• constructor overriding
• operator overloading
249. Method Overloading
• When two or more methods in python program
have the same name but different signatures, a
method is said to be overloaded.
• The two or more definitions of the overloaded
method may or may not be the same.
• Python supports method overloading only when a
method belongs to one class is overloaded in
another class.
• It will not support parent child relationship
250. Duck Typing
• The programmer does not need to specify the type
of object while initializing a variable
• The python interpreter resolves the type of objects
at runtime
• No need to explicitly define the object type
251. Resolving method overriding
• Method overriding in inheritance can be resolved
using the super() method
• By calling the base class method directly through
base class name.
253. Operator Overloading
• A single operator can be used to perform multiple
operations
• ‘+’ – can be used to add two numbers
• Can be used to concatenate two strings
• So a single operator is used to add two different
types of operands
• Provide flexibility to the programmer .
• Any operator in python can be overloaded
255. • It is part of the fpectl module.
• The FloatingPointError shouldn't be raised if you
don't explicitly turn it on (fpectl.turnon_sigfpe()).
• usage is discouraged
• Even with FloatingPointErrors turned on, 10/'a' will
never raise one.
• It will always raise a TypeError.
256. • A FloatingPointError will only be raised for
operations that reach the point of actually
performing floating-point math, like 1.0/0.0. 10/'a'
doesn't get that far.