0% found this document useful (0 votes)
12 views

Unit 3

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, emphasizing code readability and efficiency. It supports multiple programming paradigms, is easy to learn, and has broad library support for various applications. Key features include its interpreted nature, data types like lists and tuples, and built-in methods for data manipulation.

Uploaded by

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

Unit 3

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, emphasizing code readability and efficiency. It supports multiple programming paradigms, is easy to learn, and has broad library support for various applications. Key features include its interpreted nature, data types like lists and tuples, and built-in methods for data manipulation.

Uploaded by

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

Introduction to

Python
UNIT 3
Introduction
•Python is a widely used general-purpose, high level programming language.

•It was created by Guido van Rossum in 1991 and further developed by the Python Software
Foundation.

•It was designed with an emphasis on code readability, and its syntax allows programmers to
express their concepts in fewer lines of code.

•Python is a programming language that lets you work quickly and integrate systems more
efficiently. There are two major Python versions: Python 2 and Python 3.
Language Features
• Multi-paradigm programming language
• Python supports more than one programming paradigms including object-oriented programming and structured
programming

• Interpreted Language
• Python is an interpreted language and does not require an explicit compilation step. The Python interpreter executes
the program source code directly, statement by statement, as a processor or scripting engine does.

• Interactive Language
• Python provides an interactive mode in which the user can submit commands at the Python prompt and interact with
the interpreter directly.
•Easy-to-learn, read and maintain
• Python is a minimalistic language with relatively few keywords, uses English keywords and has fewer
syntactical constructions as compared to other languages.

• Reading Python programs is easy with pseudo-code like constructs, Python is easy to learn yet an
extremely powerful language for a wide range of applications.

• Due to its simplicity, programs written in Python are generally easy to maintain.
• Object and Procedure Oriented
• Python supports both procedure-oriented programming and object-oriented programming.

• Procedure oriented paradigm allows programs to be written around procedures or functions that allow reuse
of code.

• Object oriented paradigm allows programs to be written around objects that include both data and
functionality.

• Extendable
• Python is an extendable language and allows integration of low-level modules written in languages such as
C/C++. This is useful when you want to speed up a critical portion of a program.
•Scalable
• Due to the minimalistic nature of Python, it provides a manageable structure for large programs.

•Broad Library Support


• Python has a broad library support and works on various platforms such as Windows, Linux, Mac, etc.

• There are a large number of Python packages available for various applications such as machine
learning, image processing, network programming, cryptography, etc.
•Portable
• Since Python is an interpreted language, programmers do not have to worry about compilation, linking
and loading of programs.

• Python programs can be directly executed from source code and copied from one machine to other
without worrying about portability.

• The Python interpreter converts the source code to an intermediate form called byte codes and then
translates this into the native language of your specific system and then runs it.
Python Data Types & Data
Structures
•Data types specify the type of data that can be stored inside a variable.
Data Types Classes Description

Numeric int, float, complex holds numeric values

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

Mapping dict holds data in key-value pair form

Boolean bool holds either True or False

Set set, frozeenset hold collection of unique items


Numeric
•The number data types are used to store the numeric values.

•Python supports integers, floating-point numbers and complex numbers. They are defined as
int, float, and complex classes in Python.
• int - holds signed integers of non-limited length.

• float - holds floating decimal points and it's accurate up to 15 decimal places.

• complex - holds complex numbers.


•Integers and floating points are separated by the presence or absence of a decimal point.

•For instance,
• 5 is an integer

• 5.42 is a floating-point number.

•Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary
part.

•We can use the type() function to know which class a variable or a value belongs to.
Example
•num1 = 5
•print(num1, 'is of type', type(num1))

•num2 = 5.42
•print(num2, 'is of type', type(num2))

•num3 = 8+2j
•print(num3, 'is of type', type(num3))
Type Conversion in Python
•Type conversion is the process of converting one type of number into another.

•Operations like addition, subtraction convert integers to float implicitly (automatically), if one of
the operands is float.
• Example : print(1 + 2.0) # prints 3.0

•Explicit Type Conversion


