0% found this document useful (0 votes)
6 views369 pages

Advance Python Program Unit I and V

The document provides an overview of Python, detailing its history, features, and applications. It covers installation instructions for Python and popular IDEs like PyCharm and Anaconda, as well as the modes of execution and data types in Python. Additionally, it compares Python with other programming languages and lists its advantages.

Uploaded by

Abhi Bunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views369 pages

Advance Python Program Unit I and V

The document provides an overview of Python, detailing its history, features, and applications. It covers installation instructions for Python and popular IDEs like PyCharm and Anaconda, as well as the modes of execution and data types in Python. Additionally, it compares Python with other programming languages and lists its advantages.

Uploaded by

Abhi Bunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 369

Python

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

• Easy to Learn and Use • Dynamically Typed


• Free and Open-Source • Portability
• Rapid Development • Strong Community Support
• Interpreted Language
• Wide Range of Libraries and
Frameworks
10

Python Version List

Python Version Released Date

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

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


11

Flavors of Python

• Flavors of Python refer to the


different types of Python
compilers. These flavors are
useful to integrate various
programming languages into
Python. Below are mention
few flavours of Python.
12

Comparison between Programming Languages


C, Java and Python
C C++ JAVA 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

Platform-specific Platform dependent Platform-unaffected Platform independent

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

PyCharm IDE Installation

• PyCharm is one of the most popular


• Python is a programming language that lets
Python-IDE developed by JetBrains and
you work quickly and integrate systems more
efficiently. used for performing scripting in Python
language.
• Running Python codes on an offline
interpreter is much more compatible than • PyCharm provides some very useful
using an online IDE. features like Code completion and
• Now, we will see how to install Python inspection, Debugging process, support
Pycharm on Windows. for various programming frameworks
such as Flask and Django, Package
Management, etc.
• PyCharm provides various tools for
productive development in Python.
15

How to install Python IDE?

• If Python is already installed, it will generate a


• Before, starting with the process of message with the Python version available.
Installing Python IDE PyCharm in
Windows, one must ensure that Python
is installed on their system.
• To check if the system is equipped with
Python, go to the Command line(search
for cmd in the Run dialog( window
button + R).
• Now run the following command on
cmd: python --version
16

How to install Pycharm IDE

• Here is a process to download


Pycharm :
• Step 1) Go to website official
website of
Jetbrains https://www.jetbrains.c
om/pycharm/download/ and click
on the “DOWNLOAD” link of the
Community section.
17

How to install Pycharm IDE

• 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

How to install Pycharm IDE

• Step 4) Choose options of installation according to • Step 5) Choose JetBrains and Click on “Install”.
your choice.
19

How to install Pycharm IDE

• Step 7) After Installation completed , It will show that


Pycharm is installed successfully , then click on “I want
• Step 6) Let the installation to manually reboot later”. Click on Finish and then the
finished. process is completed.
20

How to install Pycharm IDE

• Getting Started with PyCharm


• Once the Installation is over, PyCharm
can be searched and started from the
Start Menu. Follow the steps given
below to do the same:
• Searching from Start Menu:
21

How to install Pycharm IDE

• Getting done with License • Setting UI Theme:


Agreement:
22

How to install Pycharm IDE

• Downloading Plugins: • Get Started with PyCharm:


23

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

How to Install Anaconda on Windows?

• Anaconda is an open-source software that contains


Jupyter, spyder, etc that are used for large data
processing, data analytics, heavy scientific computing.
Anaconda works for R and python programming
language. Spyder(sub-application of Anaconda) is used
for python.
• Opencv for python will work in spyder.
• Package versions are managed by the package
management system called conda.
• Download and install Anaconda:
• Head over to anaconda.com and install the latest
version of Anaconda. Make sure to download the
“Python 3.7 Version” for the appropriate architecture.
25

How to Install Anaconda on Windows?

• Begin with the installation process: • Getting through the License Agreement:
• Getting Started:
26

How to Install Anaconda on Windows?

• Select Installation Type: Select Just Me if you want the software to


• Choose Installation Location:
be used by a single User
27

How to Install Anaconda on Windows?

• Advanced Installation Option: • Getting through the Installation


Process:
28

How to Install Anaconda on Windows?

• Recommendation to Install Pycharm: • Finishing up the Installation:


29

How to Install Anaconda on Windows?

• Working with Anaconda:


30

Python Installation Steps

▰ Download Anaconda. (currently Python 3.7).


▰ Install Anaconda
▰ Congratulations, you have installed Jupyter
Notebook. To run the notebook.
jupyter notebook
31

What is Conda?

• Conda is a powerful command line tool for


package and environment management
• Anaconda Prompt
that runs on Windows, macOS, and Linux. • The Anaconda Prompt Command Line Interface
(CLI) lets you perform tasks by writing text
• Install Python packages as well as the commands.
Python interpreter directly.
• Another key difference between the two
tools is that conda has the ability to create
isolated environments that can contain
different versions of Python and/or the
packages installed in them
32

What is Conda?

• Anaconda Navigator: • Jupiter Notebook:


33

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

• Spyder IDE: • Spyder Feature:


• Spyder is a free and open source • Key components.
• Interface. Tabs. File switcher. Split panels.
scientific environment written in • Editing features. Syntax highlighting. Code cells.
Python, for Python, and designed Automatic formatting.

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

Python Mode of Execution

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

immediately get the output. Output: "Hello GFG"


•Example 2 (addition of two numbers):
• It’s like a Read-Evaluate-Print Loop (REPL). Python
• Great for beginners to evaluate code step by step.
>>> a = 2
>>> b = 3
• To run Python code interactively:
>>> c =a + b
>>> print(c)
37

Python Mode of Execution

• Script Mode: • Example:


• In script mode, you write Python code in a file (e.g., • Create a file named my_script.py.
.py file).
• Write your Python code in the file.
• Save the file and execute it using the command • Execute it using python my_script.py.
prompt.
• Editing is easy, as you can view and modify the
entire code.
• Ideal for larger programs and reusable code.
38

Python Mode of Execution

• Batch Mode: • 1. Create a Batch File:


• In Python, batch mode allows you to run Python • First, create a batch file (e.g., my_script.bat).
scripts from a batch file (usually with a .bat
extension). Here’s how you can execute Python
• In this file, specify the path to the Python interpreter and
the path of the Python script you want to execute.
code in batch mode:
• Example batch file content:
• @echo off
• python "C:\path\to\your\script.py" %*
• Replace "C:\path\to\your\script.py" with the actual path to
your Python script.
• %* passes any command-line arguments to the Python
script.
39

Python Editors and IDE

• Pycharm • Sublime Text


• Spyder • Vi /Vim
• Thonny
• Visual studio code(VS
Code)
• Eclipse
40

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.

• Example: "Hello, World!"


• Example: [1, 2, 3]

• Numeric Types:
• Tuple (tuple): Ordered, immutable collections of items.

• Integer (int): Whole numbers (positive, negative, or


• Example: (10, 20, 30)

zero). • Range (range): Represents a sequence of numbers.

• Example: 42 • Example: range(5) (produces 0, 1, 2, 3, 4)

• Floating-Point (float): Represents decimal numbers. • Mapping Type:

• Example: 3.14 • Dictionary (dict): Stores key-value pairs.


• Example: {"name": "John", "age": 30}
41

Python Datatypes

• Set Types: • Bytearray (bytearray): Mutable version of bytes.


• Set (set): Unordered, mutable collections of unique • Example: bytearray([65, 66, 67])
elements. • None Type (NoneType): Represents absence of a value
• Example: {1, 2, 3} (similar to null in other languages).
• FrozenSet (frozenset): Similar to sets but • Example: None
immutable. • You can use the type() function to check the data type of
• Example: frozenset({1, 2, 3}) any object. For example:
• Boolean Type (bool): Represents True or False. Python
x=5
• Binary Types: print(type(x)) # Output: <class 'int'>
• Bytes (bytes): Represents a sequence of bytes.
• Example: b"Hello"
42

Python Constants

• In Python, constants are special variables whose • User-Defined Constants:


values remain fixed and don’t change during a
program’s execution. While Python doesn’t have a
• Declare your own constants in a module (a separate file).

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 provides some built-in constants:


• Define constants within a class using __slots__.

• True, False, and None.


• Explore namedtuple() and @dataclass.

• Example: True represents boolean true, None denotes


absence of a value.
43

Python Variables

• In Python, variables are identifiers used to reference


• 2. Type Flexibility: Variables can change type after
being set. For instance:
values within a program. Here are some key points
about Python variables: • x = 4 # x is an integer

• 1. Dynamic Typing: Python doesn’t require explicit • x = "Sally" # x is now a string


variable declaration. You create a variable by • 3. Casting: To specify a data type, use casting:
assigning a value to it.
• x = str(3) # x is a string '3'
• For example:
• y = int(3) # y is an integer 3
• x=5
• z = float(3) # z is a float 3.0
• y = "John"
• Case Sensitivity: Variable names are case-sensitive:
• a=4
• A = "Sally" # A won't overwrite a
44

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!")

• Inline Comments: Placed at the end of a line, they


• A multiline string (triple quotes) to create a comment block:

ignore the rest of that line. For instance: • """

• print("Hello, World!") # This is a comment • This is a comment


• written in more than one line
• """
• print("Hello, World!")
45

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

Input() Function in Python

• The input() function in Python allows you to


