Unit 3
Unit 3
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.
• 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
•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.
•For instance,
• 5 is an integer
•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
• 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++"]
• print(languages[0]) # Python
• 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.
• print(languages[-1]) # C++
• print(languages[-3]) # Python
• Slicing of a List
• In Python, it is possible to access a portion of a list using the slicing operator : .
• my_list = ['p','r','o','g','r','a','m','i','z']
• print(my_list[2:5])
• print(my_list[5:])
• 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
extend() add all the items of an iterable to the end of the list
•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.
• # using + operator
• result = greet + name
• print(result)
• # 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
•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")
• letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
•my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') •print(my_tuple[7:]) # prints ('i', 'z')
•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.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++')
• country_capitals = {
• "Italy": "Rome",
• "England": "London"
• }
• 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 = {
• "Italy": "Rome",
• "England": "London"
• }
• 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 = {
• "Italy": "Naples",
• "England": "London"
•Add Items to a Dictionary • # add an item with "Germany" as key and
a value to a new key (that does not exist in the • country_capitals["Germany"] = "Berlin"
dictionary). For example, • print(country_capitals)
• country_capitals = {
• "Italy": "Naples"
• }
•Remove Dictionary Items • # delete item having "United States" key
• "Italy": "Naples"
• }
•If we need to remove all items from the dictionary at once, we can use the clear() method.
• country_capitals = {
• "Italy": "Naples"
• }
• country_capitals.clear()
• print(country_capitals) # {}
Function Description
• if...else statement
• if...elif...else statement
•if statement
• The syntax of if statement in Python is:
• However, if we need to make a choice between more than two alternatives, then we use the if...elif...else
statement.
• In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc.
• 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.
• If the condition evaluates to True, the code inside the while loop is executed.
• 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.
•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:
• 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:
• 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.
•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:
•start.select_difficulty(2)
File Handling
•Python allows reading and writing to files using the 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.
• 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.
•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.
•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.
• 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.
import json
Parse JSON in Python(Decoding)
•The json module makes it easy to parse JSON strings and files containing JSON object.
•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 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.
• 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')
•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.
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:
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.
• 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.