Advance Python Program Unit I and V
Advance Python Program Unit I and V
Raakesh Kumar
1. Introduction
3
What is Python?
4
What is Python?
5
Why Python?
6
History of Python
• Python laid its foundation in the late 1980s. • On December 3, 2008, Python 3.0 (also called
• The implementation of Python was started in "Py3K") was released. It was designed to
December 1989 by Guido Van Rossum at rectify the fundamental flaw of the language.
CWI in Netherland.
• ABC programming language is said to be the
• In February 1991, Guido Van Rossum
predecessor of Python language, which was
published the code (labeled version 0.9.0) to
capable of Exception Handling and interfacing
alt.sources.
with the Amoeba Operating System.
• In 1994, Python 1.0 was released with new
features like lambda, map, filter, and reduce. • The following programming languages
• Python 2.0 added new features such as list
influence Python:
comprehensions, garbage collection • ABC language.
systems. • Modula-3
7
Application of Python
8
Features of Python
9
Advantages of Python
Flavors of Python
Compiled Language Compiled Programming language Compiled Programming Language Interpreted Programming Language
Operator overloading is not supported. Supports Overloading the operator Overloading of the operator is not supported. Overloading of the operator is supported
Multiple inheritance is not supported in C. Allow for both single as well as multiple inheritance options. Java provides partial multiple inheritance Provides both single as well as multiple inheritance
Threads are supported. Threads are not supported on this platform. Multithreading capability is built-in. Multithreading is supported.
A small number of libraries available. Has a small number of library patrons Many concepts, such as UI, are supported by the library. It comes with a large library set that allows it to be used for AI,
data science, and other applications.
Outside of the class, variables and functions are utilized. Outside of the class, variables and functions are utilized. Every line of code is contained within a class. Functions and variables can be declared global.
Have a similar speed as C++ C++ is a computer language that compiles quickly. The Java Program Compiler is a little slower than the C++ Execution is delayed due to the employment of an interpreter.
Compiler.
Syntax rules are strictly followed. Syntax rules are strictly followed. Syntax rules are strictly followed. It isn't necessary to use semicolon ' ;'.
2. Python Installation
14
• Step 2) After clicking on Download Click • Step 3) After Click on Next , You need to choose the
on Next destination folder according to your choice.
18
• Step 4) Choose options of installation according to • Step 5) Choose JetBrains and Click on “Install”.
your choice.
19
Installation of Python
www.python.org/download
https://www.anaconda.com/products/individual
https://www.datacamp.com/community/tutorials/
installing-anaconda-windows#after
https://www.datacamp.com/community/tutorials/
tutorial-jupyter-notebook
24
• Begin with the installation process: • Getting through the License Agreement:
• Getting Started:
26
What is Conda?
What is Conda?
What is Conda?
• Jupyter Features:
• Exploratory Data Analysis (EDA)
• Jupyter Notebook is Language-
Independent.
• Live Interactions with Code.
• Easy Caching in Built-in Cell.
• Data Visualization.
• Jupyter Notebook Helps Document Code
Samples.
34
Spyder IDE
by and for scientists, engineers and • Running code. Run file. Run line/selection. ...
• Code navigation. Find and replace. Go to line. ...
data analysts.
• Code analysis and completions. Code completion. Linting
and code style. ...
• Keyboard shortcuts.
• Related panes.
3.Python Operation
36
• In Python, there are two primary modes of execution: • Use the command prompt in Windows, terminal in Linux,
interactive mode and script mode. Let’s explore each or macOS.
of them: • Type python to start the interactive mode.
• Interactive Mode: • Enter Python statements directly at the >>> prompt.
• Interactive mode allows you to run Python code •Example 1:
interactively, line by line. Python
>>> print("Hello GFG")
• When you enter a command and press enter, you .
Python Datatypes
• In Python, data types play a crucial role in how • Complex Numbers (complex): In the form a + bj, where
variables store and handle different kinds of values. a and b are real numbers.
Let’s explore the built-in data types: • Example: 1 + 2j
• Text Type (String): Represents sequences of • Sequence Types:
characters. You can create strings using single or
double quotes.
• List (list): Ordered, mutable collections of items.
• Numeric Types:
• Tuple (tuple): Ordered, immutable collections of items.
Python Datatypes
Python Constants
dedicated syntax for defining constants, you can follow • Assign values that won’t change.
these practices: • Example:
• Naming Convention: • Python
• Use uppercase letters for constant names (e.g., PI, • MY_CONSTANT = 42
MAX_VALUE).
• Strict Constants:
• This convention signals that a variable should not be
• To enforce strict immutability:
reassigned.
• Built-in Constants:
• Use @property decorator.
Python Variables
Comments in Python
• In Python, comments serve several purposes: • Multiline Comments: Python doesn’t have a dedicated syntax
• Single-Line Comments: Start with a # symbol and for multiline comments, but you can use either:
extend to the end of the line. They explain code, • Multiple # symbols for each line:
improve readability, or prevent execution during
testing.
• # This is a comment
• For example:
• # written in
• # This is a comment
• # more than one line
• print("Hello, World!")
• print("Hello, World!")
Print() in Python
• The print() function in Python is used to display • Multiple Calls: Use print() multiple times to add
messages or values to the screen. Here are some vertical space:
key points: • Example
• Basic Usage: To print a blank line, simply call print() • print("Line 1")
without any arguments:
• Example
• print("Line 2")
• print()
• Adding Text: You can pass a string or other objects
to print():
• Example
• print("Hello, World!")
46
• In Python, type conversion refers to changing an • Explicit Type Conversion (Type Casting): The user
object from one data type to another. There are manually changes the data type using specific
two main types of type conversion: functions. Examples include:
• Implicit Type Conversion: The Python interpreter • Converting a string to an integer using int(s, base)
automatically converts data types without user
intervention.
• Converting any data type to a floating-point number
using float()
• Example: • Using ord(), hex(), and oct() for character-to-integer,
• x = 10 integer-to-hexadecimal, and integer-to-octal
• y = 10.6 conversions, respectively.
Escape Sequence
• Python uses the backslash character, \, called an escape sequence in strings, to allow for the
insertion of any type of quote inside of strings.
50
Escape Sequence
Escape Sequence
• Newline (\n): Represents a line break. Use it to split text into multiple lines:
• print("Line 1\\nLine 2")
• Tab (\t): Inserts a horizontal tab (equivalent to pressing the Tab key):
• print("Column 1\\tColumn 2")
• Carriage Return (\r): Moves the cursor to the beginning of the line:
• print("Hello,\\rWorld!")
• Backspace (\b): Removes the character before the backspace:
• print("Backspace: Hello\\bWorld!")
• Form Feed (\f): Used for formatting (less common):
• print("Before\\fAfter")
52
Escape Sequence
• Octal and Hexadecimal Escape Sequences: Represent characters using their octal or
hexadecimal values:
• Octal: \\ooo (e.g., \\141 for lowercase ‘a’)
• Hexadecimal: \\xhh (e.g., \\x61 for lowercase ‘a’)
53
Casting
• We can easily convert between numbers and strings using the appropriate type
4.Python Operators
55
Arithmetic Operator
Assignment Operator
• Assignment Operators:
• Comparison Operators:
• Assign values to variables:
• Compare two values:
• = (Assignment)
• == (Equal)
• +=, -= (Addition/subtraction
• != (Not equal)
assignment)
• >, <, >=, <= (Greater than, less than,
• *=, /=, %=
greater than or equal to, less than or
(Multiplication/division/modulus
equal to)
assignment)
• **=, //= (Exponentiation/floor division
assignment)
57
Comparison Operator
58
Logical Operators
• Logical Operators:
• Combine conditional statements:
• and (Logical AND)
• or (Logical OR)
• not (Logical NOT)
59
Logical Operators
Identity Operator
• Identity Operators:
• Compare objects based on memory location:
• is (True if both variables refer to the same
object)
• is not (True if both variables refer to different
objects)
61
Membership Operators
• Membership Operators:
• Test if a sequence is present in an object:
• in (True if a value is present)
• not in (True if a value is not present)
62
Bitwise Operators
• Bitwise Operators:
• Compare binary numbers:
• & (AND)
• | (OR)
• ^ (XOR)
• ~ (NOT)
• << (Zero fill left shift)
• >> (Signed right shift)
63
Indentation
Conditionals
If Syntax
67
If elif Statement
Infinite Loop
break
For loop
For loop
73
Continue
Continue
6.Strings in Python
lList,tuples,set and dictionary
76
Strings in Python
• In Python, a string is a sequence of characters. You can create strings by enclosing characters in either
single quotes (') or double quotes ("). For example, "hello" and 'world' are both strings1. Here are some
key points about strings in Python:
• String Literals:
• You can display a string literal using the print() function:
• Example:
• print("Hello")
• print('World')
• Quotes Inside Strings:
• You can use quotes inside a string as long as they don’t match the surrounding quotes:
• print("It's alright")
• print('He is called "Johnny"')
77
Strings in Python
Strings in Python
String Indexing
• The character value of Patrick and the corresponding index count is show below:
Character P A T R I C K
Value
Index count 0 1 2 3 4 5 6
80
String Indexing
• Now, try adding a -1 as the index value and observe the output:
81
String Indexing
• The index is a numerical representation of where each character is located. The first character is
at index 0, the second character is at index 1; the third character is at index 2, and so on.
82
String Slicing
• A slice is a subset of a string or other element. A slice could be the whole element or one
character, but it's more commonly a group of adjoining characters.
83
Comparing String
• when comparing two words, the word that comes later in the dictionary is considered greater
than the word that comes before.
84
• Splitting Strings:
• The .split() method breaks a string into a list of substrings based on a specified separator.
• Example:
• a = "this is a string"
• a = a.split(" ") # Converts 'a' to a list of strings
• print(a) # Output: ['this', 'is', 'a', 'string']
• Joining Strings:
• The .join() method combines a list of strings into a single string with a specified separator.
• Example:
• a = "-".join(a) # Joins the list using '-'
• print(a) # Output: 'this-is-a-string'
85
• In Python, you can find a substring within a string using the find() method. Let’s explore how it
works:
• Using find() to Locate a Substring:
• The find() method returns the lowest index of the specified substring if found in the original
string.
• If the substring is not present, it returns -1.
• Example:
• s = "Johny Johny Yes Papa"
• result = s.find("Johny")
• print(result) # Output: 0
• In this example, the first occurrence of the substring “Johny” starts at index 0 in the string.
86
▪ Lowercase:
▪ The .lower() method converts the entire string to
lowercase.
▪ Example:
▪ name = "BOB STONE"
▪ print(name.lower()) # Output: bob stone
7.Python List
Python Data Structures
91
Python List
Python List
94
Python List
95
Python List
96
Python List
97
Python List
98
List Methods
Characteristics of Lists
Examples
▪ # example
▪ Example
a = [ 1, 2, "Ram", 3.50, "Rahul", 5,
a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
6]
b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
a == b b = [ 1, 2, "Ram", 3.50, "Rahul", 5,
Output: 6]
False a == b
Output:
True
104
List Output
1 [1, 2, 3, 4, 5, 6]
2 [1, 2, 3, 4, 5, 6, 7]
3 [3, 4, 5]
4 [2, 4, 6]
107
Negative Indexing
Negative indexing
print(list[-3:-1])
109
▪ Output:
▪ [1, 2, 3, 4, 5, 6]
▪ [1, 2, 10, 4, 5, 6]
▪ [1, 89, 78, 4, 5, 6]
▪ [1, 89, 78, 4, 5, 25]
112
1. Repetition
2. Concatenation
3. Length
4. Iteration
Code ▪ 12
# iteration of the list ▪ 14
# declaring the list ▪ 16
list1 = [12, 14, 16, 39, 40]
▪ 39
# iterating
for i in list1: ▪ 40
print(i)
117
5. Membership
Membership
▪ Output:
▪ False
▪ False
▪ False
▪ True
▪ True
▪ True
119
Iterating a List
• list = [0,1,2,3,4]
• The remove() function in • print("printing original list: ");
Python can remove an • for i in list:
element from the List. To • print(i,end=" ")
comprehend this idea, look • list.remove(2)
at the example that follows. • print("\nprinting the list after the
removal of first element...")
• for i in list:
• print(i,end=" ")
124
• Output:
• printing original list:
• 01234
• printing the list after the
removal of first element...
• 0134
125
• Max( ) • Output:
• It returns the maximum • 782
element of the list
• # maximum of the list
• list1 = [103, 675, 321, 782, 200]
• # large element in the list
• print(max(list1))
127
▪ Min( ) ▪ Output:
▪ It returns the minimum ▪ 103
element of the list. #
minimum of the list
▪ list1 = [103, 675, 321, 782,
200]
▪ # smallest element in the
list
▪ print(min(list1))
128
Sum of List
▪ list1 = [3,4,5,9,10,12,24]
▪ Example:2- Compose a
▪ sum = 0
program to track down the
amount of the component in ▪ for i in list1:
the rundown. ▪ sum = sum+i
▪ print("The sum is:",sum)
▪ Output:
▪ The sum is: 67
130
Common element
▪ list1 = [1,2,3,4,5,6]
▪ Example: 3- Compose the ▪ list2 = [7,8,9,2,10]
program to find the ▪ for x in list1:
rundowns comprise of ▪ for y in list2:
somewhere around one ▪ if x == y:
normal component. ▪ print("The common element is:",x)
▪ Output:
▪ The common element is: 2
131
Code1
”
132
Hello!
I am Raakesh Kumar
I am here because I love Python.
You can reach me at
info.iwavelabs@gmail.com
or
Group whatsapp.
Python
Raakesh Kumar
8. Python Tuples
3
Python Tuples
Python Tuples
Python Tuples
Python Tuples
Python Tuples
Python Tuples
▪ try:
▪ # Python program to show how to
access tuple elements
▪ print(tuple_[5])
▪ # Creating a tuple
▪ except Exception as e:
Python Tuples
Example: print(e)
# Python program to show how to delete elements of a # Deleting the variable from the global space of the program
Python tuple del tuple_
# Creating a tuple # Trying accessing the tuple after deleting it
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", try:
"Collection", "Objects") Output:
print(tuple_)
# Deleting a particular element of the tuple 'tuple' object does not support
except Exception as e: item deletion
print(e) name 'tuple_' is not defined
14
What is Set?
Creating a set
Example 1
▪ The set can be created by Days = {"Monday", "Tuesday",
enclosing the comma- "Wednesday", "Thursday", "Friday",
separated immutable items "Saturday", "Sunday"}
with the curly braces {}. print(Days)
▪ Python also provides the print(type(Days))
set() method, which can be print("looping through the set elements
used to create the set by the ... ")
passed sequence. for i in Days:
print(i)
22
Creating a set
Output: Tuesday
{'Friday', 'Tuesday', 'Monday', 'Saturday', Monday
'Thursday', 'Sunday', 'Wednesday'} Saturday
<class 'set’> Thursday
looping through the set elements ... Sunday
Friday Wednesday
23
for i in Days:
▪ Monday
▪ Tuesday
print(i) ▪ Sunday
24
add multiple elements to the print("\nlooping through the set elements ... ")
for i in Months:
set. Consider the following print(i)
example.
25
update() method
pop() method
pop() method
clear() Method
▪ Despite the fact that discard() and ▪ On the other hand, if the item to be
remove() method both perform the deleted from the set using remove()
same task, There is one main doesn't exist in the set, the Python will
raise an error.
difference between discard() and
remove().
▪ If the key to be deleted from the set
using discard() doesn't exist in the set,
the Python will not give the error. The
program maintains its control flow.
35
▪ Set can be performed mathematical operation such as ▪ The method returns a new set containing all the different
union, intersection, difference, and symmetric difference. items from all the arguments if more than one set is
▪ Python provides the facility to carry out these operations supplied as an argument.
with operators or methods. We describe these operations ▪ Consider the following example to calculate the union of
as follows. two sets.
▪ Now, we can also make the union of more than two sets
▪ Python also provides the union() method which can also using the union() function, for example:
be used to calculate the union of two sets. Consider the
following example.
▪ Program:
set1 = {1, 2, 3}
▪ Example 2: using union() method
set2 = {2, 3, 4}
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
set3 = {3, 4, 5}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the # Find the common elements between the three
sets sets
▪ Output: common_elements = set1.union(set2, set3)
print(common_elements)
▪ {'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday',
'Sunday', 'Saturday'} Output:
{1, 2, 3, 4, 5}
38
▪ To discover what is common between two or more ▪ Example 1: Using & operator
sets in Python, apply the intersection() function. Days1 = {"Monday","Tuesday", "Wednesday",
▪ Only the items in all sets being compared are "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
included in the final set. One or more sets can also
print(Days1&Days2) #prints the intersection of the
be used as the intersection() function parameters.
two sets
▪ The function returns a copy of the set supplied as
▪ Output:
the lone parameter if there is just one set.
▪ The method returns a new set that only contains the ▪ {'Monday', 'Tuesday'}
elements in all the compared sets if multiple sets ▪ Example 2: Using intersection() method
are supplied as arguments. set1 = {"Devansh","John", "David", "Martin"}
▪ The intersection of two sets can be performed by set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection
the and & operator or the intersection() function.
of the two sets
▪ The intersection of the two sets is given as the set of
▪ Output:
the elements that common in both sets.
▪ {'Martin', 'David'}
39
Set Intersection
▪ We can perform the intersection of more than two sets ▪ The intersection_update() method
at a time. ▪ The intersection_update() method removes the items
▪ For Example: from the original set that are not present in both the sets
▪ Program (all the sets if more than one are specified).
# Create three sets ▪ The intersection_update() method is different from the
set1 = {1, 2, 3} intersection() method since it modifies the original set by
set2 = {2, 3, 4} removing the unwanted items, on the other hand, the
set3 = {3, 4, 5} intersection() method returns a new set.
# Find the common elements between the three sets Example:
common_elements = set1.intersection(set2, set3) a = {"Devansh", "bob", "castle"}
# Print the common elements
b = {"castle", "dude", "emyway"}
print(common_elements) c = {"fuson", "gaurav", "castle"}
Output: {3} a.intersection_update(b, c)
print(a)
▪ Output:
▪ {'castle'}
40
Set comparisons
Python Dictionary
▪ Dictionaries are a useful data structure for ▪ Values can be of any type, including
storing data in Python because they are integer, list, and tuple.
capable of imitating real-world data ▪ A dictionary is, in other words, a group
arrangements where a certain value exists of key-value pairs, where the values
for a given key. can be any Python object.
▪ The data is stored as key-value pairs using ▪ The keys, in contrast, are immutable
a Python dictionary. Python objects, such as strings, tuples,
▪ This data structure is mutable or numbers.
▪ The components of dictionary were made ▪ Dictionary entries are ordered as of
using keys and values. Python version 3.7. In Python 3.6 and
▪ Keys must only have one component. before, dictionaries are generally
unordered.
45
▪ # Creating a Dictionary
▪ Python provides the built-in function ▪ # with dict() method
dict() method which is also used to
create the dictionary.
▪ Dict = dict({1: 'Hcl', 2: 'WIPRO',
3:'Facebook'})
▪ The empty curly braces {} is used to
create empty dictionary.
▪ print("\nCreate Dictionary by using
dict(): ")
▪ # Creating an empty Dictionary
▪ print(Dict)
Dict = {}
▪ Output:
print("Empty Dictionary: ")
print(Dict)
47
▪ Example - 2:
▪ Output Employee = {"Name": "Dev", "Age": 20,
"salary":45000,"Company":"WIPRO"}
Empty Dictionary:
print(type(Employee))
{}
print("printing Employee data .... ")
Dictionary after adding 3 elements:
print(Employee)
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
print("Enter the details of the new employee....");
Dictionary after adding 3 elements: Employee["Name"] = input("Name: ");
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, Employee["Age"] = int(input("Age: "));
33, 24)} Employee["salary"] = int(input("Salary: "));
Updated key value: Employee["Company"] = input("Company:");
{0: 'Peter', 2: 'Joseph', 3: ‘iWaveLabs', print("printing the new data");
'Emp_ages': (20, 33, 24)} print(Employee)
52
▪ print(type(Employee))
▪ print("Deleting the dictionary:
Employee");
▪ print("printing Employee data .... ")
▪ del Employee
▪ print(Employee)
▪ print("Lets try to print it again ");
▪ print("Deleting some of the employee
data")
▪ print(Employee)
54
▪ {'Name': 'David', 'Age': 30, 'salary': ▪ The last print statement in the above
55000, 'Company': 'WIPRO'} code, it raised an error because we tried
to print the Employee dictionary that
▪ Deleting some of the employee data
already deleted.
▪ printing the modified information
▪ {'Age': 30, 'salary': 55000}
▪ Deleting the dictionary: Employee
▪ Lets try to print it again
55
Iterating Dictionary
Iterating Dictionary
▪ Example – 3 ▪ Example 4
#for loop to print the values of the dictionary #for loop to print the items of the dictionary
by using values() method. by using items() method
Employee = {"Name": "John", "Age": 29,
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"WIPRO"}
"salary":25000,"Company":"WIPRO"}
for x in Employee.values():
print(x) for x in Employee.items():
print(x)
▪ Output
John
▪ Output
29 ('Name', 'John')
25000 ('Age', 29)
WIPRO ('salary', 25000)
('Company', 'WIPRO')
58
▪ Example 1:
▪ Salary 25000
▪ any() ▪ all()
▪ Like how it does with lists and tuples, the ▪ Unlike in any() method, all() only returns
any() method returns True indeed if one True if each of the dictionary's keys
dictionary key does have a Boolean contain a True Boolean value.
expression that evaluates to True. ▪ Example:
▪ Example: dict = {1: "Ayan", 2: "Bunny", 3:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
"Ram", 4: "Bheem"} all({1:'',2:'','':''})
any({'':'','':'','3':''}) ▪ Output
▪ Output ▪ False
▪ True
62
▪ sorted() ▪ clear()
▪ Like it does with lists and tuples, the ▪ It is mainly used to delete all the items of
sorted() method returns an ordered the dictionary.
series of the dictionary's keys. The # dictionary methods
ascending sorting has no effect on the dict = {1: "Hcl", 2: "WIPRO", 3:
original Python dictionary. "Facebook", 4: "Amazon", 5: "Flipkart"}
▪ Example: # clear() method
dict = {7: "Ayan", 5: "Bunny", 8: "Ram", dict.clear()
1: "Bheem"} print(dict)
sorted(dict) ▪ Output
▪ Output {}
▪ [ 1, 5, 7, 8]
63
▪ copy() ▪ pop()
▪ It returns a shallow copy of the ▪ It mainly eliminates the element using
dictionary which is created. the defined key.
▪ Example: ▪ Example:
# dictionary methods # dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4:
"Amazon", 5: "Flipkart"}
"Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
# pop() method
print(dict_demo) dict_demo = dict.copy()
x = dict_demo.pop(1)
▪ Output
print(x)
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4:
'Amazon', 5: 'Flipkart'}
▪ Output
▪ {2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
64
▪ popitem() ▪ keys()
▪ removes the most recent key-value ▪ It returns all the keys of the dictionary.
pair entered. ▪ Example:
▪ Example: # dictionary methods
# dictionary methods dict = {1: "Hcl", 2: "WIPRO", 3:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", "Facebook", 4: "Amazon", 5: "Flipkart"}
4: "Amazon", 5: "Flipkart"}
# keys() method
# popitem() method
print(dict_demo.keys())
dict_demo.popitem()
print(dict_demo) ▪ Output
▪ Output ▪ dict_keys([1, 2, 3, 4, 5])
▪ {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
65
▪ items() ▪ get()
▪ It returns all the key-value pairs as a ▪ It is used to get the value specified for the
tuple. passed key.
▪ Example ▪ Example:
# dictionary methods # dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: dict = {1: "Hcl", 2: "WIPRO", 3:
"Amazon", 5: "Flipkart"}
"Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
# get() method
print(dict_demo.items())
print(dict_demo.get(3))
▪ Output
▪ Output
▪ dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3,
'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
▪ Facebook
66
▪ update() ▪ values()
▪ It mainly updates all the dictionary by ▪ It returns all the values of the dictionary
adding the key-value pair of dict2 to this with respect to given input.
dictionary. ▪ Example:
▪ Example: # dictionary methods
# dictionary methods dict = {1: "Hcl", 2: "WIPRO", 3:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4:
"Amazon", 5: "Flipkart"}
"Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method # values() method
dict_demo.update({3: "TCS"}) print(dict_demo.values())
print(dict_demo)
▪ Output
▪ Output
▪ dict_values(['Hcl', 'WIPRO', 'TCS'])
▪ {1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}
11. Python Function
68
Python Function
Python Function
▪ Example1:
▪ Syntax def square( num ):
# An example Python Function return num**2
def function_name( parameters ): # code block object_ = square(6)
print( "The square of the given
▪ Illustration of a User-Defined Function number is: ", object_ )
▪ Function computes the square of the ▪ Output:
number ▪ The square of the given number is: 36
70
Python Function
Python Function
▪ Pass by Reference vs. Pass by Value ▪ # Example Python Code for Pass by Reference vs. Value
reference. '''''''This function will find the square of items in the list'''
squares = [ ]
▪ It shows that if we modify the worth of
for l in item_list:
contention within a capability, the
squares.append( l**2 )
calling capability will similarly mirror
return squares
the change. For instance,
# calling the defined function
my_list = [17, 52, 8];
Output: my_result = square( my_list )
Squares of the list are: [289, 2704, 64]
print( "Squares of the list are: ", my_result )
72
Python Function
▪ 1) Default Arguments
▪ Function Arguments ▪ If we call the function without argument, it
▪ The following are the types of uses the default value:
arguments that we can use to call a ▪ Example 1:
function:
def my_function(country = "Norway"):
▪ Default arguments print("I am from " + country)
▪ Keyword arguments my_function("Sweden")
▪ Required arguments my_function("India")
▪ Variable-length arguments my_function()
my_function("Brazil")
73
Python Function
Python Function
Python Function
Python Functions
Python Functions
Python Function
Python Function
Python Function
Python Functions
▪ Example:
▪ Combine Positional-Only and def my_function(a, b, /, *, c, d):
Keyword-Only
print(a + b + c + d)
▪ You can combine the two argument
types in the same function. my_function(5, 6, c = 7, d = 8)
▪ Any argument before the / , are ▪ Output: 26
positional-only, and any argument
after the *, are keyword-only.
82
Python Functions
Python Functions
Python Functions
Python Functions
▪ Example:
▪ bool() in Python user_input = bool(int(input(“Enter any
▪ Python bool() function is used to number from 0: "))
return or convert a value to a if user_input == True:
Boolean value i.e., True or False, print(" You need to eat some foods ")
using the standard truth testing else:
procedure. print("Let's go for walk")
▪ Output: ▪ Output:
Are you hungry? True or false: False
Let's go for walk
86
Python Function
Python Function
Python Function
▪ Example: Output:
lambda_ = lambda argument1, ▪ Value of the function is : 50
argument2: argument1 +
argument2;
▪ Value of the function is : 90
Python Function
Python Function
Normal Import
Adding Variables
Module alias
import platform
▪ Using the dir() Function
x = dir(platform)
▪ There is a built-in function to list all
print(x)
the function names (or variable
names) in a module. The dir() ▪ Note: The dir() function can be used
function: on all modules, also the ones you
create yourself.
▪ Example
▪ List all the defined names belonging
to the platform module:
99
def greeting(name):
▪ Import From Module
print("Hello, " + name)
▪ You can choose to import only parts
from a module, by using the from
keyword. person1 = {
Example
Import only the person1 dictionary from the module:
import math
x = 81
print('The square root of', x, 'is', math.sqrt())
• Factorialx
import math
x=6
print('The factorial of', x, 'is:', math.factorial(x))
104
Random Module
DateTime Module
• In Python, date and time are not a data type of their own, but a module named datetime
can be imported to work with the date as well as time. Python Datetime module comes
built into Python, so there is no need to install it externally.
• Date class
• The date class is used to instantiate date objects in Python. When an object of this class is
instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class
needs three mandatory arguments year, month and date.
• Constructor syntax:
• class datetime.date(year, month, day)
106
DateTime Module
DateTime Module
DateTime Module
Time class
• The time class creates the time object which represents local time, independent of any
day.
• Constructor Syntax:
• class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *,
fold=0)
• All the arguments are optional. tzinfo can be None otherwise all the attributes must be
integer in the following range –
110
Time Class
Time Class
Time Class
Python Package
• What is Package?
• A python package is a collection of modules. Modules that are related to each
other are mainly put in the same package.
• When a module from an external package is required in a program, that package
can be imported and its modules can be put to use.
• We organize a large number of files in different folders and subfolders based on
some criteria, so that 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.
115
Python Package
• As you know, 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.
116
Python Packages
Python Package
Python Package
Python Package
__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 the above modules available
when this package is imported. Note that __init__.py is essential for the folder to
be recognized by Python as a package. You can optionally define functions from
individual modules to be made available.
120
Python Package
• Note:
• We shall also create another Python script in the MyApp folder and import the mypackage
package in it. It should be at the same level of the package to be imported.
• 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. Modify __init__.py as below:
__init__.py
from .functions import average, power
from .greet import SayHello
121
Python Package
Python Package
• Note that functions power() and SayHello() are imported from the package and not from
their respective modules, as done earlier. The output of the above script is:
D:\MyApp>python test.py
Hello world
power(3,2) : 9
15. Exception Handling
124
Exceptional Handling
What is Exception?
• Exceptions are events that are used to modify the flow of control through a program when the error
occurs. Exceptions get triggered automatically on finding errors in Python.
Exceptions are processed using five statements:
• try/except: catch the error and recover from exceptions hoist by programmers or Python itself.
• try/finally: Whether exception occurs or not, it automatically performs the clean-up action.
• assert: triggers an exception conditionally in the code.
• raise: manually triggers an exception in the code.
• with/as: implement context managers in older versions of Python such as - Python 2.6 & Python
3.0.
125
Exceptional Handling
Why Exceptions?
• To handle the errors in a proper manner and make others to understand. We use
Exceptional Handling.
Roles of Exception Handler in Python
• Error handling: The exceptions get raised whenever Python detects an error in a program
at runtime. As a programmer, if you don't want the default behavior, then code a 'try'
statement to catch and recover the program from an exception. Python will jump to the
'try' handler when the program detects an error; the execution will be resumed.
• Event Notification: Exceptions are also used to signal suitable conditions & then passing
result flags around a program and text them explicitly.
126
Exceptional Handling
• Terminate Execution: There may arise some problems or errors in programs that it
needs a termination. So try/finally is used that guarantees that closing-time operation
will be performed. The 'with' statement offers an alternative for objects that support it.
• Exotic flow of Control: Programmers can also use exceptions as a basis for
implementing unusual control flow. Since there is no 'go to' statement in Python so that
exceptions can help in this respect.
127
Exceptional Handling
• Example 1:
(a,b) = (6,0)
try:# simple use of try-except block for handling
errors
g = a/b
except ZeroDivisionError:
print ("This is a DIVIDED BY ZERO error")
128
Exceptional Handling
Python Exception
• Example 1
a = ["Python", "Exceptions", "try and except"]
try:
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
except:
print ("Index out of range")
130
• If a condition does not meet our criteria but is correct according to the
Python interpreter, we can intentionally raise an exception using the
raise keyword. We can use a customized exception in conjunction with
the statement.
• If we wish to use raise to generate an exception when a given condition
happens, we may do so as follows:
131
• Example
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or
equal to 3 but is {len(num)}" )
132
• Python also supports the else clause, which should come after every except clause, in the try, and except blocks.
Only when the try clause fails to throw an exception the Python interpreter goes on to the else block.
• Here is an instance of a try clause with an else clause.
• Example :
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
reciprocal( 4 )
reciprocal( 0 )
133
• The finally keyword is available in Python, and it is always used after the try-except block. The finally code block
is always executed after the try block has terminated normally or after the try block has terminated for some other
reason.
• Here is an example of finally keyword with try-except clauses:
• Example:
try:
div = 4 // 0
print( div )
# this block will handle the exception raised
except ZeroDivisionError:
print( "Atepting to divide by zero" )
# this will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )
134
User-Defined Exceptions
• By inheriting classes from the typical built-in exceptions, Python also lets us design
our customized exceptions.
• Here is an illustration of a RuntimeError. In this case, a class that derives from
RuntimeError is produced. Once an exception is detected, we can use this to display
additional detailed information.
• We raise a user-defined exception in the try block and then handle the exception in the
except block. An example of the class EmptyError is created using the variable var.
135
User-Defined Exceptions
try:
▪ Example: input_num = int(input("Enter a number: "))
class
if input_num < number:
InvalidAgeException(Exception):
raise InvalidAgeException
"Raised when the input value is
less than 18" else:
pass print("Eligible to Vote")
number = 18
except InvalidAgeException:
print("Exception occurred: Invalid Age")
136
class Error(Exception):
pass
class zerodivision(Error):
pass
try:
i_num = int(input("Enter a number: "))
if i_num == 0:
raise zerodivision
except zerodivision:
print("Input value is zero, try again!")
print()
16. Database in Python
138
• To build the real world applications, connecting with the databases is the
necessity for the programming languages. However, python allows us to
connect our application to the databases like MySQL, SQLite, MongoDB,
and many others.
• We will discuss Python - MySQL connectivity, and we will perform the
database operations in python.
Install mysql.connector
• To connect the python application with the MySQL database, we must
import the mysql.connector module in the program.
• The mysql.connector is not a built-in module that comes with the python
installation. We need to install it to get it working.
139
• $ cd mysql-connector-python-8.0.13/
• Step 4: Run the file named setup.py with python (python3 in case you
have also installed python 2) with the parameter build.
• $ python setup.py build
• Step 5: Run the following command to install the mysql-connector.
• $ python setup.py install
• This will take a bit of time to install mysql-connector for python. We can
verify the installation once the process gets over by importing mysql-
connector on the python shell.
141
Database Connection
• In this section, we will discuss the steps to connect the python application to the
database.
• There are the following steps to connect a python application to our database.
╺ Import mysql.connector module
╺ Create the connection object.
╺ Create the cursor object
╺ Execute the query
Creating the connection
• To create a connection between the MySQL database and the python application,
the connect() method of mysql.connector module is used.
143
Database Connection
• Pass the database details like HostName, username, and the database password in the
method call. The method returns the connection object.
• The syntax to use the connect() is given below.
╺ Connection-Object= mysql.connector.connect(host = <host-name> , user = <username> , passwd =
<password> )
• Consider the following example.
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
• #printing the connection object
• print(myconn)
144
Database Connection
• Output:
• <mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>
• Here, we must notice that we can specify the database name in the connect() method if we want to
connect to a specific database.
Example 2:
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")
• #printing the connection object
• print(myconn)
Output:
• <mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>
145
Database Connection
Database Connection
Example:
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google", database = "mydb")
• #printing the connection object
• print(myconn)
• #creating the cursor object
• cur = myconn.cursor()
• print(cur)
147
Database Connection
• Output:
• <mysql.connector.connection.MySQLConnection object at
0x7faa17a15748>
• MySQLCursor: (Nothing executed yet)
Creating new databases
• Let us create the new database PythonDB.
• Getting the list of existing databases
• We can get the list of all the databases by using the
following MySQL query.
148
Execute Database
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google")
#creating the cursor object Example
cur = myconn.cursor() Output:
try: ('EmployeeDB',)
('Test',)
dbs = cur.execute("show databases")('TestDB',)
except: ('information_schema',)
myconn.rollback() ('mydb',)
('mysql',)
for x in cur: ('performance_schema',)
print(x) ('testDB',)
myconn.close()
149
• The new database can be created by using the following SQL query.
• > create database <database-name>
Example
• import mysql.connector
• #Create the connection object
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google")
• #creating the cursor object
• cur = myconn.cursor()
•
150
• try:
• #creating a new database
• cur.execute("create database PythonDB2")
• #getting the list of all the databases which will now include the new database PythonDB
• dbs = cur.execute("show databases")
• except: Output:
• myconn.rollback()
('EmployeeDB',)
('PythonDB',)
• for x in cur: ('Test',)
• print(x)
('TestDB',)
('anshika',)
• myconn.close() ('information_schema',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
151
Creating a Table
import mysql.connector
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
cur = myconn.cursor()
try:
dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20)
not null primary key, salary float not null, Dept_id int not null)")
except:
myconn.rollback()
myconn.close()
152
Alter Table
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user =
"root",passwd = "google",database = "PythonDB")
• cur = myconn.cursor()
• try:
• dbs = cur.execute("alter table Employee add branch_name
varchar(20) not null")
• except:
• myconn.rollback()
• myconn.close()
153
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"Raaki1973$",database='pythondb2')
• cur=myconn.cursor()
• sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
• val = ("John", 110, 25000.00, 201, "Newyork")
• try:
• cur.execute(sql,val)
• myconn.commit()
• except:
• myconn.rollback()
•
• print(cur.rowcount,"record inserted!")
• myconn.close()
154
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "Raaki1973$",database='pythondb2')
• cur=myconn.cursor()
• sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"
• val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of
spain"),("Nick",104,90000.00,201,"Newyork")]
• try:
• cur.executemany(sql,val)
• myconn.commit()
• except:
• myconn.rollback()
• print(cur.rowcount,"record inserted!")
• myconn.close()
155
Read Operation
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"Raaki1973$",database='pythondb2')
• cur=myconn.cursor()
• try:
• cur.execute("select * from Employee")
• res=cur.fetchall()
• for x in res:
• print(x)
• except:
• myconn.rollback()
• myconn.close()
156
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"Raaki1973$",database='pythondb2')
• cur=myconn.cursor()
• try:
• cur.execute("select name, id, salary from Employee")
• res=cur.fetchall()
• for x in res:
• print(x)
• except:
• myconn.rollback()
157
Update operation
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"Raaki1973$",database='pythondb2')
• cur=myconn.cursor()
• try:
• cur.execute("update Employee set name = 'alex' where id = 110")
• myconn.commit()
• except:
• myconn.rollback()
• myconn.close()
158
Delete Operation
• import mysql.connector
• myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"Raaki1973$",database='pythondb2')
• cur=myconn.cursor()
• try:
• cur.execute("delete from Employee where id = 110")
• myconn.commit()
• except:
• myconn.rollback()
• myconn.close()
17. File Handling in Python
160
• We were taking the input from the console and writing it back to the console to interact with
the user.
• Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the
console since the memory is volatile, it is impossible to recover the programmatically
generated data again and again.
• The file handling plays an important role when the data needs to be stored permanently into
the file. A file is a named location on disk to store related information. We can access the
stored information (non-volatile) after the program termination.
161
File Handling
Opening a file
Opening a File
• Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
165
• Once all the operations are done on the file, we must close it
through our Python script using the close() method.
• Any unwritten information gets destroyed once the close()
method is called on a file object.
• We can perform any operation on the file externally using the file
system which is the currently opened in Python; hence it is good
practice to close the file once all the operations are done.
• The syntax to use the close() method is given below.
166
• Syntax
fileobject.close()
Example:
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()
167
• After closing the file, we cannot perform any operation in the file. The file
needs to be properly closed. If any exception occurs while performing some
operations in the file then the program terminates without closing the file.
• We should use the following method to overcome such type of problem.
try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()
168
• Example:
# open the file.txt in append mode. Create a new file if no such
file exists.
fileptr = open("file2.txt", "w")
# appending the content to the file
fileptr.write('''''Python is the modern day language. It makes
things so simple.
It is the fastest-growing programing language''')
# closing the opened the file
fileptr.close()
172
• We have opened the file in w mode. The file1.txt file doesn't exist, it
created a new file and we have written the content in the file using
the write() function.
• Example 2
#open the file.txt in write mode.
fileptr = open("file2.txt","a")
#overwriting the content of the file
fileptr.write(" Python has an easy syntax and user-friendly interaction.")
#closing the opened file
fileptr.close()
• Here, the count is the number of bytes to be read from the file
starting from the beginning of the file. If the count is not
specified, then it may read the content of the file until the end.
• Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r")
#stores all the data of the file into the variable content
content = fileptr.read(10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
175
• We can read the file using for loop. Consider the following
example.
#open the file.txt in read mode. causes an error if no
such file exists.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
177
• Python facilitates to read the file line by line by using a function readline()
method.
• The readline() method reads the lines of the file from the beginning, i.e., if
we use the readline() method two times, then we can get the first two lines
of the file.
• Consider the following example which contains a function readline() that
reads the first line of our file "file2.txt" containing three lines. Consider the
following example.
• We called the readline() function two times that's why it read two lines from
the file.
• Python provides also the readlines() method which is used for the reading
lines. It returns the list of the lines till the end of file(EOF) is reached.
178
• Realine() Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
179
• Example:
#open the file.txt in read mode. causes error if no such
file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
180
• Example 1
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x")
print(fileptr)
if fileptr:
print("File created successfully")
• Output:
• <_io.TextIOWrapper name='file2.txt' mode='x'
encoding='cp1252'>
• File created successfully
182
tell()
• Python provides the tell() method which is used to print the byte number at which the file pointer currently exists. Consider
the following example.
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
• Output:
• The filepointer is at byte : 0
• After reading, the filepointer is at: 117
183
• Example Output:
Code1
”
187
Hello!
I am Raakesh Kumar
I am here because I love
Python.
You can reach me at
info@ritepros.com
or
Group whatsapp.
Python
Raakesh Kumar
18.Regular Expression
in Python
3
▪ RegEx Module
▪ A regular expression is a set of characters ▪ Python has a built-in package called re,
with highly specialized syntax that we can which can be used to work with Regular
use to find or match other characters or Expressions.
groups of characters.
▪ Import the re module:
▪ Regular expressions, or Regex, are widely
used in the UNIX world.
▪ import re
▪ The re-module in Python gives full
support for regular expressions .
▪ The re module raises the re.error
exception whenever an error occurs while
implementing or using a regular
expression.
4
▪ Metacharacters
▪ Metacharacters are characters with a special meaning:
Character Description Example
\ Signals a special sequence (can also be used to escape special characters) "\d"
| Either or "falls|stays"
5
▪ Example 2: ▪ Example 3:
▪ #Find all lower case characters ▪ # To Find all digit characters:
alphabetically between "a" and "m": ▪ import re
▪ import re ▪ txt = "That will be 59 dollars"
▪ txt = "The rain in Spain" ▪ x = re.findall("\d", txt)
▪ x = re.findall("[a-m]", txt) ▪ print(x)
▪ print(x) ▪ Output:
▪ Output: ▪ ['5', '9']
▪ ['h', 'e', 'a', 'i', 'i', 'a', 'i']
7
▪ Example 5:
▪ Example 4: ▪ #Check if the string starts with 'hello':
▪ #Search for a sequence that starts ▪ import re
with "he", followed by any two
characters, and end with "o":
▪ txt = "hello planet"
▪ import re
▪ x = re.findall("^hello", txt)
▪ x = re.findall("he..o", txt)
▪ print("Yes, the string starts with 'hello'")
▪ print(x)
▪ else:
▪ Output: ['hello']
▪ print("No match")
▪ Output: Yes, the string starts with 'hello'
8
▪ Example 6: ▪ Example 7:
▪ #Check if the string ends with 'planet': ▪ #Search for a sequence that starts with "he",
▪ import re followed by 0 or more occurrence of
characters, and an "o":
▪ txt = "hello planet"
▪ import re
▪ x = re.findall("planet$", txt)
▪ txt = "hello planet"
▪ if x:
▪ x = re.findall("he.*o", txt)
▪ print("Yes, the string ends with
'planet'") ▪ print(x)
▪ else: ▪ Output:
▪
Character Description Example
Special Sequences \A Returns a match if the specified characters are at the beginning of the string "\AThe"
▪ A special sequence is a \
\b Returns a match where the specified characters are at the beginning or at the end
of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw
r"\bain"
r"ain\b"
\B Returns a match where the specified characters are present, but NOT at the r"\Bain"
and has a special meaning: \d Returns a match where the string contains digits (numbers from 0-9) "\d"
\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space character "\s"
\S Returns a match where the string DOES NOT contain a white space character "\S"
\w Returns a match where the string contains any word characters (characters from a "\w"
to Z, digits from 0-9, and the underscore _ character)
\W Returns a match where the string DOES NOT contain any word characters "\W"
\Z Returns a match if the specified characters are at the end of the string "Spain\Z"
12
▪ import re
▪ txt = "The rain in Spain"
▪ x = re.findall(r"ain\B", txt)
▪ txt = "The rain in Spain"
▪ print(x)
▪ x = re.findall(r"\Bain", txt) ▪ if x:
▪ print(x) ▪ print("Yes, there is at least one match!")
▪ if x: ▪ else:
▪ else: ▪ Output:
▪ print("No match")
▪ []
Sets
Set Description
▪ Sets [arn] Returns a match where one of the specified characters (a, r, or n) is
present
▪ A set is a set of characters [a-n] Returns a match for any lower case character, alphabetically
between a and n
inside a pair of square brackets [^arn] Returns a match for any character EXCEPT a, r, and n
[] with a special meaning:
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are
present
[0-9] Returns a match for any digit between 0 and 9
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower
case OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a
match for any + character in the string
14
Sets
sets
Split() Function
Sub() Function
▪ Class
▪ class is a user-defined data type that
contains both the data itself and the
methods that may be used to manipulate
it.
▪ Classes serve as a template to create
objects.
▪ A class is a prototype of a building.
▪ A building contains all the details about the
floor, rooms, doors, windows, etc.
▪ we can make as many buildings as we
want, based on these details.
22
▪ Class ▪ Syntax
▪ The class can be defined as a
collection of objects. class ClassName:
▪ It is a logical entity that has some
<statement-1>
specific attributes and methods.
.
▪ For example: if you have an
employee class, then it should .
contain an attribute and method, <statement-N>
▪ i.e. an email id, name, age, salary,
etc.
24
▪ Example: ▪ Output:
class car: ▪ Toyota 2016
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
26
▪ Object ▪ Method
▪ In the above example, we have ▪ The method is a function that is
created the class named car, associated with an object. In Python, a
and it has two attributes method is not unique to class instances.
modelname and year. Any object type can have methods.
▪ We have created a c1 object to
access the class attribute.
▪ The c1 object will allocate
memory for these values.
27
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
▪ Syntax d.bark()
d.speak()
class derived-class(base class):
<class-suite> Output:
dog barking Animal Speaking
37
def Divide(self,a,b):
return a/b;
41
c.setMaxPrice(1000)
c.sell()
43
class Polygon:
▪ Polymorphism # method to render a shape
▪ Polymorphism contains two words def render(self):
"poly" and "morphs". print("Rendering Polygon...")
▪ Poly means many, and morph means class Square(Polygon):
shape. # renders Square
▪ By polymorphism, we understand that def render(self):
one task can be performed in different print("Rendering Square...")
ways. class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
44
Method Overriding
▪ Example:
▪ When the parent class method is ▪ class Animal:
defined in the child class with some
specific implementation, then the
▪ def speak(self):
concept is called method overriding. ▪ print("speaking")
▪ We may need to perform method ▪ class Dog(Animal):
overriding in the scenario where the ▪ def speak(self):
different definition of a parent class
▪ print("Barking")
method is needed in the child class.
▪ d = Dog()
▪ d.speak()
▪ Output: Barking
46
“
Code1
The End
”
50
Hello!
I am Raakesh Kumar
I am here because I love
Python.
You can reach me at
info@ritepros.com
or
Group whatsapp.