accept data from the user. When called, it
prompts the user to enter input and waits for
them to type a response followed by the Enter
key. The input is returned as a string, which you
can save to a variable or use directly in your
program.
• Example:
• user_input = input("Enter something: ")
• print("You entered:", user_input)
47

Type()/id() Function in python

• The id() function in Python returns a unique identifier for


• The type() function in Python serves two main an object. Here are some key points:
purposes:
• Purpose: The id() function assigns an integer identity
• Determining Object Type: When you pass an object (memory address) to an object when it is created.
as an argument, it returns the type of that object.
• Uniqueness: Each object has its own unique ID.
• Example:
• Constant During Lifetime: The ID remains constant
• x = 10 throughout the program’s execution (except for some
• print(type(x)) # Output: <class 'int'> objects with predefined IDs, like integers from -5 to
256).
• Usage Example:
• x = ('apple', 'banana', 'cherry')
• y = id(x) # Get the ID of the tuple
• print("ID of x:", y)
48

Type Conversion in Python

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

• z = x + y # z is automatically converted to a float


49

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

• In Python, an escape sequence is a sequence of characters that, when


used inside a string, doesn’t represent itself directly but is converted into
another character or series of characters. Let’s explore some common
escape sequences:
• Backslash (\): The backslash itself is an escape character. To include a
literal backslash in a string, use \\\\.
• Single Quote (\') and Double Quote (\" ): To include single or double
quotes within a string, escape them with a backslash. For example:
• print("She said, \\"Hello!\\"")
51

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

• Python provides various types of operators that


allow you to perform different operations on
variables and values. Let’s explore some of the
key operator groups:
• Arithmetic Operators:
• Used for common mathematical operations:
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulus)
• ** (Exponentiation)
• // (Floor division)
56

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

• Booleans may be combined with the and, or,


and not logical operators.
60

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

• Indentation is one of Python's singular features.


Indentation is used everywhere in Python.
• It takes one keystroke to tab, and two
keystrokes to insert brackets.
• Another advantage is readability. It's clearer and
easier to read code
5.Flow Control Statement
65

Conditionals

• Conditionals evaluate Boolean values or


Boolean expressions, and they are usually
preceded by 'if'.
• if Syntax:
66

If Syntax
67

If elif Statement

• elif is short for else if. elif does not have


meaning in isolation. elif appears in between an
if and else
68

The While Loop

• In a while loop, a designated segment of code


repeats provided that a particular condition is
true. When the condition evaluates to false, the
while loop stops running.
69

Infinite Loop

• If something is taking much longer than


expected, an infinite loop might be the one.
70

break

• break is a special keyword in Python that is


specifically designed for loops. If placed inside
of a loop, commonly in a conditional, break will
immediately terminate the loop.
71

For loop

• The for loops are similar to while loops, but they


have additional advantages, such as being able
to iterate over strings and other objects.
72

For loop
73

Continue

• continue is another Python keyword designed for


loops.
• When Python reaches the continue keyword, it stops
the code and goes back to the beginning of the loop.
• continue is similar to break because they both
interrupt the loop process, but break terminates the
loop, continue continues the loop from the
beginning.
74

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

• Assigning Strings to Variables:


• Assign a string to a variable using the variable name followed by an equal sign and the string:
• a = "Hello"
• Multiline Strings:
• Use three quotes (either single or double) for multiline strings:
• a = """Lorem ipsum dolor sit amet,consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua."""
• String Length:
• Get the length of a string using the len() function:
• a = "Hello, World!"
• print(len(a)) # Prints 13
78

Strings in Python

• Looping Through a String:


• Since strings are arrays, you can loop through their characters:
• for char in "banana":
• print(char)
• Checking for Substrings:
• Use the in keyword to check if a certain phrase or character is present in a string:
• txt = "The best things in life are free!"
• print("free" in txt) # Prints True
79

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

String Splitting and Joining

• 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

Finding Substring in Python

• 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

Finding Substring in Python

• Searching Within a Slice:


• You can also search for a substring within a specific slice of the string.
• Example:
• s = "Johny Johny Yes Papa"
• result = s.find("Johny", 1) # Search starting from index 1
• print(result) # Output: 6
• Here, the second occurrence of “Johny” begins at index 6 within the
string.
87

Finding Substring in Python

• Handling Non-Existent Substrings:


• If the substring doesn’t exist, the method returns -1.
• Example:
• s = "Johny Johny Yes Papa"
• result = s.find("Julia")
• print(result) # Output: -1
• Since “Julia” is not present, the result is -1.
88

String Change Case

• In Python, you have a few ways to change the case of a


string. Let’s explore them:
• Swapcase:
• The .swapcase() method converts all uppercase
characters to lowercase and vice versa in the given string.
• Example:
• s = "rAAkeshKUMar"
• print(s.swapcase())
89

String Change Case

▪ 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 Data Strucutre

• Data structures refer to objects that can hold some data


together, which means they are used to store a collection of
related data.
• There are four types of data structures in python. They are

• It defines the relationship between data and operations that can


be performed on data.
92

Python List

• A list is a type of container in Python that is used to


store multiple data sets at the same time. Python lists
are often compared to arrays in other programming
languages.
• list in Python is written within square brackets, [ ].
• Each element in the list has its own distinct position
and index.
• The elements in a list have a finite sequence.
93

Python List
94

Python List
95

Python List
96

Python List
97

Python List
98

Matrix as Nested List


99

Matrices as Nested List

List with in a list is called nested list. In python we


can create Nested List which is show below:
100

Matrix as Nested List


101

List Methods

# a simple list Output:


list1 = [1, 2, "Python", "Program", 15.9]
[1, 2, 'Python', 'Program', 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list ['Amy', 'Ryan', 'Henry', 'Emma']
print(list1)
print(list2)
< class ' list ' >
# printing the type of list
< class ' list ' >
print(type(list1))
print(type(list2))
102

Characteristics of Lists

• The lists are in order.


• The list element can be accessed via the index.
• The mutable type of List is
• The rundowns are changeable sorts.
• The number of various elements can be stored in a list.
103

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 Indexing and Splitting

▪ The indexing procedure is carried out similarly


to string processing. The slice operator [] can be
used to get to the List's components.
▪ The index ranges from 0 to length -1. The 0th
index is where the List's first element is stored;
the 1st index is where the second element is
stored, and so on.
105

List Indexing and Splitting

list = [1,2,3,4,5,6,7] # By default, the index value is 0 so its


starts from the 0th element and go for
print(list[0])
index -1.
print(list[1])
print(list[:])
print(list[2])
print(list[2:5])
print(list[3])
print(list[1:6:2])
# Slicing the elements
print(list[0:6])
106

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

• In contrast to other programming languages, Python


lets you use negative indexing as well.
• The negative indices are counted from the right.
• The index -1 represents the final element on the
List's right side, followed by the index -2 for the next
member on the left, and so on, until the last element
on the left is reached.
108

Negative indexing

Example where we will use negative indexing to access the


elements of the list.
# negative indexing example
list = [1,2,3,4,5]
Output:
print(list[-1])
5
print(list[-3:]) [3, 4, 5]
[1, 2, 3, 4]
print(list[:-1]) [3, 4]

print(list[-3:-1])
109

Updating List Values

▪ Due to their mutability and the slice and assignment


operator's ability to update their values, lists are Python's
most adaptable data structure. Python's append() and insert()
methods can also add values to a list.
▪ Consider the following example to update the values inside
the List.
110

Updating List Values

# updating list values # Adding multiple-element


list = [1, 2, 3, 4, 5, 6] list[1:3] = [89, 78]
print(list) print(list)
# It will assign value to the # It will add value at the end of the list
value to the second index list[-1] = 25
list[2] = 10 print(list)
print(list)
111

Updating List Values

▪ 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

Python List Operations

▪ The concatenation (+) and repetition (*) operators work in


the same way as they were working with the strings. The
different operations of list are
▪ Repetition
▪ Concatenation
▪ Length
▪ Iteration
▪ Membership
113

1. Repetition

# repetition of list Output:


# declaring the list [12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
114

2. Concatenation

# concatenation of two lists Output:


# declaring the lists [12, 14, 16, 18, 20, 9, 10, 32, 54,
list1 = [12, 14, 16, 18, 20] 86]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
115

3. Length

It is used to get the length of the


list Output:
Code 9
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27,
39, 40]
# finding length of the list
len(list1)
116

4. Iteration

The for loop is used to iterate


over the list elements. Output:

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

• It returns true if a particular • print(600 in list1)


item exists in a particular list • print(700 in list1)
otherwise false. • print(1040 in list1)
• # membership of the list •
• # declaring the list
• print(300 in list1)
• list1 = [100, 200, 300, 400, 500]
• # true will be printed if value exists • print(100 in list1)
• # and false if not • print(500 in list1)
118

Membership

▪ Output:
▪ False
▪ False
▪ False
▪ True
▪ True
▪ True
119

Iterating a List

▪ A list can be iterated by • # iterating a list


using a for - in loop. A simple • list = ["John", "David", "James",
list containing four strings, "Jonathan"]
which can be iterated as
• for i in list:
follows.
• print(i)
Output:
• John
• David
• James
• Jonathan
120

Adding Elements to the List

• #Declaring the empty list