• We can also use built-in functions like int(), float() and complex() to convert between types explicitly.
These functions can even convert from strings.
• num1 = int(2.3)
• print(num1) # prints 2

• num2 = int(-2.8)
• print(num2) # prints -2

• num3 = float(5)
• print(num3) # prints 5.0

• num4 = complex('3+5j')
• print(num4) # prints (3 + 5j)
List
•In Python, lists are used to store multiple data at once.
•We create a list by placing elements inside [], separated by commas.
• Example
• ages = [19, 26, 23]
• print(ages)
• # Output: [19, 26, 23]

•A list can
• store elements of different types (integer, float, string, etc.)
• store duplicate elements
•Access List Elements
• In Python, lists are ordered and each item in a list is associated with a number. The number is known as
a list index.

• The index of the first element is 0, second element is 1 and so on. For example,
• languages = ["Python", "Swift", "C++"]

• # access item at index 0

• print(languages[0]) # Python

• # access item at index 2

• print(languages[2]) # C++
•Negative Indexing in Python
• Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.

• languages = ["Python", "Swift", "C++"]

• # access item at index 2

• print(languages[-1]) # C++

• # access item at index 0

• print(languages[-3]) # Python
• Slicing of a List
• In Python, it is possible to access a portion of a list using the slicing operator : .

• # List slicing in Python

• my_list = ['p','r','o','g','r','a','m','i','z']

• # items from index 2 to index 4

• print(my_list[2:5])

• # items from index 5 to end

• print(my_list[5:])

• # items beginning to end

• print(my_list[:])
•Add Elements to a List
• Lists are mutable (changeable). Meaning we can add and remove elements from a list.
• Python list provides different methods to add items to a list.

•Using append()
• The append() method adds an item at the end of the list. For example,
• numbers = [21, 34, 54, 12]
• print("Before Append:", numbers)
• # using append method
• numbers.append(32)
• print("After Append:", numbers)
•Using extend()
• We use the extend() method to add all the items of a list to the end of the list. For example,
• numbers = [1, 3, 5]
• even_numbers = [4, 6, 8]
• # add elements of even_numbers to the numbers list
• numbers.extend(even_numbers)
• print("List after append:", numbers)
•Using insert()
• We use the insert() method to add an element at the specified index.
• numbers = [10, 30, 40]
• # insert an element at index 1 (second position)
• numbers.insert(1, 20)
• print(numbers) # [10, 20, 30, 40]
•Change List Items
• Python lists are mutable. Meaning lists are changeable.
• And we can change items of a list by assigning new values using the = operator.
• For example,
• languages = ['Python', 'Swift', 'C++']
• # changing the third item to 'C'
• languages[2] = 'C'
• print(languages) # ['Python', 'Swift', 'C']
• Remove an Item From a List
• Using del Statement
• In Python we can use the del statement to remove one or more items from a list. For example,
• languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
• # deleting the second item
• del languages[1]
• print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']
• # deleting the last item
• del languages[-1]
• print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']
• # delete the first two items
• del languages[0 : 2]
• print(languages) # ['C', 'Java', 'Rust']
•Using remove()
• We can also use the remove() method to delete a list item. For example,
• languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
• # remove 'Python' from the list
• languages.remove('Python')
• print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']
Method Description

append() add an item to the end of the list

extend() add all the items of an iterable to the end of the list

insert() inserts an item at the specified index

remove() removes item present at the given index

pop() returns and removes item present at the given index

clear() removes all items from the list

index() returns the index of the first matched item

count() returns the count of the specified item in the list

sort() sort the list in ascending/descending order

reverse() reverses the item of the list

copy() returns the shallow copy of the list


Strings
•String is a sequence of characters. For example, "hello" is a string containing a sequence of
characters 'h', 'e', 'l', 'l', and 'o'.
•We use single quotes or double quotes to represent a string in Python. For example,
•# create string type variables
•name = "Python"
•print(name)
•message = "I love Python."
•print(message)
•Access String Characters in Python
• We can access the characters in a string in three ways.