• The append() function in
• l =[]
Python can add a new item
to the List. In any case, the • #Number of elements will
annex() capability can be entered by the user
enhance the finish of the • n = int(input("Enter the
rundown. number of elements in the
list:"))
• # for loop to take the input
121

Adding Elements to the List

• for i in range(0,n): • # traversal loop to


• # The input is taken print the list items
from the user and added • for i in l:
to the list as the item • print(i, end = " ")
• l.append(input("Enter
the item:"))
• print("printing the list
items..")
122

Adding Elements to the List

• Enter the number of elements in the


list:10
• printing the list items..
• Enter the item:32 • 32 56 81 2 34 65
• Enter the item:56
• Enter the item:81
09 66 12 18
• Enter the item:2
• Enter the item:34
• Enter the item:65
• Enter the item:09
• Enter the item:66
• Enter the item:12
• Enter the item:18
123

Removing Elements from the 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

Removing Elements from the List

• Output:
• printing original list:
• 01234
• printing the list after the
removal of first element...
• 0134
125

Python List Built-in Functions

• Python provides the • len( )


following built-in • It is used to calculate the length of the list.
functions, which can be • # size of the list
used with the lists. • # declaring the list
• list1 = [12, 16, 18, 20, 39, 40]
• len()
• # finding length of the list
• max() • len(list1)
• min() • Output:
• 6
126

Python List Built-in Functions

• 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

Python List Built-in Functions

▪ 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

List's duplicate items.

• Example: 1- Create a • list2 = []


program to eliminate the • for i in list1:
List's duplicate items.
• if i not in list2:
• list1 =
• list2.append(i)
[1,2,2,3,55,98,65,65,13,29
] • print(list2)

• # Declare an empty list that ▪ Output:


will store unique values ▪ [1, 2, 3, 55, 98, 65, 13, 29]
129

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

▪ Tuples are used to store multiple items in ▪ Features of Python Tuple


a single variable. ▪ Tuples are an immutable data type,
▪ A tuple is a collection which is ordered meaning their elements cannot be changed
and unchangeable. after they are generated.
▪ Tuples are written with round brackets. ▪ Each element in a tuple has a specific order
Example that will never change because tuples are
ordered sequences.
("Suzuki", "Audi", "BMW"," Skoda ")
4

Python Tuples

# Python program to show how to create a tuple


▪ Forming a Tuple:
# Creating an empty tuple
▪ All the objects-also known as
"elements"-must be separated by a empty_tuple = ()
comma, enclosed in parenthesis (). print("Empty tuple: ", empty_tuple)
Although parentheses are not
# Creating tuple having integers
required, they are recommended.
int_tuple = (4, 6, 8, 10, 12, 14)
▪ Any number of items, including those
with various data types (dictionary, print("Tuple with integers: ", int_tuple)
string, float, list, etc.), can be
contained in a tuple.
5

Python Tuples

# Creating a tuple having objects of different Output:


data types Empty tuple: ()
mixed_tuple = (4, "Python", 9.3) Tuple with integers: (4, 6, 8, 10, 12, 14)
print("Tuple with different data types: ", Tuple with different data types: (4, 'Python',
mixed_tuple) 9.3)
# Creating a nested tuple A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3,
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 5, 6))
3, 5, 6))
print("A nested tuple: ", nested_tuple)
6

Python Tuples

# Checking the data type of object tuple_


▪ Parentheses are not necessary for the print(type(tuple_) )
construction of multiples. This is # Trying to modify tuple_
known as triple pressing. try:
▪ Example: tuple_[1] = 4.2
# Python program to create a tuple except:
without using parentheses print(TypeError )
# Creating a tuple ▪ Output:
tuple_ = 4, 5.7, "Tuples", ["Python", (4, 5.7, 'Tuples', ['Python', 'Tuples'])
"Tuples"] <class 'tuple'>
# Displaying the tuple created <class 'TypeError'>
print(tuple_)
7

Python Tuples

▪ A tuple's objects can be accessed in a ▪ Because the index in Python must be an


variety of ways. integer, we cannot provide an index of a
Indexing floating data type or any other type. If we
provide a floating index, the result will be
▪ Indexing We can use the index operator []
TypeError.
to access an object in a tuple, where the
index starts at 0. ▪ The method by which elements can be
accessed through nested tuples can be
▪ The indices of a tuple with five items will
seen in the example below.
range from 0 to 4. An Index Error will be
raised assuming we attempt to get to a
list from the Tuple that is outside the
scope of the tuple record. An index above
four will be out of range in this scenario.
8

Python Tuples

▪ try:
▪ # Python program to show how to
access tuple elements
▪ print(tuple_[5])

▪ # Creating a tuple
▪ except Exception as e:

▪ tuple_ = ("Python", "Tuple", "Ordered",


▪ print(e)
"Collection") ▪ # trying to access elements through the index
of floating data type
▪ print(tuple_[0])
▪ print(tuple_[1])
▪ try:

▪ # trying to access element index more


▪ print(tuple_[1.0])
than the length of a tuple ▪ except Exception as e:
▪ print(e)
9

Python Tuples

▪ # Creating a nested tuple ▪ Output:


▪ nested_tuple = ("Tuple", [4, 6, 2, 6], (6, Python
2, 6, 7)) Tuple
tuple index out of range
▪ tuple indices must be integers or slices, not
▪ # Accessing the index of a nested tuple float
▪ print(nested_tuple[0][3]) l
▪ print(nested_tuple[1][1]) 6
10

Python Tuples -Negative Indexing

▪ Python's sequence objects support # Printing elements using negative


negative indexing. indices
print("Element at -1 index: ", tuple_[-1])
▪ The last thing of the assortment is
print("Elements between -4 and -1 are:
addressed by - 1, the second last
", tuple_[-4:-1])
thing by - 2, etc.
Output:
Example:
Element at -1 index: Collection
# Python program to show how
Elements between -4 and -1 are:
negative indexing works in Python
('Python', 'Tuple', 'Ordered')
tuples
# Creating a tuple
tuple_ = ("Python", "Tuple",
"Ordered", "Collection")
11

Python Tuples – Slicing

▪ Slicing # Python program to show how slicing works in


▪ Tuple slicing is a common practice in Python tuples
Python and the most common way for # Creating a tuple
programmers to deal with practical tuple_ = ("Python", "Tuple", "Ordered",
issues. Look at a tuple in Python. Slice a "Immutable", "Collection", "Objects")
tuple to access a variety of its elements.
# Using slicing to access elements of the tuple
Using the colon as a straightforward
slicing operator (:) is one strategy. print("Elements between indices 1 and 3: ",
tuple_[1:3])
▪ To gain access to various tuple
elements, we can use the slicing
operator colon (:).
12

Python Tuples -Slicing

# Using negative indexing in slicing Output:


print("Elements between indices 0 and -4: ", Elements between indices 1 and 3: ('Tuple',
tuple_[:-4]) 'Ordered')
# Printing the entire tuple by using the default Elements between indices 0 and -4: ('Python',
start and end values. 'Tuple')
print("Entire tuple: ", tuple_[:]) Entire tuple: ('Python', 'Tuple', 'Ordered',
'Immutable', 'Collection', 'Objects')
13

Python Tuples – Deleting a Tuple

▪ Deleting a Tuple try:

A tuple's parts can't be modified. We are unable to eliminate del tuple_[3]


or remove tuple components as a result. print(tuple_)
the keyword del can completely delete a tuple. except Exception as e:

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

Python Tuples - Repetition Tuples in Python

# Python program to show repetition in tuples Tuple Methods


tuple_ = ('Python',"Tuples") ▪ Count () Method
print("Original tuple is: ", tuple_) ▪ The times the predetermined
# Repeting the tuple elements component happens in the Tuple is
returned by the count () capability of the
tuple_ = tuple_ * 3
Tuple.
print("New tuple is: ", tuple_)
Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python',
'Tuples', 'Python', 'Tuples')
15

Python Tuples – Tuples Method

# Creating tuples Output:


T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2) Count of 2 in T1 is: 5
T2 = ('python', 'java', 'python', 'Tpoint', Count of java in T2 is: 2
'python', 'java')
# counting the appearance of 2
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
print('Count of Java in T2 is:', res)
16

Python Tuples – Index() Method

Index() Method: # Creating tuples


The Index() function returns the first instance of Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
the requested element from the Tuple.
# getting the index of 3
Parameters:
res = Tuple_data.index(3)
Start: (Optional) the index that is used to begin
the final (optional) search: The most recent print('First occurrence of 1 is', res)
index from which the search is carried out # getting the index of 3 after 4th
# index
Output:
First occurrence of 1 is 2 res = Tuple_data.index(3, 4)
First occurrence of 1 after 4th index is:6
print('First occurrence of 1 after 4th index is:',
res)
17

Tuple Membership Test

Utilizing the watchword, we can decide whether a


Output:
thing is available in the given Tuple.
True
# Python program to show how to perform membership
test for tuples False
# Creating a tuple False
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", True
"Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
18

Iterating Through a Tuple

A for loop can be used to iterate through each Output:


tuple element. Python
Example Tuple
# Python program to show how to iterate over Ordered
tuple elements
Immutable
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered",
"Immutable")
# Iterating over tuple elements using a for loop
for item in tuple_:
print(item)
9. Python Set
20

What is Set?

▪ A Python set is the collection of the unordered items.


▪ Each element in the set must be unique, immutable, and the sets remove
the duplicate elements.
▪ Sets are mutable which means we can modify it after its creation.
▪ Unlike other collections in Python, there is no index attached to the
elements of the set, i.e.,
▪ We cannot directly access any element of the set by the index.
▪ We can print them all together, or we can get the list of elements by
looping through the set.
21

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

Using set() method

Example 2: Using set() method ▪ Output:

Days = set(["Monday", "Tuesday",


▪ {'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday',
'Tuesday', 'Sunday'}
"Wednesday", "Thursday", "Friday",
▪ <class 'set'>
"Saturday", "Sunday"])
▪ looping through the set elements ...
print(Days) ▪ Friday
print(type(Days)) ▪ Wednesday

print("looping through the set ▪ Thursday

elements ... ") ▪ Saturday

for i in Days:
▪ Monday
▪ Tuesday
print(i) ▪ Sunday
24

Set Built-in Methods- Adding items to the set

▪ Python provides the add() • Example: 1 - Using add() method


Months = set(["January","February", "March", "April", "May", "June"])
method and update() method
print("\nprinting the original set ... ")
which can be used to add some print(months)
particular item to the set. print("\nAdding other months to the set...");
Months.add("July");
▪ The add() method is used to Months.add ("August");
add a single element whereas print("\nPrinting the modified set...");

the update() method is used to print(Months)

add multiple elements to the print("\nlooping through the set elements ... ")
for i in Months:
set. Consider the following print(i)
example.
25

Set Built-in Methods- Adding items to the set

▪ Output: looping through the set elements ...


printing the original set ... February
{'February', 'May', 'April', 'March',
July
'June', 'January'}
May
Adding other months to the set...
Printing the modified set... April
{'February', 'July', 'May', 'April', March
'March', 'August', 'June', 'January'} August
June
January
26

update() method

▪ To add more than one item in the set, ▪ Output:


Python provides the update() method. It
printing the original set ...
accepts iterable as an argument.
{'January', 'February', 'April', 'May',
▪ Example - 2 Using update() 'June', 'March'}
function
Months = set(["January","February", "March", "April", "May", updating the original set ...
"June"])
print("\nprinting the original set ... ") printing the modified set ...
print(Months)
print("\nupdating the original set ... ") {'January', 'February', 'April', 'August',
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
'October', 'May', 'June', 'July',
print(Months); 'September', 'March'}
27

Removing items from the set- discard()

▪ Python provides the discard() ▪ Consider the following example.


method and remove() method ▪ Example-1 Using discard() method
which can be used to remove the months = set(["January","February", "March", "April", "May",
"June"])
items from the set. print("\nprinting the original set ... ")
print(months)
▪ The difference between these print("\nRemoving some months from the set...");
function, using discard() function months.discard("January");
months.discard("May");
if the item does not exist in the print("\nPrinting the modified set...");
print(months)
set then the set remain print("\nlooping through the set elements ... ")
unchanged whereas remove() for i in months:
print(i)
method will through an error.
28

Removing items from the set – discard()

looping through the set elements ...


▪ Output: February
printing the original set ... March
{'February', 'January', 'March', 'April', April
'June', 'May'} June
Removing some months from the
set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
29

Using remove() Method

▪ Python provides also the remove() method print(months)


to remove the item from the set. Consider
print("\nRemoving some months from
the following example to remove the items
using remove() method.
the set...");

▪ Example-2 Using remove() function months.remove("January");


months = months.remove("May");
set(["January","February", print("\nPrinting the modified set...");
"March", "April", "May", "June"]) print(months)
print("\nprinting the original set
... ")
30

Using remove() Method

▪ printing the original set ...


▪ {'February', 'June', 'April', 'May', 'January', 'March'}
▪ Removing some months from the set...
▪ Printing the modified set...
▪ {'February', 'June', 'April', 'March'}
31

pop() method

▪ We can also use the pop() method to Months = set(["January","February",


remove the item. Generally, the pop() "March", "April", "May", "June"])
method will always remove the last print("\nprinting the original set ... ")
item but the set is unordered, we
print(Months)
can't determine which element will be
popped from set. print("\nRemoving some months from the
set...");
▪ Consider the following example to
remove the item from the set using Months.pop();
pop() method. Months.pop();
print("\nPrinting the modified set...");
print(Months)
32

pop() method

▪ Output: ▪ In the above code, the last element of the


Month set is March but the pop() method
printing the original set ...
removed the June and January because
{'June', 'January', 'May', 'April', the set is unordered and the pop() method
'February', 'March'} could not determine the last element of
the set.
Removing some months from the
set...
Printing the modified set...
{'May', 'April', 'February', 'March'}
33

clear() Method

▪ Python provides the clear() method to ▪ Output:


remove all the items from the set.
▪ Consider the following example. ▪ printing the original set ...
Months = set(["January","February",
"March", "April", "May", "June"])
▪ {'January', 'May', 'June', 'April', 'March',
'February'}
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the
set...");
Months.clear()
print("\nPrinting the modified set...")
print(Months)
34

Difference between discard() and remove()

▪ 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

Difference between discard() and remove()

Months = set(["January","February", ▪ Output:


"March", "April", "May", "June"]) printing the original set ...
print("\nprinting the original set ... ") {'March', 'January', 'April', 'June', 'February', 'May'}
print(Months) Removing items through discard() method...

print("\nRemoving items through discard() printing the modified set...


method..."); {'March', 'January', 'April', 'June', 'February', 'May'}

Months.discard("Feb"); #will not give an Removing items through remove() method...


error although the key feb is not available Traceback (most recent call last):
in the set File "set.py", line 9, in
print("\nprinting the modified set...") Months.remove("Jan")

print(Months) KeyError: 'Jan'


36

Python Set Operations

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

▪ Union of two Sets ▪ Example 1: using union | operator


Days1={"Monday","Tuesday","Wednesday","Thursday",
▪ To combine two or more sets into one set in Python, use "Sunday"}
the union() function. Days2 = {"Friday","Saturday","Sunday"}
▪ All of the distinctive characteristics from each combined print(Days1|Days2) #printing the union of the sets
set are present in the final set. ▪ Output:
▪ As parameters, one or more sets may be passed to the ▪ {'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday',
union() function. 'Monday', 'Thursday'}
▪ The function returns a copy of the set supplied as the lone
parameter if there is just one set.
37

Python Set Operations

▪ 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

The intersection of two sets

▪ 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

Difference between the two sets

Symmetric Difference of two sets


▪ The difference of two sets can be calculated by using ▪ In Python, the symmetric Difference between set1 and
the subtraction (-) operator or intersection() method. set2 is the set of elements present in one set or the
▪ Suppose there are two sets A and B, and the other but not in both sets.
difference is A-B that denotes the resulting set will be ▪ The set of elements is in set1 or set2 but not in their
obtained that element of A, which is not present in intersection.
the set B.
▪ The Symmetric Difference of two sets can be computed
▪ Example 1 : Using subtraction ( - ) operator using Python's symmetric_difference() method.
Days1 = {"Monday",
"Thursday"}
"Tuesday", "Wednesday",
▪ This method returns a new set containing all the
elements in either but not in both.
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will
be printed}
▪ Output:
▪ {'Thursday', 'Wednesday'}
41

Symmetric Difference of two sets

Example - 2: Using symmetric_difference() method


Example - 1: Using ^ operator
a = {1,2,3,4,5,6}
a = {1,2,3,4,5,6} b = {1,2,9,8,10}
b = {1,2,9,8,10} C = a.symmetric_difference(b)
c = a^b print(c)
print(c) Output:
Output: {3, 4, 5, 6, 8, 9, 10}
{3, 4, 5, 6, 8, 9, 10}
42

Set comparisons

▪ In Python, you can compare sets to check if they are Output:


equal, if one set is a subset or superset of another, or if
two sets have elements in common. True
Example
Days1 = {"Monday", "Tuesday", "Wednesday",
False
"Thursday"} False
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
10. Python Dictionary
44

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

▪ Curly brackets are the simplest way to ▪ Example Code:


generate a Python dictionary, although Employee = {"Name": "Johnny", "Age":
there are other approaches as well. 32, "salary":26000,"Company":"^TCS"}
▪ With many key-value pairs surrounded in print(type(Employee))
curly brackets and a colon separating each print("printing Employee data .... ")
key from its value, the dictionary can be print(Employee)
built. (:).
▪ Output:
▪ Syntax:
▪ Dict = {"Name": "Gayle", "Age": 25}
▪ <class 'dict'>

▪ In the above dictionary Dict, The keys


▪ printing Employee data ....
Name and Age are the strings which ▪ {'Name': 'Johnny', 'Age': 32, 'salary':
comes under the category of an 26000, 'Company': TCS}
immutable object.
46

Creating the Dictionary

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

Creating the Dictionary

▪ Creating a Dictionary ▪ Output


# with each item as a Pair Empty Dictionary:
Dict = dict([(4, 'Rinku'), (2, Singh)]) {}
print("\nDictionary with each item Create Dictionary by using dict():
as a pair: ") {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
print(Dict) Dictionary with each item as a pair:
{4: 'Rinku', 2: 'Singh'}
48

Accessing the dictionary values

▪ Employee = {"Name": "Dev", "Age": 20,


▪ To access data contained in lists and "salary":45000,"Company":"WIPRO"}
tuples, indexing has been studied.
The keys of the dictionary can be used
▪ print(type(Employee))
to obtain the values because they are ▪ print("printing Employee data .... ")
unique from one another. The ▪ print("Name : %s" %Employee["Name"])
following method can be used to
▪ print("Age : %d" %Employee["Age"])
access dictionary values.
▪ print("Salary : %d" %Employee["salary"])
▪ print("Company : %s"
%Employee["Company"])
49

Accessing the dictionary values

▪ Adding Dictionary Values


▪ Output: ▪ The dictionary is a mutable data type,
<class 'dict'> and utilizing the right keys allows you to
change its values. Dict[key] = value and
printing Employee data ....
the value can both be modified. An
Name : Dev existing value can also be updated using
Age : 20 the update() method.

Salary : 45000 ▪ Note: The value is updated if the key-


value pair is already present in the
Company : WIPRO dictionary. Otherwise, the dictionary's
newly added keys.
50

Adding Dictionary Values

▪ Example - 1: # Adding set of values


# Creating an empty Dictionary # with a single Key
Dict = {} # The Emp_ages doesn't exist to dictionary
print("Empty Dictionary: ")
Dict['Emp_ages'] = 20, 33, 24
print(Dict)
print("\nDictionary after adding 3 elements:
# Adding elements to dictionary one at a time
")
Dict[0] = 'Peter'
print(Dict)
Dict[2] = 'Joseph'
# Updating existing Key's Value
Dict[3] = 'Ricky'
Dict[3] = ‘iWaveLabs'
print("\nDictionary after adding 3 elements: ")
print(Dict)
print("\nUpdated key value: ")
print(Dict)
51

Adding Dictionary Values

▪ 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

Adding Dictionary Values

▪ Output ▪ Name: Sunny


▪ <class 'dict'> ▪ Age: 38
▪ printing Employee data .... ▪ Salary: 39000
▪ Employee = {"Name": "Dev", "Age": ▪ Company:Hcl
20, ▪ printing the new data
"salary":45000,"Company":"WIPRO"
} Enter the details of the new
▪ {'Name': 'Sunny', 'Age': 38, 'salary':
39000, 'Company': 'Hcl'}
employee....
53

Deleting Elements using del Keyword

▪ The items of the dictionary can be ▪ del Employee["Name"]


deleted by using the del keyword as ▪ del Employee["Company"]
given below.
▪ print("printing the modified information
▪ Employee = {"Name": "David", "Age": ")
30,
"salary":55000,"Company":"WIPRO"}
▪ print(Employee)

▪ 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

Deleting Elements using del Keyword

▪ <class 'dict'> ▪ NameError: name 'Employee' is not


▪ printing Employee data .... defined.

▪ {'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

Deleting Elements using pop() Method

▪ A dictionary is a group of key-value ▪ # Creating a Dictionary


pairs in Python. You can retrieve, insert, Dict1 = {1: 'iWaveLabs', 2:
and remove items using this unordered, 'Educational', 3: 'Website'}
mutable data type by using their keys. # Deleting a key
The pop() method is one of the ways to
# using pop() method
get rid of elements from a dictionary.
pop_key = Dict1.pop(2)
▪ The value connected to a specific key in
print(Dict1)
a dictionary is removed using the pop()
method, which then returns the value. ▪ Output
The key of the element to be removed ▪ {1: 'iWaveLabst', 3: 'Website'}
is the only argument needed.
Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items. In contrast to the clear()
method, which removes all of the elements from the entire dictionary, popitem() removes any element from a dictionary.
56

Iterating Dictionary

▪ A dictionary can be iterated using for loop as ▪ Example 2:


given below. #for loop to print all the values of the
▪ Example 1 dictionary
# for loop to print all the keys of a dictionary Employee = {"Name": "John", "Age": 29,
Emin Employee: "salary":25000,"Company":"WIPRO"}
printployee = {"Name": "John", "Age": 29,
for x in Employee:
"salary":25000,"Company":"WIPRO"}
print(Employee[x])
for x (x)
▪ Output ▪ Output
Name John
Age 29
salary 25000
Company WIPRO
57

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

Properties of Dictionary Keys

1. In the dictionary, we cannot store ▪ Output


multiple values for the same keys. If we
pass more than one value for a single key, ▪ Name John
then the value which is last assigned is
considered as the value of the key.
▪ Age 29

▪ Example 1:
▪ Salary 25000

Employee={"Name":"John","Age":29,"Sa ▪ Company WIPRO


lary":25000,"Company":"WIPRO","Name
":
"John"}
for x,y in Employee.items():
print(x,y)
59

Properties of Dictionary Keys

2. The key cannot belong to any mutable ▪ Output


object in Python. Numbers, strings, or Traceback (most recent call last):
tuples can be used as the key, however File "dictionary.py", line 1, in
mutable objects like lists cannot be Employee = {"Name": "John", "Age": 29,
used as the key in a dictionary. "salary":26000,"Company":"WIPRO",[100,
▪ Example: 201,301]:"Department ID"}
Employee = {"Name": "John", "Age": 29, TypeError: unhashable type: 'list'
"salary":26000,"Company":"WIPRO",[10
0,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
60

Built-in Dictionary Functions

▪ A function is a method that can be ▪ len()


used on a construct to yield a value. ▪ The dictionary's length is returned via
Additionally, the construct is the len() function in Python. The string
unaltered. A few of the Python is lengthened by one for each key-
methods can be combined with a value pair.
Python dictionary.
▪ dict = {1: "Ayan", 2: "Bunny", 3: "Ram",
▪ The built-in Python dictionary methods 4: "Bheem"}
are listed below, along with a brief
description.
▪ len(dict)
▪ Output
▪ 4
61

Built-in Dictionary Functions

▪ 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

Built-in Dictionary Functions

▪ 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

Built-in Dictionary Functions

▪ 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

Built-in Dictionary Functions

▪ 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

Built-in Dictionary Functions

▪ 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

Built-in Dictionary Functions

▪ 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

▪ Advantages of Python Functions


▪ What is a function? ▪ Once defined, Python functions can be called
▪ A function will perform a specific task multiple times and from any location in a program.
and return a single value. ▪ Our Python program can be broken up into
numerous, easy-to-follow functions if it is
▪ A function is a block of code which
significant.
only runs when it is called.
▪ The ability to return as many outputs as we want
▪ You can pass data, known as using a variety of arguments is one of Python's most
parameters, into a function. significant achievements.
▪ A function can return data as a result. ▪ However, Python programs have always incurred
overhead when calling functions.
▪ However, calling functions has always been
overhead in a Python program.
69

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

▪ # Example Python Code for calling a function


▪ Calling a Function ▪ # Defining a function
▪ Calling a Function To define a def a_function( string ):
function, use the def keyword to give "This prints the value of length of string"
it a name, specify the arguments it return len(string)
must receive, and organize the code # Calling the function we defined
block. print( "Length of the string Functions is: ", a_function( "Functions" ) )
▪ When function is finished, we can print( "Length of the string Python is: ", a_function( "Python" ) )
call it from anywhere in the program. Output:
Length of the string Functions is: 9
Length of the string Python is: 6
71

Python Function

▪ Pass by Reference vs. Pass by Value ▪ # Example Python Code for Pass by Reference vs. Value

▪ In the Python programming language, ▪ # defining the function

all parameters are passed by def square( item_list ):

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 code to demonstrate the ▪ Output:


use of default arguments
Passing only one argument
def function( n1, n2 = 20 ):
print("number 1 is: ", n1) number 1 is: 30
print("number 2 is: ", n2) number 2 is: 20
print( "Passing only one Passing two arguments
argument" ) number 1 is: 50
function(30) number 2 is: 30
print( "Passing two arguments" )
function(50,30)
74

Python Function

▪ Keyword Arguments ▪ Example 2:


def function( n1, n2 ):
▪ Example 1: print("number 1 is: ", n1)
def my_function(child3, child2, print("number 2 is: ", n2)
print( "Without using keyword" )
child1): function( 50, 30)
print("The youngest child is " + print( "With using keyword" )
function( n2 = 50, n1 = 30)
child3)
my_function(child1 = "Abinav", ▪ Output:
Without using keyword
child2 = "Priya", child3 = "Harshitha") number 1 is: 50
▪ Output: number 2 is: 30
With using keyword
▪ The youngest child is Harshitha
number 1 is: 30
number 2 is: 50
75

Python Function

▪ Required Arguments – Positional ▪ Example 1:


Argument def function( n1, n2 ):
▪ Required arguments are those supplied print("number 1 is: ", n1)
to a function during its call in a print("number 2 is: ", n2)
predetermined positional sequence. The print( "Passing out of order arguments" )
number of arguments required in the function( 30, 20 )
method call must be the same as those print( "Passing only one argument" )
provided in the function's definition. try:
Output: function( 30 )
Passing out of order arguments
number 1 is: 30 except:
number 2 is: 20 print( "Function needs two positional
Passing only one argument
Function needs two positional arguments arguments" )
76

Python Functions

▪ You can specify that a function can ▪ Example :


have ONLY positional arguments, or def my_function(x, /):
ONLY keyword arguments.
print(x)
▪ To specify that a function can have
my_function(3)
only positional arguments, add , /
after the arguments: ▪ Output:
▪ 3
77

Python Functions

▪ But when adding the , / you will get an error if


▪ Without the , / you are actually you try to send a keyword argument:
allowed to use keyword arguments ▪ Example:
even if the function expects
def my_function(x, /):
positional arguments:
print(x)
▪ Example: my_function(x = 3)
def my_function(x):
▪ Output:
print(x) Traceback (most recent call last):
my_function(x = 3) File "./prog.py", line 4, in <module>
▪ Output: 3 TypeError: my_function() got some positional-
only arguments passed as keyword arguments:
'x'
78

Python Function

▪ Variable-Length Arguments ▪ Example :


▪ Arbitrary Arguments, *args def my_function(*kids):
▪ If you do not know how many arguments print("The youngest child is " +
that will be passed into your function, add kids[2])
a * before the parameter name in the my_function("Abinav", "Priya",
function definition. "Harshitha")
▪ This way the function will receive a tuple
of arguments, and can access the items ▪ Output:
accordingly:
▪ The youngest child is Harshitha
79

Python Function

▪ Arbitrary Keyword Arguments, **kwargs ▪ Example:


▪ If you do not know how many keyword def my_function(**kid):
arguments that will be passed into your print("His last name is " + kid["lname"])
function, add two asterisk: ** before the my_function(fname = "Raakesh", lname
parameter name in the function = "Kumar")
definition. ▪ Output:
▪ This way the function will receive a ▪ His last name is Kumar
dictionary of arguments, and can access
the items accordingly:
80

Python Function

▪ Example 2: def function( **kargs_list ):


def function( *args_list ): ans = []
ans = [] for key, value in kargs_list.items():
ans.append([key, value])
for l in args_list:
return ans
ans.append( l.upper() )
object = function(First = "Python", Second
return ans = "Functions", Third = "Variable")
object = function('Python', print(object)
'Functions', 'variable') Output:

print( object ) ['PYTHON', 'FUNCTIONS', 'VARIABLE']


[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Variable']]
81

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

▪ Passing a List as an Argument def my_function(food):


▪ You can send any data types of argument for x in food:
to a function (string, number, list, print(x)
dictionary etc.), and it will be treated as fruits = ["apple", "banana", "cherry"]
the same data type inside the function. my_function(fruits)
▪ E.g. if you send a List as an argument, it ▪ Output:
will still be a List when it reaches the ▪ apple
function:
▪ banana
▪ cherry
83

Python Functions

▪ The pass Statement def myfunction():


▪ function definitions cannot be empty, pass
but if you for some reason have a ▪ # having an empty function
function definition with no content, definition like this, would raise
put in the pass statement to avoid an error without the pass
getting an error. statement
84

Python Functions

▪ Example of a recursive function:


▪ Recursive Function def factorial(x):
▪ A function can call other functions. It is if x == 1:
even possible for the function to call return 1
itself. These types of construct are else:
termed as recursive functions. return (x * factorial(x-1))
▪ The following image shows the working num = 3
of a recursive function called recurse. print("The factorial of", num, "is",
factorial(num))
▪ The factorial of 3 is 6
85

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

▪ Inner functions ▪ Example:


▪ A function which is defined inside def f1():

another function is known as inner s = 'I love iWaveLabs'

function or nested function. def f2():


s = 'Me too'
▪ Nested functions are able to access
print(s)
variables of the enclosing scope.
f2()
▪ Inner functions are used so that they
print(s)
can be protected from everything
f1()
happening outside the function.
▪ Output:
▪ This process is also known as Me too
Encapsulation. I love iWaveLabs
87

Python Function

▪ The Anonymous Functions ▪ Example1:


▪ A lambda function is a small ▪ x = lambda a: a + 10
anonymous function. ▪ print(x(5))
▪ A lambda function can take any ▪ output: 15
number of arguments, but can only
have one expression.
▪ Syntax:
▪ lambda arguments : expression
88

Python Function

▪ Example: Output:
lambda_ = lambda argument1, ▪ Value of the function is : 50
argument2: argument1 +
argument2;
▪ Value of the function is : 90

print( "Value of the function is : ",


lambda_( 20, 30 ) )
print( "Value of the function is : ",
lambda_( 40, 50 ) )
89

Python Function

▪ Using Lambda Function with filter()


▪ Example:
list_ = [35, 12, 69, 55, 75, 14, 73]
▪ The filter() method accepts two odd_list = list(filter( lambda num: (num % 2 != 0) ,
arguments in Python: a function and list_ ))
an iterable such as a list. print('The list of odd number is:',odd_list)

▪ The function is called for every item of


the list, and a new iterable or list is ▪ Output:
returned that holds just those ▪ The list of odd number is: [35, 69, 55, 75, 73]
elements that returned True when
supplied to the function.
90

Python Function

▪ Using Lambda Function with map() ▪ Example:


▪ A method and a list are passed to numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
Python's map() function. squared_list = list(map( lambda num:
▪ The function is executed for all of the num ** 2 , numbers_list ))
elements within the list, and a new print( 'Square of each number in the
list is produced with elements given list:' ,squared_list )
generated by the given function for ▪ Output:
every item.
▪ Square of each number in the given list: [4,
▪ The map() method is used to square 16, 25, 1, 9, 49, 64, 81, 100]
all the entries in a list.
91

Creating User Defined Modules

▪ Create a Module ▪ Example


▪ To create a module just save ▪ def greeting(name):
the code you want in a file ▪ print("Hello, " + name)
with the file extension .py: ▪ greeting("Raaki")
▪ Save this code in a file named
mymodule.py
92

How to import modules in python?

• In Python, we may import functions from one module into our


program.
• For this, we make use of the import Python keyword. In the Python
window, we add the next to import keyword, the name of the module
we need to import.
• Syntax:
• import <module-name>
93

How to import modules in python?

Example import example_module


Save the file as example_module.py result = example_module.square( 4 )
after entering the following. print( "By using the module square of number
is: ", result )

def square( number ):


result = number ** 2
return result
94

Normal Import

▪ Use a Module import mymodule


▪ Now we can use the module we mymodule.greeting(“Mohan")
just created, by using the import
statement: Note: When using a function from a
▪ Example module, use the syntax:
module_name.function_name.
▪ Import the module named
mymodule, and call the greeting
function:
95

Adding Variables

▪ Variables in Module ▪ Example 2:


person1 = {
▪ The module can contain functions, as
"name": "John",
already described, but also variables of
"age": 36,
all types (arrays, dictionaries, objects
"country": "Norway"
etc):
}
▪ Example ▪ Import the module named mymodule, and
▪ Save this code in the file mymodule.py access the person1 dictionary:
▪ Example 1: import mymodule
import mymodule a = mymodule.person1["age"]
mymodule.greeting(“Mohan") print(a)
Name=“Raaki” Print(mymodule.person1[“name”])
96

Module alias

▪ Naming a Module import mymodule as mx


▪ You can name the module file a = mx.person1["age"]
whatever you like, but it must have print(a)
the file extension .py
▪ Re-naming a Module
▪ You can create an alias when you
import a module, by using the as
keyword:
▪ Example
▪ Create an alias for mymodule called
mx:
97

Working with Standard Modules

▪ Built-in Modules ▪ import platform


▪ There are several built-in modules ▪ x = platform.system()
in Python, which you can import ▪ print(x)
whenever you like.
▪ Example
▪ Import and use the platform
module:
98

Using Dir() Function

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

Using From Import

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 "name": "John",

▪ The module named mymodule has "age": 36,


one function and one dictionary: "country": "Norway"
}
100

Using From Import

Example
Import only the person1 dictionary from the module:

from mymodule import person1


print (person1["age"])
13. Python Date and Time
102

Working with Standard moules -Math,


Random, Date time modules.

• Python's standard library is very extensive, offering a wide range of functionalities


• Usint Math
• Using the import Python keyword and the dot operator, we may import a standard
module and can access the defined functions within it.
• Example:
import math
print( "The value of euler's number is", math.e )
sqrt(x): Return the square root of x.
103

Working with Standard moules -Math,


Random, Date time modules.

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

• implements pseudo-random number generators for various


distributions.
• randint(a, b): Return a random integer x, which belongs to the range
[a,b].
import random
result = random.randint(1, 11)
print('The random integer number in range [1,11] is:', result)
105

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

• The arguments must be in the following range –


• MINYEAR <= year <= MAXYEAR
• 1 <= month <= 12
• 1 <= day <= number of days in the given month and year
• Example 1:
from datetime import date
my_date = date(1996, 12, 11)
print("Date passed as argument is", my_date)
107

DateTime Module

• Get Current Date


from datetime import date
today = date.today()
print("Today's date is", today)
• Example 3: Get Today’s Year, Month, and Date
from datetime import date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
108

DateTime Module

• Example 4: Get date from Timestamp


from datetime import datetime
date_time =
datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)
109

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

• 0 <= hour < 24


• 0 <= minute < 60
• 0 <= second < 60
• 0 <= microsecond < 1000000
• fold in [0, 1]
111

Time Class

• Example 1: Time object representing time in Python


from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute=12)
print("\nTime with one argument", my_time)
# Calling constructor with
# 0 argument
my_time = time()
print("\nTime without argument", my_time)
112

Time Class

• Example 2: Get hours, minutes, seconds, and microseconds


• After creating a time object, its attributes can also be printed
separately.
from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
14.Python Packages
Package
114

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

• Let's create a package named mypackage, using the


following steps:
• 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.
• Using a Python-aware editor like IDLE, create modules
greet.py and functions.py with the following code:
117

Python Package

• Importing a Module from a Package


• Now, to test our package, navigate the command prompt to the MyApp folder and
invoke the Python prompt from there.
D:\MyApp>python
• Import the functions module from the mypackage package and call its power() function.
• >>> from mypackage import functions
• >>> functions.power(3,2)
• 9
118

Python Package

• It is also possible to import specific functions from a module in the package.


• >>> from mypackage.functions import sum
• >>> sum(10,20)
30
• >>> average(10,12)
• Traceback (most recent call last):
• File "<pyshell#13>", line 1, in <module>
• NameError: name 'average' is not defined
119

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

• The specified functions can now be imported in the interpreter session or


another executable script.
• Create test.py in the MyApp folder to test mypackage.
test.py
from mypackage import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x)
122

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

'Try - except' Clause with no Exception


• In Python, we catch exceptions and handle them using try and except code
blocks.
• The try clause contains the code that can raise an exception, while the except
clause contains the code lines that handle the exception.
• Let's see if we can access the index from the array, which is more than the
array's length, and handle the resulting exception.
129

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

How to Raise an Exception

• 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

How to Raise an Exception

• 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

Try with Else Clause

• 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

Finally Keyword in Python

• 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

Python user-defined exceptions

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

Database Environment Setup

• 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

Database Environment Setup

• Execute the following command to install it using pip installer.


• python -m pip install mysql-connector Or follow the following steps.
• Step 1: Click the link:
• https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3
dfd08c7b8660d09f91d8d5411298bcacbd309f96/mysql-connector-
python-8.0.13.tar.gz to download the source code.
• Step 2. Extract the archived file.
• Step 3: Open the terminal (CMD for windows) and change the present
working directory to the source code directory.
140

Database Environment Setup

• $ 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 Environment Setup

• Hence, we have successfully installed mysql-


connector for python on our system.
142

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

Creating a cursor object


• The cursor object can be defined as an abstraction specified in
the Python DB-API 2.0. It facilitates us to have multiple separate
working environments through the same connection to the
database. We can create the cursor object by calling the 'cursor'
function of the connection object. The cursor object is an
important aspect of executing queries to the databases.
• The syntax to create the cursor object is given below.
• <my_cur> = conn.cursor()
146

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

Creating the new database

• 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

Creating the new database

• 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

Insert data through python

• 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

Insert multiple rows

• 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

Reading specific Columns

• 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

File Handling in python

• 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

• The file-handling implementation is slightly lengthy or


complicated in the other programming language, but it is easier
and shorter in Python.
• n Python, files are treated in two modes as text or binary. The file
may be in the text or binary format, and each line of a file is ended
with the special character.
• Hence, a file operation can be done in the following order.
╺ Open a file
╺ Read or write - Performing operation
╺ Close the file
162

Opening a file

• Python provides an open() function that accepts two arguments,


file name and access mode in which the file is accessed. The
function returns a file object which can be used to perform
various operations like reading, writing, etc.
• Syntax:
file object = open(<file-name>, <access-mode>, <buffering>)
• The files can be accessed using various modes like read, write,
or append. The following are the details about the access mode
to open a file.
163

Types of file handling


164

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

The close() method

• 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

The close() method

• 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

The close() method

• 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

The with statement

• The with statement was introduced in python 2.5.


• The with statement is useful in the case of manipulating the files.
• It is used in the scenario where a pair of statements is to be
executed with a block of code in between.
• The syntax to open a file using with the statement is given below.
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
• The advantage of using with statement is that it provides the
guarantee to close the file regardless of how the nested block
exits.
169

The with statement

• It is always suggestible to use the with statement in the


case of files because, if the break, return, or exception
occurs in the nested block of code then it automatically
closes the file, we don't need to write the close() function.
It doesn't let the file to corrupt.
• Example
with open("file.txt",'r') as f:
content = f.read();
print(content)
170

Writing the file

• To write some text to a file, we need to open the


file using the open method with one of the
following access modes.
• w: It will overwrite the file if any file exists. The file
pointer is at the beginning of the file.
• a: It will append the existing file. The file pointer is
at the end of the file. It creates a new file if no file
exists.
171

Writing the file

• 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

Writing the file

• 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()

• Output: Python is the modern day language. It makes things so


173

The read() method

• We can see that the content of the file is modified. We have


opened the file in a mode and it appended the content in the
existing file2.txt.
• To read a file using the Python script, the Python provides the
read() method. The read() method reads a string from the file. It
can read the data in the text as well as a binary format.
• The syntax of the read() method is given below.
• Syntax:
• fileobj.read(<count>)
174

The read() method

• 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

The read() method

• In the above code, we have read the content of file2.txt by


using the read() function. We have passed count value as
ten which means it will read the first ten characters from
the file.
• If we want to print all content of the file the we can add
the the code as given below:.
content = fileptr.read()
print(content)
176

Read file through for loop

• 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

Read Lines of the file

• 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

Reading Lines Using readlines() function

• 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

Creating a new file

• The new file can be created by using one of the following


access modes with the function open().
• x: it creates a new file with the specified name. It causes
an error a file exists with the same name.
• a: It creates a new file with the specified name if no such
file exists. It appends the content to the file if the file
already exists with the specified name.
• w: It creates a new file with the specified name if no such
file exists. It overwrites the existing file.
181

Creating a new File

• 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

File Pointer positions

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

Modifying file pointer position

• In real-world applications, sometimes we need to change


the file pointer location externally since we may need to
read or write the content at various locations.
• For this purpose, the Python provides us the seek()
method which enables us to modify the file pointer
position externally.
• The syntax to use the seek() method is given below.
• Syntax:
• <file-ptr>.seek(offset[, from)
184

Modifying file pointer position

• The seek() method accepts two parameters:


• offset: It refers to the new position of the file pointer within the
file.
• from: It indicates the reference position from where the bytes
are to be moved.
• If it is set to 0, the beginning of the file is used as the reference
position.
• If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer
is used as the reference position.
185

Modifying file pointer position

• Example Output:

# open the file file2.txt in read mode The filepointer is at byte : 0


fileptr = open("file2.txt","r") After reading, the filepointer is at: 10

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())
#changing the file pointer location to 10.
fileptr.seek(10);
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
186

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

What is Regular Expression

▪ 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

Regular Expression Metacharacters

▪ Metacharacters
▪ Metacharacters are characters with a special meaning:
Character Description Example

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape special characters) "\d"

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "planet$"

* Zero or more occurrences "he.*o"

+ One or more occurrences "he.+o"

? Zero or one occurrences "he.?o"

{} Exactly the specified number of occurrences "he.{2}o"

| Either or "falls|stays"
5

Regular Expression Metacharacters

▪ How to Use RegEx in Python? ▪ txt = "The rain in Spain"


▪ You can use RegEx in Python after ▪ x = re.search("^The.*Spain$",
importing re module. txt)
▪ Example 1: ▪ if x:
▪ Search the string to see if it starts ▪ print("YES! We have a
with "The" and ends with "Spain": match!")
▪ else:
▪ print("No match")
6

Regular Expression Examples Programs

▪ 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

Regular Expression Metacharacters

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

▪ txt = "hello planet"


▪ if x:

▪ 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

Regular Expression Metacharacters

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

▪ print("No match") ▪ ['hello']

▪ Output: Yes, the string ends with 'planet'


9

Regular Expression Metacharacters

▪ Example 9: #Search for a sequence that starts


▪ Example 8: One or more Occurance with "he", followed by 0 or 1 (any) character,
▪ #Search for a sequence that starts with and an "o":
"he", followed by 1 or more (any) ▪ import re
characters, and an "o": ▪ txt = "hello planet"
▪ import re ▪ x = re.findall("he.?o", txt)
▪ txt = "hello planet" ▪ print(x)
▪ x = re.findall("he.+o", txt) ▪ Output: []
▪ print(x)
▪ Output: ['hello']
10

Regular Expression Metacharacters

▪ Example 11: #Check if the string contains either "falls" or "stays":


▪ Example 10: #Search for a sequence ▪ import re
that starts with "he", followed excactly ▪ txt = "The rain in Spain falls mainly in the plain!"
2 (any) characters, and an "o":
▪ x = re.findall("falls|stays", txt)
▪ import re ▪ print(x)
▪ txt = "hello planet" ▪ if x:
▪ x = re.findall("he.{2}o", txt) ▪ print("Yes, there is at least one match!")
▪ print(x) ▪ else:

▪ Output: ['hello'] ▪ print("No match")


▪ Output: ['falls']
▪ Yes, there is at least one match!
11

Regular Expression Metacharacters


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"

followed by one of the


string")

\B Returns a match where the specified characters are present, but NOT at the r"\Bain"

characters in the list below,


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"ain\B"
string")

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

Regular Expression Metacharacters

▪ Example 1: ▪ Example 2: #Check if "ain" is present, but NOT at


the end of a word:
▪ #Check if "ain" is present, but NOT at the
beginning of a word:
▪ import re

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

▪ print("Yes, there is at least one match!") ▪ print("No match")

▪ else: ▪ Output:

▪ print("No match")
▪ []

▪ Output: ['ain', 'ain’] Yes, there is at least one


▪ No match
13

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

[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59

[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

▪ Example 1: #Check if the ▪ print("Yes, there is at least one


string has any a, r, or n match!")
characters: ▪ else:
▪ import re ▪ print("No match")
▪ txt = "The rain in Spain" ▪ Output:
▪ x = re.findall("[arn]", txt) ▪ ['r', 'a', 'n', 'n', 'a', 'n']
▪ print(x) ▪ Yes, there is at least one
▪ if x: match!

15

sets

▪ Example 2: #Check if the ▪ print("Yes, there is at least one


string has any characters match!")
between a and n: ▪ else:
▪ import re ▪ print("No match")
▪ txt = "The rain in Spain" ▪ Output:
▪ x = re.findall("[a-n]", txt) ▪ ['h', 'e', 'a', 'i', 'n', 'i', 'n', 'a', 'i',
▪ print(x) 'n']
▪ if x: ▪ Yes, there is at least one
match!
16

The findall() Function

▪ The findall() function returns a ▪ The search() Function


list containing all matches. ▪ The search() function searches the string
▪ #Return a list containing every for a match, and returns a Match object if
occurrence of "ai": there is a match.
▪ import re ▪ If there is more than one match, only the
▪ txt = "The rain in Spain" first occurrence of the match will be
returned:
▪ x = re.findall("ai", txt)
▪ print(x)
▪ Output: ['ai', 'ai']
17

Split() Function

▪ import re ▪ The split() Function


▪ txt = "The rain in Spain" ▪ The split() function returns a list where the
▪ x = re.search("\s", txt) string has been split at each match:

▪ print("The first white-space ▪ #Split the string at every white-space


character is located in character:
position:", x.start()) ▪ import re
▪ Output: ▪ txt = "The rain in Spain"
▪ The first white-space character ▪ x = re.split("\s", txt)
is located in position: 3 ▪ print(x)
▪ Output: ['The', 'rain', 'in', 'Spain']
18

Sub() Function

▪ The sub() Function


▪ The sub() function replaces the
matches with the text of your choice:
▪ #Replace all white-space characters
with the digit "9":
▪ import re
▪ txt = "The rain in Spain"
▪ x = re.sub("\s", "9", txt)
▪ print(x)
▪ Output: The9rain9in9Spain
19. Opps Concept in
Python
20

Python Opps Concept

▪ Like other general-purpose ▪ The object is related to real-word entities


programming languages, Python is also such as book, house, pencil, etc.
an object-oriented language since its ▪ The oops concept focuses on writing the
beginning. reusable code.
▪ It allows us to develop applications ▪ It is a technique to solve the problem by
using an Object-Oriented approach. creating objects.
▪ In Python, we can easily create and ▪ Major principles of object-oriented
use classes and objects. programming system are given below.
▪ An object-oriented paradigm is to ▪ Class, Object, Method, Inheritance,
design the program using classes and Polymorphism ,Data Abstraction,
objects. Encapsulation
21

▪ 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

▪ Hence, the building can be ▪ Example:


seen as a class, and we can ▪ class Person:
create as many objects of this
class.
▪ def __init__(self, name,
age):
▪ syntax:
▪ self.name = name
▪ class ClassName:
▪ self.age = age
▪ #statement_suite
▪ def greet(self):
▪ print("Hello, my name is "
+ self.name)
23

Introduction to opps in python

▪ 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

Introduction to opps in python

▪ Object ▪ When we define a class, it needs to


The object is an entity that has state and create an object to allocate the
behavior. It may be any real-world memory. Consider the following
object like the mouse, keyboard, chair, example.
table, pen, etc.
▪ Everything in Python is an object, and
almost everything has attributes and
methods. All functions have a built-in
attribute __doc__, which returns the
docstring defined in the function source
code.
25

Introduction to opps in python

▪ 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

Introduction to opps in python

▪ 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

Introduction to Opps in python

Example :Object & Methods Output:


class Person: "Hello, my name is Ayan"
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
person1 = Person("Ayan", 25)
person1.greet()
28

Introduction to Opps in python

▪ Class and Instance Variables ▪ class Person:


▪ All instances of a class count = 0 # This is a class variable
exchange class variables. def __init__(self, name, age):
self.name = name # This is an
▪ They function independently of
instance variable
any class methods and may be
self.age = age
accessed through the use of
Person.count += 1 # Accessing the
the class name.
class variable using the name of the
class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print(Person.count)
▪ Output: 2
29

Introduction to Opps in python

▪ Python Constructor ▪ Constructors can be of two types.


▪ A constructor is a special type of ╺ Parameterized Constructor
method (function) which is used to ╺ Non-parameterized Constructor
initialize the instance members of ▪ Constructor definition is executed when
the class. we create the object of this class.
▪ In C++ or Java, the constructor has ▪ Constructors also verify that there are
the same name as its class, but it enough resources for the object to
treats constructor differently in perform any start-up task.
Python.
▪ It is used to create an object.
30

Introduction to Opps in python

Creating the constructor in python emp1.display()


class Employee: emp2.display()
def __init__(self, name, id): ▪ Output:
self.id = id ID: 101
self.name = name Name: John
def display(self): ID: 102
print("ID: %d \nName: %s" % (self.id, Name: David
self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
31

Introduction to Opps in python

▪ Python Non-Parameterized def show(self,name):


Constructor print("Hello",name)
class Student: student = Student()
# Constructor - non parameterized student.show("John")
def __init__(self):
print("This is non parametrized
constructor")

32

Introduction to Opps in python

▪ Python Parameterized def show(self):


Constructor print("Hello",self.name)
class Student:
student = Student("John")
def __init__(self, name):
student.show()
print("This is
parametrized ▪ Output:
This is parametrized constructor
constructor") Hello John
self.name = name
33

Introduction to Opps in python

▪ Python Default Constructor ▪ Output:


class Student: ▪ 101 Joseph
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.na
me)
st = Student()
st.display()
34

Introduction to Opps in python

▪ More than One Constructor in st = Student()


Single class ▪ Output:
class Student:
▪ The Second Constructor
def __init__(self):
print("The First
Constructor")
def __init__(self):
print("The second
contructor")
35

Introduction to Opps in python

▪ Python Inheritance ▪ A child class can also provide its specific


implementation to the functions of the
▪ Inheritance is an important aspect of the
parent class.
object-oriented paradigm. Inheritance
provides code reusability to the program ▪ In python, a derived class can inherit base
because we can use an existing class to class by just mentioning the base in the
create a new class instead of creating it bracket after the derived class name.
from scratch. Consider the following syntax to inherit a
base class into the derived class.
▪ In inheritance, the child class acquires the
properties and can access all the data
members and functions defined in the
parent class.
36

Introduction to Opps in python

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

Introduction to Opps in python

▪ Python Multi-Level inheritance


▪ Multi-Level inheritance is possible in
python like other object-oriented
languages.
▪ Multi-level inheritance is archived
when a derived class inherits another
derived class.
▪ There is no limit on the number of
levels up to which, the multi-level
inheritance is archived in python.
38

Introduction to Opps in python

▪ Syntax class Animal:


def speak(self):
class class1:
print("Animal Speaking")
<class-suite> class Dog(Animal):

class class2(class1): def bark(self):


print("dog barking")
<class suite>
class DogChild(Dog):
class class3(class2): def eat(self):

<class suite> print("Eating bread...")


d = DogChild()
Output: d.bark()
dog barking Animal Speaking Eating bread...
d.speak()
d.eat()
39

Introduction to Opps in python

▪ Python Multiple inheritance ▪ Syntax


▪ Python provides us the flexibility class Base1:

to inherit multiple base classes <class-suite>

in the child class. class Base2:


<class-suite> ……..
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>
40

Introduction to Opps in python

class Calculation1: d = Derived()


def Summation(self,a,b): print(d.Summation(10,20))
return a+b; print(d.Multiplication(10,20))
class Calculation2: print(d.Divide(10,20))
def Multiplication(self,a,b):
return a*b; Output:
class Derived(Calculation1,Calculation2): 30 200 0.5

def Divide(self,a,b):
return a/b;
41

Introduction to Opps in python

▪ Python Encapsulation ▪ This also helps to achieve data


▪ Encapsulation is one of the key features of hiding.
object-oriented programming. ▪ In Python, we denote private
▪ Encapsulation refers to the bundling of attributes using underscore as the
attributes and methods inside a single prefix i.e single _ or double __. For
class. example,

▪ It prevents outer classes from accessing


and changing attributes and methods of a
class.
42

Introduction to Opps in python

class Computer: def setMaxPrice(self, price):


def __init__(self): self.__maxprice = price
self.__maxprice = 900 c = Computer()
c.sell()
Output:
def sell(self): Selling Price: 900
Selling Price: 900
print("Selling Price: c.__maxprice = 1000 Selling Price: 1000
{}".format(self.__maxprice)) c.sell()

c.setMaxPrice(1000)
c.sell()
43

Introduction to Opps in python

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

Introduction to Opps in python

▪ # create an object of Square Output


Rendering Square... Rendering
▪ s1 = Square() Circle...
▪ s1.render()

▪ # create an object of Circle


▪ c1 = Circle()
▪ c1.render()
45

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

Introduction to Opps in python

▪ Abstraction ▪ The classes with one or more


▪ Abstraction allows us to focus abstract methods are known
on what the object does as Abstract classes.
instead of how it does it. Some ▪ Whereas an abstract method is
of the features of abstraction declared but does not hold an
are: implementation.
▪ It only showcases the
necessary information to the
user.
47

Introduction to Opps in python

from abc import ABC, abstractmethod


▪ Benefits of Abstraction class Car(ABC):
▪ Abstraction provides several def mileage(self):
benefits, such as:
pass
▪ It helps in minimizing the
class Tesla(Car):
complexity of the code written.
def mileage(self):
▪ It makes the code reusable.
print("The mileage is 30kmph")
▪ It enhances security because it
hides sensitive information class Suzuki(Car):
from the user. def mileage(self):
print("The mileage is 25kmph ")
48

Introduction to Opps in python

class Duster(Car): t= Tesla ()


def mileage(self): t.mileage()
print("The mileage is 24kmph ") r = Renault() Output:

r.mileage() The mileage is 30kmph


The mileage is 27kmph
class Renault(Car): s = Suzuki() The mileage is 25kmph
def mileage(self): s.mileage() The mileage is 24kmph

print("The mileage is 27kmph ") d = Duster()


d.mileage()
49


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.

You might also like