•Indexing: One way is to treat strings as a list and use index values. For example,
• greet = 'hello'
• # access 1st index element
• print(greet[1]) # "e“

•Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For
example,
• greet = 'hello'
• # access 4th last element
• print(greet[-4]) # "e"
•Slicing: Access a range of characters in a string by using the slicing operator colon : . For
example,
• greet = 'Hello'
• # access character from 1st index to 3rd index
• print(greet[1:4]) # "ell“
•Multiline String:
• We can also create a multiline string in Python. For this, we use triple double quotes """ or triple single
quotes '''. For example,
• # multiline string
• message = """
• Never gonna give you up
• Never gonna let you down
• """
• print(message)
•String Operations
• There are many operations that can be performed with strings which makes it one of the most used data
types in Python.

•Compare Two Strings


• We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False. For example,
• str1 = "Hello, world!"
• str2 = "I love Python."
• str3 = "Hello, world!"
• # compare str1 and str2
• print(str1 == str2)
• # compare str1 and str3
• print(str1 == str3)
•Join Two or More Strings
• In Python, we can join (concatenate) two or more strings using the + operator.
• greet = "Hello, "
• name = "Jack“

• # using + operator
• result = greet + name
• print(result)

• # Output: Hello, Jack


•String Length
• In Python, we use the len() method to find the length of a string. For example,
• greet = 'Hello'

• # count length of greet string


• print(len(greet))

• # Output: 5

•We can test if a substring exists within a string or not, using the keyword in.
• print('a' in 'program') # True
• print('at' not in 'battle') False
Methods Description

upper() converts the string to uppercase

lower() converts the string to lowercase

partition() returns a tuple

replace() replaces substring inside

find() returns the index of first occurrence of substring

rstrip() removes trailing characters

split() splits string from left

startswith() checks if string starts with the specified string

isnumeric() checks numeric characters

index() returns index of substring


Tuple
•A tuple in Python is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas we can change the elements of a list.

•Creating a Tuple
• A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to use them.

• A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
•# Different types of tuples •# tuple with mixed datatypes
•# Empty tuple •my_tuple = (1, "Hello", 3.4)
•my_tuple = () •print(my_tuple)
•print(my_tuple) •# nested tuple
•# Tuple having integers •my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
•my_tuple = (1, 2, 3) •print(my_tuple)
•print(my_tuple)
•Create a Tuple With one Element
• In Python, creating a tuple with one element is a • # Creating a tuple having one element
bit tricky. Having one element within parentheses • var2 = ("hello",)
is not enough.
• print(type(var2)) # <class 'tuple'>
• We will need a trailing comma to indicate that it is
• # Parentheses is optional
a tuple,
• var3 = "hello",
• var1 = ("hello")
• print(type(var3)) # <class 'tuple'>
• print(type(var1)) # <class 'str’>
•Access Tuple Elements

•Indexing
• # accessing tuple elements using indexing

• letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

• print(letters[0]) # prints "p"

• print(letters[5]) # prints "a"


•Negative Indexing
• # accessing tuple elements using negative indexing

• letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

• print(letters[-1]) # prints 'z'

• print(letters[-3]) # prints 'm'


•Slicing
•We can access a range of items in a tuple by using the slicing operator colon : .

•# accessing tuple elements using slicing •# elements 8th to end

•my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') •print(my_tuple[7:]) # prints ('i', 'z')

•# elements 2nd to 4th index •# elements beginning to end

•print(my_tuple[1:4]) # prints ('r', 'o', 'g') •print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a',
'm', 'i', 'z')
•# elements beginning to 2nd

•print(my_tuple[:-7]) # prints ('p', 'r')


• Tuple Methods
• In Python ,methods that add items or remove items are not available with tuple. Only the following two methods are available.

• my_tuple = ('a', 'p', 'p', 'l', 'e',)

• print(my_tuple.count('p')) # prints 2

• print(my_tuple.index('l')) # prints 3

• We use the in keyword to check if an item exists in the tuple or not. For example,
• languages = ('Python', 'Swift', 'C++')

• print('C' in languages) # False

• print('Python' in languages) # True


Dictionary
•In Python, a dictionary is a collection that allows us to store data in key-value pairs.
•Create a Dictionary
• We create dictionaries by placing key:value pairs inside curly brackets {}, separated by commas. For
example,
• # creating a dictionary
• country_capitals = {
• "United States": "Washington D.C.",
• "Italy": "Rome",
• "England": "London"
• }
• # printing the dictionary
• print(country_capitals)
•# Valid dictionary •# Invalid dictionary
•my_dict = { •# Error: using a list as a key is not allowed
• 1: "Hello", •my_dict = {
• (1, 2): "Hello Hi", • 1: "Hello",
• 3: [1, 2, 3] • [1, 2]: "Hello Hi",
•} •}
•print(my_dict) •print(my_dict)
•Dictionary Length
• We can get the size of a dictionary by using the len() function.

• country_capitals = {

• "United States": "Washington D.C.",

• "Italy": "Rome",

• "England": "London"

• }

• # get dictionary's length

• print(len(country_capitals)) # 3
• Access Dictionary Items
• We can access the value of a dictionary item by placing the key inside square brackets.

• country_capitals = {

• "United States": "Washington D.C.",

• "Italy": "Rome",

• "England": "London"

• }

• print(country_capitals["United States"]) # Washington D.C.

• print(country_capitals["England"]) # London
•Change Dictionary Items • }

• Python dictionaries are mutable (changeable). We • # change the value of "Italy" key to "Rome"
can change the value of a dictionary element by • country_capitals["Italy"] = "Rome"
referring to its key. For example,
• print(country_capitals)
• country_capitals = {

• "United States": "Washington D.C.,

• "Italy": "Naples",

• "England": "London"
•Add Items to a Dictionary • # add an item with "Germany" as key and

• We can add an item to the dictionary by assigning "Berlin" as its value

a value to a new key (that does not exist in the • country_capitals["Germany"] = "Berlin"
dictionary). For example, • print(country_capitals)
• country_capitals = {

• "United States": "Washington D.C.",

• "Italy": "Naples"

• }
•Remove Dictionary Items • # delete item having "United States" key

• We use the del statement to remove an element • del country_capitals["United States"]


from the dictionary. For example, • print(country_capitals)
• country_capitals = {

• "United States": "Washington D.C.",

• "Italy": "Naples"

• }
•If we need to remove all items from the dictionary at once, we can use the clear() method.
• country_capitals = {

• "United States": "Washington D.C.",

• "Italy": "Naples"

• }

• country_capitals.clear()

• print(country_capitals) # {}
Function Description

pop() Remove the item with the specified key.

update() Add or change dictionary items.

clear() Remove all the items from the dictionary.

keys() Returns all the dictionary's keys.

values() Returns all the dictionary's values.

get() Returns the value of the specified key.

Returns the last inserted key and value as a


popitem()
tuple.

copy() Returns a copy of the dictionary.


Control of Flow
•if...else Statement
• we use the if statement to run a block code only when a certain condition is met.

•In Python, there are three forms of the if...else statement.


• if statement

• if...else statement

• if...elif...else statement
•if statement
• The syntax of if statement in Python is:

• The if statement evaluates condition.

• If condition is evaluated to True, the code inside the body of if is executed.

• If condition is evaluated to False, the code inside the body of if is skipped.


•Example:
•if...else Statement
• An if statement can have an optional else clause.

• The syntax of if...else statement is:


•The if...else statement evaluates the given condition:

•If the condition evaluates to True,


• the code inside if is executed

• the code inside else is skipped

•If the condition evaluates to False,


• the code inside else is executed

• the code inside if is skipped


Example:
•if...elif...else Statement
• The if...else statement is used to execute a block of code among two alternatives.

• However, if we need to make a choice between more than two alternatives, then we use the if...elif...else
statement.

• The syntax of the if...elif...else statement is:


•If condition1 evaluates to true, code block 1 is executed.

•If condition1 evaluates to false, then condition2 is evaluated.


• If condition2 is true, code block 2 is executed.

• If condition2 is false, code block 3 is executed.


Example:
•Nested if statements
• We can also use an if statement inside of an if statement. This is known as a nested if statement.

• The syntax of nested if statement is:


Example:
•for Loop
• loops are used to repeat a block of code.

• In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc.

• The syntax of a for loop is:

• Here, val accesses each item of sequence on each iteration. The loop continues until we reach the last
item in the sequence.
•Example:
•Example: Loop Through a String
•for Loop with Python range()
• A range is a series of values between two numeric intervals.

• We use Python's built-in function range() to define a range of values. For example,
• for loop with else
• A for loop can have an optional else block. The else part is executed when the loop is exhausted (after the loop
iterates through every item of a sequence). For example,

• Here, the for loop prints all the items of the digits list. When the loop finishes, it executes the else block and
prints No items left.
•while Loop

•while loop is used to run a block code until a certain condition is met.

•The syntax of while loop is:


• A while loop evaluates the condition

• If the condition evaluates to True, the code inside the while loop is executed.

• condition is evaluated again.

• This process continues until the condition is False.

• When condition evaluates to False, the loop stops.


Example:
Example:
•While loop with else
• In Python, a while loop may have an optional else block.

• Here, the else part is executed after the condition of the loop evaluates to False.
•break Statement
• The break statement is used to terminate the loop immediately when it is encountered.
•break Statement with for Loop
• We can use the break statement with the for loop to terminate the loop when a certain condition is met.
For example,
•break Statement with while Loop
• We can also terminate the while loop using the break statement. For example,
•continue Statement
• The continue statement is used to skip the current iteration of the loop and the control flow of the
program goes to the next iteration.
•continue Statement with for Loop
• We can use the continue statement with the for loop to skip the current iteration of the loop. Then the
control of the program jumps to the next iteration. For example,
•continue Statement with while Loop
• In Python, we can also skip the current iteration of the while loop using the continue statement. For
example,
•pass Statement
• In Python programming, the pass statement is a
null statement which can be used as a placeholder
for future code.

• Suppose we have a loop or a function that is not


• Here, we have used the pass statement inside the
implemented yet, but we want to implement it in
if statement.
the future. In such cases, we can use the pass
• nothing happens when the pass is executed. It
statement.
results in no operation (NOP).
Functions
•Functions
• A function is a block of code that performs a specific task.

•Types of function
• There are two types of function in Python programming:

• Standard library functions - These are built-in functions in Python that are available to use.

• User-defined functions - We can create our own functions based on our requirements.
•Function Declaration
• The syntax to declare a function is:

• def - keyword used to declare a function

• function_name - any name given to the function

• arguments - any value passed to function

• return (optional) - returns value from a function


•Calling a Function
•Function Arguments
• An argument is a value that is accepted by a function. For example,
•return Statement:
• A function may or may not return a value. If we want our function to return some value to a function
call, we use the return statement. For example,
•Benefits of Using Functions
• Code Reusable - We can use the same function multiple times in our program which makes our code
reusable.

• Code Readability - Functions help us break our code into chunks to make our program readable and
easy to understand.
•Recursive Function
• In Python, we know that a function can call other functions.

• It is even possible for the function to call itself. These types of construct are termed as recursive
functions.

• The following image shows the working of a recursive function called recurse.
•Example:
•Lambda/Anonymous Function
• In Python, a lambda function is a special type of function without the function name. For example,
•lambda Function Declaration
• We use the lambda keyword instead of def to create a lambda function. Here's the syntax to declare the
lambda function:

• argument(s) - any value passed to the lambda function

• expression - expression is executed and returned


•Example:
•lambda Function with an Argument
• Similar to normal functions, the lambda function can also accept arguments. For example,
Modules
• Module is a file that contains code to perform a specific task.

• A module may contain variables, functions, classes etc.

• To create a module. Type the following and save it as example.py.

• Here, we have defined a function add() inside a module named example.


•Import modules in Python
• We can import the definitions inside a module to another module or the interactive interpreter in Python.

• We use the import keyword to do this. To import our previously defined module example, we type the
following in the Python prompt.

• Using the module name we can access the function using the dot . operator.

• example.add(4,5) #returns 9
•Python Standard Library Modules
• The Python standard library contains over 200 modules. We can import a module according to our needs.

• Suppose we want to get the value of pi, first we import the math module and use math.pi. For example,
•import with Renaming
• In Python, we can also import a module by renaming it. For example,
•from...import statement
• We can import specific names from a module without importing the module as a whole. For example,
•Import all names
• In Python, we can import all names(definitions) from a module using the following construct:
•The dir() built-in function
• In Python, we can use the dir() function to list all
the function names in a module.

• For example, earlier we have defined a function


add() in the module example.

• We can use dir in example module in the


following way:
Package
•A package is a container that contains various functions to perform specific tasks.

•While working on big projects, we have to deal with a large amount of code, and writing
everything together in the same file will make our code look messy.

•Instead, we can separate our code into multiple files by keeping the related code together in
packages.

•Now, we can use the package whenever we need it in our projects. This way we can also reuse
our code.
Package Model Structure in
Python
•Importing module from a package
• In Python, we can import modules from packages using the dot (.) operator.

• For example, if we want to import the start module in the above example, it can be done as follows:

• import Game.Level.start
• Now, if this module contains a function named select_difficulty(), we must use the full name to
reference it.

• Game.Level.start.select_difficulty(2)
•Import Without Package Prefix
• If the above construct seems lengthy, we can import the module without the package prefix as follows:

•from Game.Level import start


• We can now call the function simply as follows:

•start.select_difficulty(2)
File Handling
•Python allows reading and writing to files using the file object.

•The open(filename,mode) function is used to get a file object.

•The mode can be read (r), write (w), append (a), read and write (r+ or w+), read-binary (rb),
write-binary (wb).

•After the file contents have been read the close function is called which closes the file object.
Reading a file
Reading file contents line by line
Reading lines in loop
Reading certain no. of bytes
from a file
Seeking to a certain position in a
file
Writing to the file
Appending to a file
Classes
•Python is an object oriented programming language.
•Almost everything in Python is an object, with its properties and methods.
•A Class is like an object constructor, or a "blueprint" for creating objects.
The __init__() Function
•All classes have a function called __init__(), which is always executed when the class is being
initiated.
•Use the __init__() function to assign values to object properties
The __str__() Function
•The __str__() function controls what should be returned when the class object is represented as a
string.
•If the __str__() function is not set, the string representation of the object is returned:
Object Methods
•Objects can also contain methods. Methods in objects are functions that belong to the object.
•Let us create a method in the Person class:
The self Parameter
•The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
•It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
The pass Statement
•class definitions cannot be empty, but for some reason have a class definition with no content,
put in the pass statement to avoid getting an error.
Python Inheritance
•Inheritance allows us to define a class that inherits all the methods and properties from another
class.
•Parent class is the class being inherited from, also called base class.
•Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Create a Child Class

• Now the Student class has the same properties and methods as the Person class.
• Add the __init__() Function
• So far we have created a child class that inherits the properties and methods from its parent.
• We want to add the __init__() function to the child class (instead of the pass keyword).

• When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.
• Use the super() Function
• Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:
Exceptions
•An exception is an unexpected event that occurs during program execution. Errors that occur at
runtime (after passing the syntax test) are called exceptions or logical errors.

•For instance, they occur when we


• try to open a file(for reading) that does not exist (FileNotFoundError)

• try to divide a number by zero (ZeroDivisionError)

• try to import a module that does not exist (ImportError) and so on.

•Whenever these types of runtime errors occur, Python creates an exception object. If not handled
properly, it prints a traceback to that error along with some details about why that error occurred.
Example
Built-in Exceptions
•Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.

•We can view all the built-in exceptions using the built-in local() function

•print(dir(locals()['__builtins__’]))

•locals()['__builtins__'] will return a module of built-in exceptions, functions, and attributes and
dir allows us to list these attributes as strings.
•AttributeError: Raised when attribute assignment or reference fails.

•EOFError: Raised when the input() function hits end-of-file condition.

•FloatingPointError: Raised when a floating point operation fails.

•ImportError: Raised when the imported module is not found.

•IndexError: Raised when the index of a sequence is out of range.


•KeyError: Raised when a key is not found in a dictionary.

•OverflowError: Raised when the result of an arithmetic operation is too large to be represented.

•RuntimeError: Raised when an error does not fall under any other category.

•StopIteration: Raised by next() function to indicate that there is no further item to be returned by
iterator.

•SyntaxError: Raised by parser when syntax error is encountered.

•IndentationError: Raised when there is incorrect indentation.


Exception Handling
•Exceptions abnormally terminate the execution of a program.

•To avoid this it is important to handle exceptions. In Python, we use the try...except block

•try...except Block
• The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block:
Example: Exception Handling
Using try...except
Catching Specific Exceptions in
Python
•For each try block, there can be zero or more
except blocks. Multiple except blocks allow us
to handle each exception differently.

•The argument type of each except block


indicates the type of exception that can be
handled by it.
Python try with else clause
•In some situations, we might want to run a
certain block of code if the code block inside
try runs without any errors.

•For these cases, you can use the optional else


keyword with the try statement.
Python try...finally
•In Python, the finally block is always executed
no matter whether there is an exception or not.

•The finally block is optional. And, for each try


block, there can be only one finally block.
Defining Custom Exceptions
•In Python, we can define custom exceptions by
creating a new class that is derived from the
built-in Exception class.

•Here's the syntax to define custom exceptions:


Python Packages
•Python packages :
• JSON

• XML

• HTTPLib

• URLLib

• SMTPLib
JSON
• JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data.

• JSON is a popular data format used for representing structured data. It's common to transmit and receive
data between a server and web application in JSON format.

• JSON is "self-describing" and easy to understand.

• JSON Syntax Rules


• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays
•In Python, JSON exists as a string. For example:

p = '{"name": "Bob", "languages": ["Python", "Java"]}'

•It's also common to store a JSON object in a file.

•Import json Module


• To work with JSON (string, or file containing JSON object), you can use Python's json module. You need
to import the module before you can use it.

import json
Parse JSON in Python(Decoding)
•The json module makes it easy to parse JSON strings and files containing JSON object.

•Example 1: Python JSON to dict


• You can parse a JSON string using json.loads() method. The method returns a dictionary.
•Example 2: Python read JSON file named data.

• You can use json.load() method to read a file


containing JSON object.

• Suppose, you have a file named person.json


which contains a JSON object.

• Here, we have used the open() function to read


the json file. Then, the file is parsed using
json.load() method which gives us a dictionary
Python Convert to JSON
string(Encoding)
•You can convert a dictionary to JSON string using json.dumps() method.

•Example 3: Convert dict to JSON


•Writing JSON to a file
• To write JSON to a file in Python, we can use
json.dump() method.

• In the program, we have opened a file named


person.txt in writing mode using 'w'. If the file
doesn't exist, it will be created. Then,
json.dump() transforms person_dict to a JSON
string which will be saved in the person.txt file.
Python pretty print JSON
•To analyze and debug JSON data, we may need to print it in a more readable format.

•This can be done by passing additional parameters indent and sort_keys to json.dumps() and
json.dump() method.
•In the program, we have used 4 spaces for
indentation. And, the keys are sorted in
ascending order.

•The default value of indent is None. And, the


default value of sort_keys is False.
XML
•XML, or Extensible Markup Language, is a markup-language that is commonly used to
structure, store, and transfer data between systems.

•The XML Modules


• The minidom, or Minimal DOM Implementation, is a simplified implementation of the Document
Object Model (DOM). The DOM is an application programming interface that treats XML as a tree
structure, where each node in the tree is an object.

• The ElementTree module provides a more "Pythonic" interface to handling XML and is a good option
for those not familiar with the DOM.
•XML File Example

•We will be using the following XML file, which we will save as "items.xml":
• <data>
• <items>
• <item name="item1">item1abc</item>
• <item name="item2">item2abc</item>
• </items>
• </data>
Reading XML Documents
• Using minidom

• In order to parse an XML document using minidom, we must first import it from the xml.dom module.
This module uses the parse function to create a DOM object from our XML file.

• The parse function has the following syntax:

• xml.dom.minidom.parse(filename_or_file)

• Here the file name can be a string containing the file path or a file-type object. The function returns a

document, which can be handled as an XML type. Thus, we can use the function
getElementByTagName() to find a specific tag.
•If we wanted to use an already-opened file, can just pass our file object to parse like so:

•datasource = open('items.xml')

•# parse an open file

•mydoc = parse(datasource)
•Using ElementTree
• ElementTree presents us with an very simple way to process XML files. As always, in order to use it we
must first import the module.

• Following the import, we create a tree structure with the parse function, and we obtain its root element.
Once we have access to the root node we can easily traverse around the tree, because a tree is a
connected graph.

• Using ElementTree, and like the previous code example, we obtain the node attributes and text using the
objects related to each node.
Writing XML Documents
•Using ElementTree
• ElementTree is also great for writing data to XML files. The code below shows how to create an XML
file with the same structure as the file we used in the previous examples.

• The steps are:

1. Create an element, which will act as our root element. In our case the tag for this element is "data".

2. Once we have our root element, we can create sub-elements by using the SubElement function. This
function has the syntax:

• SubElement(parent, tag, attrib={}, **extra)


• Here parent is the parent node to connect to, attrib is a dictionary containing the element attributes, and
extra are additional keyword arguments. This function returns an element to us, which can be used to
attach other sub-elements, as we do in the following lines by passing items to the SubElement
constructor.

3. Although we can add our attributes with the SubElement function, we can also use the set()
function, as we do in the following code. The element text is created with the text property of the
Element object.

4. In the last 3 lines of the code below we create a string out of the XML tree, and we write that data to
a file we open.
• Executing this code will result in a
new file, "items2.xml", which should
be equivalent to the original
"items.xml" file, at least in terms of
the XML data structure.
Creating XML Sub-Elements
•Using ElementTree

•The ElementTree module has more than one way to add a new element.

•The first way by using the makeelement() function, which has the node name and a dictionary
with its attributes as parameters.

•The second way is through the SubElement() class, which takes in the parent element and a
dictionary of attributes as inputs.
Deleting XML Elements
•Using ElementTree

•The ElementTree module has the necessary functionality to delete node's attributes and sub-
elements.

•Deleting an attribute
• To remove a node's attribute we use the pop() function. The function applies to the attrib object
parameter. It specifies the name of the attribute and sets it to None.
•Deleting one sub-element
• One specific sub-element can be deleted using
the remove function. This function must specify
the node that we want to remove.
•Deleting all sub-elements
• The ElementTree module presents us with the
clear() function, which can be used to remove all
sub-elements of a given element.
HTTPLIb & URLLIb
•HTTPLib2 and URLLib2 are Python libraries used in network/internet programming.

•HTTPLib2 is an HTTP client library and URLLib2 is a library for fetching URLs.

•Box 6.40 shows an example of an HTTP GET request using the HTTPLib.

•The variable resp contains the response headers and content contains the content retrieved from
the URL.
•Box 6.41 shows an HTTP request example using URLLib2.

•A request object is created by calling urllib2.Request with the URL to fetch as input parameter.

•Then urllib2.urlopen is called with the request object which returns the response object for the
requested URL.

•The response object is read by calling read function.


SMTPLIb
• Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending email and routing e-mail
between mail servers. The Python smtplib module provides an SMTP client session object that can be used
to send email.

• Box 6.44 shows a Python example of sending email from a Gmail account.
• The string message contains the email message to be sent. To send email from a Gmail account the Gmail SMTP
server is specified in the server string.

• To send an email, first a connection is established with the SMTP server by calling smitplib.SMTP with the SMTP
server name and port. The user name and password provided are then used to login into the server. The email is then
sent by calling server.sendmail function with the from address, to address list and message as input parameters.

You might also like