PYTHON_UNIT-1_NOTES[1]
PYTHON_UNIT-1_NOTES[1]
PYTHON_UNIT-1_NOTES[1]
REGULATION R22
COURSE OBJECTIVES:
The main objectives of this course are to:
1. The course demonstrates an in-depth understanding of the Python language with basic syntax and
semantics.
2. To learn advanced Python programming features to develop GUI applications and access databases and
object-oriented concepts.
3. To introduce the libraries for python programming.
4. To introduce the basics of parallel computing and Memory IO communication in Python.
5. To Learn GPU programming and Parallel AI Computing.
COURSE OUTCOMES:
After the completion of the course, the student will be able to
CO1: Mastery of Python’s syntax and semantics for robust programming.
CO2: Proficiency in advanced Python for GUIs, databases and OOP.
CO3: Familiarity with essential Python libraries for diverse applications.
CO4: understanding of parallel computing basics and Memory IO communication.
CO5: Acquisition of skills in GPU programming and Parallel AI Computing.
TEXT BOOKS:
1. “Think Python: How to Think Like a Computer Scientist”, Allen B. Downey, 2nd edition,
Shroff/O’Reilly Publishers, 2016.
2.”An Introduction to Python”, Guido van Rossum and Fred L. Drake Jr – Network Theory Ltd.,2011.
3.Nelli, F.(2023). Parallel and high performance programming with Python: Unlock parallel and
concurrent programming in Python using multithreading, CUDA, Pytorch and DASK. Orange Education
Pvt.
Course Code L T P C
PYTHON PROGRAMMING
IT3305 3 0 2 4
COURSE OBJECTIVES:
1. The course demonstrates an in-depth understanding of the Python language with
basic syntax and semantics.
2. To learn advanced Python programming features to develop GUI applications
and access databases and object-oriented concepts.
3. To introduce the libraries for python programming.
4. To introduce the basics of parallel computing and Memory IO communication
in Python.
5. To Learn GPU programming and Parallel AI Computing.
6 Custom Classes and Inheritance: Experiment with custom class inheritance hierarchies to
understand the behavior of inherited methods and attributes.
7 Polymorphism Demonstration: Design experiments to demonstrate polymorphic behavior in
Python classes using method overriding and overloading.
8 Properties vs Direct Access: Compare the performance of accessing class attributes directly versus
using properties for data encapsulation.
9 Custom Collection Classes Evaluation: Implement and evaluate custom collection classes in
terms of performance and usability compared to built-in Python data structures.
10 Decorators Impact on Performance: Investigate the overhead introduced by decorators on
function execution time and memory consumption.
11 File Handling Efficiency Study: Compare the efficiency of reading and writing binary and text
data using different file handling techniques.
12 Structured Text File Parsing: Experiment with parsing CSV, XML, HTML, and JSON files to
understand their structure and performance implications.
13 Debugging and Testing Frameworks Comparison: Compare the effectiveness and ease of use of
different debugging and testing frameworks for Python.
14 Django Web Framework Usage: Develop a simple web application using Django and evaluate
its performance under various loads and scenarios.
TEXTBOOKS:
1. “Think Python: How to Think Like a Computer Scientist”, Allen B . Downey, 2ndedition,
Shroff/O‘Reilly Publishers, 2016.
2. “An Introduction to Python”, Guido van Rossum and Fred L. Drake Jr – Network Theory Ltd.,
2011.
3. Nelli, F. (2023). Parallel and high performance programming with Python: Unlock parallel and
concurrent programming in Python using multithreading, CUDA, Pytorch and DASK. Orange
Education Pvt.
REFERENCES:
1. “Introduction to Computation and Programming Using Python‘‘, John V Guttag Revised and
Expanded Edition, MIT Press, 2013
2. “Introduction to Programming in Python: An Inter-disciplinary Approach”, Robert Sedgewick,
Kevin Wayne, Robert Dondero, Pearson India Education Services Pvt. Ltd.,2016.
3. Exploring Python‖, Timothy A. Budd, Mc-Graw Hill Education (India) Private Ltd., 2015.
4. Fundamentals of Python: First Programs‖, Kenneth A. Lambert, CENGAGE Learning,2012.
UNIT I BASIC SYNTAX 9
Python Interpreter, Execution model, Interactive prompt and IDLE, Basic syntactical
structures, Identifiers and keywords, Basic data types – integers,, Booleans, float,
complex, Decimal, other standard library types, String type. String formatting, built-in
functions, simple programs. Sequence types – Lists, Tuples, Named tuples, Set types –
Sets, Frozen sets, Mapping types – Dictionaries, Default dictionaries, iterating
collections, Copying collections, Comprehensions, Generators, Control structures –
Conditional branching, Looping, Exception handling.
***********************************************************************************
1. PYTHON INTERPRETER
Python Interpreter
Interpreters
• Interpreters are the computer program that will convert the source code or an high
level language into intermediate code (machine level language). It is also called
translator in programming terminology.
• Interpreters executes each line of statements slowly. This process is called
Interpretation.
• For example Python is an interpreted language, PHP, Ruby, and JavaScript.
5
Working of Interpreter
Example: Here is the simple Python program that takes two inputs as a and b and prints
the sum in the third variable which is c. It follows sequential as well as functional
execution of programs
a=3
b=7
c=a+b
print( c ) #output 10
Output
10
Compiler Interpreter
It generates output in the form of .(exe) It does not generate any form of outputs.
6
Compiler Interpreter
In Python, the execution model refers to how Python interprets and executes your code.
Here are the key components of the Python execution model:
1. Source Code: Python programs are typically written in .py files, which contain the
source code written by the programmer.
2. Lexer and Parser: When you run a Python script or module, Python first processes the
source code using a lexer and a parser. The lexer breaks the code into tokens, and the
parser analyzes the structure according to the grammar rules of Python.
7
3. Abstract Syntax Tree (AST): After parsing, Python generates an Abstract Syntax Tree
(AST), which represents the syntactic structure of the code. The AST is a hierarchical
tree of nodes, each representing a syntactic construct like expressions, statements,
functions, etc.
4. Bytecode Compilation: Python bytecode is a low-level representation of the Python
source code. The AST is then compiled into bytecode instructions, which are platform-
independent and are executed by the Python Virtual Machine (PVM).
5. Python Virtual Machine (PVM): The PVM is the runtime engine that executes Python
bytecode. It includes the interpreter and various other components like memory manager,
import system, etc.
6. Dynamic Execution: Python is dynamically typed and executes code dynamically at
runtime. This means that variable types are determined during execution rather than at
compile time.
7. Execution of Statements and Expressions: Python executes statements and expressions
sequentially, one after another, following the control flow defined by constructs like
loops, conditionals, function calls, etc.
8. Memory Management: Python handles memory management automatically through a
mechanism called garbage collection. Objects are allocated in memory when they are
created and deallocated when no longer in use.
9. Import System: Python has a powerful import system that allows modules to be
imported into other modules or scripts. The import system manages the loading of
modules and ensures that modules are only imported once per interpreter session.
-----------------------------------------------------------x---------------------------------------------------
In Python, the interactive prompt and IDLE are two environments that facilitate writing and
executing Python code interactively.
Interactive Prompt (Python Shell)
The interactive prompt, often referred to as the Python shell or REPL (Read-Eval-Print
Loop), provides an interactive way to execute Python code line by line. Here’s how it
works:
• Usage: You can open the Python shell by typing python or python3 in your terminal or
command prompt (depending on your Python installation).
• Features:
o Immediate Feedback: Allows you to execute Python statements and expressions
interactively and see their results immediately.
o Exploration: Useful for exploring Python libraries, testing small code snippets, or
debugging.
8
o History: Stores the history of executed commands, which can be recalled using
the up and down arrow keys.
Example:
$ python
>>> 2 + 3
>>> math.sqrt(16)
4.0
>>>
---------------------------------------------------x---------------------------------------------------------
4. IDLE (Integrated Development and Learning Environment)
IDLE is an Integrated Development and Learning Environment for Python, which includes a
text editor and a Python shell. It's typically installed automatically when you install Python
from python.org.
• Features:
o Text Editor: Provides a built-in text editor where you can write and edit Python
scripts.
o Interactive Shell: Includes a Python shell similar to the interactive prompt, where
you can execute statements interactively.
o Syntax Highlighting: Highlights Python syntax to improve readability and help
catch syntax errors.
o Debugger: Basic debugging capabilities to step through code and inspect
variables.
• Usage: You can start IDLE by searching for it in your operating system's application
menu or by running idle or idle3 from the command line.
• Example: Here’s how IDLE looks when running:
9
In the IDLE shell, you can type Python statements directly and see the output immediately.
You can also create new Python files, edit them, and run them within the IDLE
environment.
Key Differences
• Usage Context: The interactive prompt is often used for quick experimentation and
testing, while IDLE provides a more comprehensive environment for writing, editing,
and running Python scripts.
• Features: IDLE offers additional features like a built-in text editor with syntax
highlighting and basic debugging capabilities, whereas the interactive prompt focuses
solely on immediate code execution and feedback.
Both the interactive prompt and IDLE are valuable tools depending on your needs: the
interactive prompt for quick tests and exploratory coding, and IDLE for more structured
script development with a richer set of editing and debugging features.
--------------------------------------------------------x------------------------------------------------------
In Python, syntactical structures refer to the fundamental elements and rules that define how
the language is structured and how code is written. Here are some of the basic syntactical
structures in Python:
1. Statements
A statement is a unit of code that Python can execute. It typically ends with a newline
character, but a single line can contain multiple statements separated by semicolons (;).
Examples:
10
2. Comments
Comments are annotations within the code that are ignored by the interpreter. They are used
to document code or temporarily disable code execution.
Examples:
Variables are used to store data values. Python is dynamically typed, so variables do not
need to be explicitly declared with their type.
Examples:
11
4. Control Flow
Control flow structures dictate the order in which statements are executed based on
conditions or loops.
Examples:
5. Functions
Functions are reusable blocks of code that perform a specific task. They can accept input
parameters and return output values. Examples:
12
6. Classes and Objects
Examples:
7. Indentation
Python uses indentation to define blocks of code (e.g., loops, functions, classes). It uses
consistent levels of indentation (usually 4 spaces per level) to indicate which statements are
grouped together. Example:
13
6. Identifiers and keywords
In Python, identifiers and keywords are fundamental concepts related to naming conventions
and reserved words. Here's an explanation of each:
Identifiers
Keywords Keywords are reserved words in Python that have special meanings and
cannot be used as identifiers. These words are part of the language syntax and serve specific
purposes in the code.
14
List of Python keywords:
Identifiers are essential for naming variables, functions, classes, and other objects in
Python code, while keywords are predefined and have specific meanings within the
language. Understanding these distinctions is crucial for writing clear, readable, and error-
free Python code.
----------------------------------------------------x----------------------------------------------------------
7. Basic data types – integers, Booleans, float, complex, Decimal
In Python, there are several basic data types that represent different kinds of values. Here's
an explanation of each:
1. Integers (int)
Integers represent whole numbers, positive or negative, without any decimal point. In
Python, integers can be of arbitrary precision, meaning they can be as large as the memory
allows.
Examples:
15
2. Booleans (bool)
Booleans represent truth values, either True or False. Booleans are used in conditional
expressions and control flow statements.
Examples:
3. Floats (float)
Floats represent numbers with a decimal point or numbers written in scientific notation
(using 'e' or 'E' to indicate powers of 10).
Examples:
Complex numbers are numbers with a real part and an imaginary part. They are written with
a "j" or "J" suffix for the imaginary part.
Examples:
16
5. Decimal (decimal.Decimal)
The Decimal data type is provided by the decimal module in Python and is used for decimal
floating-point arithmetic. It is particularly useful when precision is critical, such as in
financial applications.
Summary
-------------------------------------------------x-----------------------------------------------------------
A Python library is a collection of related modules. It contains bundles of code that can
be used repeatedly in different programs. It makes Python Programming simpler and
convenient for the programmer.
17
Python standard library
• The Python Standard Library contains the exact syntax, semantics, and tokens of
Python. It contains built-in modules that provide access to basic system functionality
like I/O and some other core modules.
• Most of the Python Libraries are written in the C programming language.
• The Python standard library consists of more than 200 core modules. All these work
together to make Python a high-level programming language.
• Python Standard Library plays a very important role. Without it, the programmers
can’t have access to the functionalities of Python.
• But other than this, there are several other libraries in Python that make a
programmer’s life easier. Let’s have a look at some of the commonly used libraries:
1. TensorFlow: This library was developed by Google in collaboration with the Brain
Team. It is an open-source library used for high-level computations. It is also used in
machine learning and deep learning algorithms. It contains a large number of tensor
operations. Researchers also use this Python library to solve complex computations in
Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why it is
used in data analysis. It is also an open-source library and plots high-defined figures
like pie charts, histograms, scatterplots, graphs, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly used
library. It is a popular machine learning library that supports large matrices and multi-
dimensional data. It consists of in-built mathematical functions for easy computations.
Even libraries like TensorFlow use Numpy internally to perform several operations on
tensors. Array Interface is one of the key features of this library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library
used for high-level scientific computations. This library is built over an extension of
Numpy. It works with Numpy to handle complex computations. While Numpy allows
sorting and indexing of array data, the numerical data code is stored in SciPy. It is also
widely used by application developers and engineers.
18
6. Scrapy: It is an open-source library that is used for extracting data from websites. It
provides very fast web crawling and high-level screen scraping. It can also be used for
data mining and automated testing of data.
8. PyGame: This library provides an easy interface to the Standard Directmedia Library
(SDL) platform-independent graphics, audio, and input libraries. It is used for
developing video games using computer graphics and audio libraries along with Python
programming language.
9. PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural networks.
10.PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning,
Artificial Intelligence, and Neural Networks library. It is an open-source library built
for beginners in the field of Machine Learning. It provides fast and easy-to-use
algorithms for machine learning tasks. It is so flexible and easily understandable and
that’s why is really helpful for developers that are new in research fields.
There are many more libraries in Python. We can use a suitable library for our purposes.
Hence, Python libraries play a very crucial role and are very helpful to the developers.
-------------------------------------------------x----------------------------------------------------------
9.String type
In Python, the str type represents strings of characters. Strings are sequences of Unicode
characters and are immutable, meaning they cannot be changed after they are created. Here
are some key features and operations related to Python's str type:
Creating Strings
Strings can be created using single quotes (') or double quotes ("). Triple quotes (''' or """)
are used for multiline strings.
19
Basic Operations
String Operators
Operator Description
not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified
string.
r/R It is used to specify the raw string. Raw strings are used in the
21
cases where we need to print the actual meaning of escape
characters such as "C://python". To define any string as a raw
string, the character r or R is followed by the string.
10.String formatting
• Python allows us to use the format specifiers used in C's printf statement.
• The format specifiers in Python are treated in the same way as they are treated in C.
• However, Python provides an additional operator %,which is used as an interface
between the format specifiers and their values.
• In other words, we can say that it binds the format specifiers to the values.
Output:
Hi I am Integer ... My value is 10
Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh
----------------------------------------------------x------------------------------------------------------
11.Built-in functions
Python comes with a rich set of built-in functions that are readily available for use without
needing to import any module. Here are some commonly used built-in functions in Python:
23
input()
The input() function in Python is used to take user input from the keyboard. It pauses the
execution of the program and waits for the user to enter a line of text. Here's a simple
example demonstrating its usage:
24
In this example:
• input("Enter your name: ") prompts the user to enter their name. The string "Enter your
name: " is displayed as a prompt.
• input("Enter your age: ") prompts the user to enter their age.
• The user's inputs are stored in the variables name and age.
• Finally, a greeting message is printed using an f-string, which incorporates the values
entered by the user.
Execution Example:
len()
The len() function in Python is used to determine the length (number of items) of an object.
Its behavior varies depending on the type of object passed to it. Here's an example
demonstrating its usage with different types of data:
25
max(), min():
The max() and min() functions in Python are used to find the maximum and minimum
values from a collection of values or an iterable like lists, tuples, or strings. Here are
examples demonstrating their usage:
The max() function returns the maximum value from its arguments or from elements of an
iterable.
26
Output:
The min() function returns the minimum value from its arguments or from elements of an
iterable.
27
Output:
-----------------------------------------------x------------------------------------------------------------
12. Sequence types – Lists, Tuples, Named tuples
The sequence types in Python: lists, tuples, and named tuples are:
Lists:
• A list is a mutable, ordered sequence of values that are all stored in a single variable.
For example, you can make a list names that contains the strings “Sarah”, “Amit”, and
“Zhang”, or a list one_to_seventy that stores the numbers from 1 to 70.
• Each value in a list is referred to as an element of that list;
• Thus your names list would have 3 elements: "Sarah", "Amit", and "Zhang".
• Lists are written as literals inside of square brackets ([]), with each element in the list
separated by a comma (,):
28
Example
List Indices
You can refer to individual elements in a list by their index, which is the number of their
position in the list. Lists are zero-indexed, which means that positions are counted starting
at 0. For example, in the list:
• The 'a' (the first element) is at index 0, 'e' (the second element) is at index 1, and so
on.
• This also means that the last element can be found at the index length_of_list - 1.
• You can retrieve an element from a list using bracket notation: you refer to the
element at a particular index of a list by writing the name of the list, followed by
square brackets ([]) that contain the index of interest:
29
It is also possible to select multiple, consecutive elements from a list by specifying a slice.
A slice is written as the starting and ending indices separated by a colon (:); the starting
index is included and the ending index is excluded. For example:
30
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
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
Code
Output:
2. Concatenation
Code
31
3. Length
It is used to get the length of the list
Code
4. Iteration
The for loop is used to iterate over the list elements.
Code
32
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
33
Output:
LIST METHODS
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
34
insert() Adds an element at the specified position
Tuple:
Example
Create a Tuple:
Tuple Items
• Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
35
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Output
To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
Example
One item tuple, remember the comma:
36
Tuple Items - Data Types
Example
Print(tuple1)
Print(tuple2)
Print(tuple3)
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position
of where it was found
Named Tuples:
Key Differences:
• Mutability: Lists are mutable (can be changed), while tuples (including named tuples) are
immutable (cannot be changed after creation).
• Accessing Elements: Elements in both lists and tuples are accessed via indexing, but named
tuples allow access using named attributes (p.x, p.y).
• Performance: Tuples are generally faster than lists because of their immutability, which
allows for optimizations in memory allocation and performance.
• Use lists when you have a collection of items that may need to be modified, such as adding
or removing elements.
• Use tuples when you want to store a fixed collection of items that should not change, such
as coordinates or settings.
• Use named tuples when you want more readable and self-documenting code for simple
classes, without needing the complexity of full-fledged classes.
Each of these sequence types serves different purposes based on their mutability, performance
characteristics, and intended use cases in Python programming.
---------------------------------------------------x-------------------------------------------------------------
There are currently two built in set types, set and frozenset
38
1. Sets:
Example
Create a Set:
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
o Unordered means that the items in a set do not have a defined order.
o Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
Output
{‘banana’, ’cherry’, ’apple’}
Set Items - Data Types
39
Example
Operations on Sets:
• Adding Elements: You can add elements to a set using the .add() method.
• Removing Elements: Elements can be removed from a set using methods like .remove()
or .discard().
• Set Operations: Sets support operations like union (|), intersection (&), difference (-),
and symmetric difference (^), which are very efficient.
Add Items
• Once a set is created, you cannot change its items, but you can add new items.
• To add one item to a set use the add() method.
Example
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
40
Set Methods
Python has a set of built-in methods that you can use on sets.
41
intersection() & Returns a set, that is the
intersection of two other sets
42
union() | Return a set containing the union of
sets
In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements. The major advantage of using a set, as opposed to a list, is that it has a
highly optimized method for checking whether a specific element is contained in the set.
2. Frozen Sets:
Example
• Since frozen sets are immutable, they are hashable and can be used as keys in
dictionaries or as elements of other sets.
--------------------------------------------------x------------------------------------------------------------
Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
43
• Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items
• Dictionary items are presented in key: value pairs, and can be referred to by using the key
name.
Example
Output
Ford
Ordered or Unordered?
• When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change.
• Unordered means that the items do not have a defined order, you cannot refer to an item by
using an index.
44
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
output
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to
it:
Example
45
Removing Items
Example
The pop() method removes the item with the specified key name:
Output
{'brand': 'Ford', 'year': 1964}
Example
The del keyword removes the item with the specified key name:
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
46
fromkeys() Returns a dictionary with the specified keys and value
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
Default dictionaries
The dictionary is an unordered collection of data values in Python used for storing data
values such as maps. The dictionary holds key-value pairs instead of holding a single value
as an element like other data types. The key implemented in the dictionary must be unique
and immutable. That is, the Python tuple can be a key, but the Python list cannot be a key in
the dictionary. We can create a dictionary by placing a sequence of elements inside the
47
curly brackets {}, a comma "," can separate the values.
Example 1:
Output:
But if we try to print the 5th key value then, we will get the error because "Dict_1" does
not contain the 5th key value.
Example 2:
Output:
48
defaultdict
The defaultdict is a dictionary of Python, which is like a container present inside the
'collections' module. It is a sub-class of the dictionary class which is used for returning the
dictionary-like object. Both defaultdict and dictionary have the same functionality, except
defaultdict never raise any KeyError as it provides a default value for the Key, which does
not exist in the dictionary created by the user.
Syntax:
Parameters:
o default_factory: The default_factory() function returns the default value set by the user for
the dictionary defined by them. If this argument is absent, then the dictionary will raise the
KeyError. Example:
49
Output:
Iterating Collections
Python Iterators
• An iterator is an object that can be iterated upon, meaning that you can traverse through
all the values.
Iterator vs Iterable
• Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.
• All these objects have a iter() method which is used to get an iterator:
Example
50
Even strings are iterable objects, and can return an iterator:
Example
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
output
b
a
n
a
n
a
Looping Through an Iterator
Example
for x in mytuple:
print(x)
Output
51
Create an Iterator
All classes have a function called __init__(), which allows you to do some initializing when
the object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.), but must always
return the iterator object itself.
The __next__() method also allows you to do operations, and must return the next item in
the sequence.
Example
Create an iterator that returns numbers, starting with 1, and each sequence will increase by
one (returning 1,2,3,4,5 etc.):
Output
1
2
3
4
5
52
StopIteration
The example above would continue forever if you had enough next() statements, or if it was
used in a for loop.
To prevent the iteration from going on forever, we can use the StopIteration statement.
In the __next__() method, we can add a terminating condition to raise an error if the
iteration is done a specified number of times:
Example
Stop after 20 iterations:
Output
53
Copying collections
Copying collections in Python can be done in several ways, depending on the type of
collection
Here’s how you can copy various types of collections:
1. Lists
• Using Slicing:
54
2. Tuples
Tuples are immutable, so you typically don't need to make copies of them. However, you
can create a new tuple from an existing one:
3. Sets
Sets can be copied using the copy() method or by using set comprehension:
55
4. Dictionaries
Dictionaries can be copied using the copy() method or by using dictionary comprehension:
The copy module is used to create the shallow copy and deep copy. Let's see the each
method.
Shallow Copy
A shallow copy is a copy of an object that stores the reference of the original elements. It
creates the new collection object and then occupying it with reference to the child objects
found in the original.
56
It makes copies of the nested objects' reference and doesn't create a copy of the nested
objects. So if we make any changes to the copy of the object will reflect in the original
object. We will use the copy() function to implement it.
Example –
Output
57
In the above code, we made chance in the list1 that reflected in the other list.
A deep copy is a process where we create a new object and add copy elements recursively.
We will use the deecopy() method which present in copy module. The independent copy is
created of original object and its entire object. Let's understand the following example.
Explanation -
In the above output, we can see that z is a clone of x that we have created using
the deecopy() method. If we make change to one of child won't affect the original object.
Comprehensions
Comprehension provides a precise way of writing a program in Python. It reduces the code
size without affecting its easy readability.
1. List Comprehension
2. Dictionary Comprehension
3. Set Comprehension
4. Generator Comprehension
58
1. List Comprehension
We know that the elements of a list are enclosed in square brackets and it can hold values of
multiple data types.
In the program given below, we will take out the even numbers from the list.
Example 1-
Output-
The next program given below, we performed the same using list comprehension.
Output-
59
2. Dictionary Comprehension
We all know that dictionary uses key-value pairs, let us have a look at the program of
displaying these pairs.
Example –
Output-
Output-
The resultant dictionary using comprehension would be:
{‘Apple’:’Red’,’Bananas’:’Yellow’, ‘Custard Apple’:’Green’, ‘Pineapple’:’Brown’,
‘Blueberries’:’Violet’}
60
Set is used to display the unique elements from a given collection. Let's obtain the square of
all elements of list using set.
We have taken each element from list1 and provided the expression in result_set for
calculating the square of these elements.
-------------------------------------------------------x------------------------------------------------------
Generator Comprehension
The generators are the quite similar to functions. It uses the yield keyword to generate a
value. Let us see how comprehension can be used here.
Example –
Output
61
On executing the program, it displays the even elements from list1.
---------------------------------------------------x-------------------------------------------------------
15. Control structures – Conditional branching, Looping, Exception handling.
Control flow refers to the sequence a program will follow during its execution.
Sequential
Code
Output
62
The result of the subtraction is: 10
The result of the addition is :
30
The result of the multiplication is: 200
The statements used in selection control structures are also referred to as branching
statements or, as their fundamental role is to make decisions, decision control statements.
A program can test many conditions using these selection statements, and depending on
whether the given condition is true or not, it can execute different code blocks.
There can be many forms of decision control structures. Here are some most commonly
used control structures:
o Only if
o if-else
o The nested if
o The complete if-elif-else
Simple if
If statements in Python are called control flow statements. The selection statements assist us
in running a certain piece of code, but only in certain circumstances. There is only one
condition to test in a basic if statement.
Syntax
if <conditional expression> :
The code block to be executed if the condition is True
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
63
A nested if example
(an if statement within another if statement)
nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows us to
nest if statements within if statements. i.e, we can place an if statement inside another
if statement.
Syntax:
if (condition1):
# Executes when condition1 is
true if (condition2):
# Executes when condition2 is
true # if Block is end here
# if Block is end here
Example
score=raw_input("Enter score: ") score=int(score)
if score>=80: grade='A'
else:
if score>=70: grade='B'
else:
grade='C'
print "Grade is:" +grade
64
if
(condition
):
statement
elif
(condition):
statement
.
.
else:
statement
Example
There are generally two loop statements to implement the repetition structure:
We use a for loop to iterate over an iterable Python sequence. Examples of these data
structures are lists, strings, tuples, dictionaries, etc. Under the for loop code block, we write
the commands we want to execute repeatedly for each sequence item.
Syntax
▪ Variable: Represents the loop variable that takes each value from the iterable.
▪ Iterable: Could be a list, tuple, string, or any iterable object
Example
While Loop
While loops are also used to execute a certain code block repeatedly, the difference is that
loops continue to work until a given precondition is satisfied. The expression is checked
before each execution. Once the condition results in Boolean False, the loop stops the
66
iteration.
Syntax
while condition:
# body of the loop
Example
# Python program to show how to execute a while loop
b=9
a=2
Output:
---------------------------------------------------x----------------------------------------------------------
Exception Handling
Exception
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in
the code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or
other sequence types.
• IOError: This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.
• ImportError: This exception is raised when an import statement fails to find or load a
module.
• Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.
• Simplified error handling: Exception handling allows you to separate error handling
code from the m ain program logic, making it easier to read and maintain your code.
• Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.
• Easier debugging: When an exception is raised, the Python interpreter prints a
traceback that shows the exact location where the exception occurred, making it easier
to debug your code.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
Example:
try:
print(x)
except:
print("An exception occurred")
2. Try – Multiple except Statements
Exception type must be different for except statements
Syntax:
try:
statements
except errors1:
statements
except errors2:
69
statements
except errors3:
statements
Example:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
3. Try–Except-Else
• The else part will be executed only if the try block does not raise the exception.
• Python will try to process all the statements inside try block. If value error occur, the
flow of control will immediately pass to the except block and remaining statements in
try block will be skipped.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
Example
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
4. Raise statement
• The raise statement allows the programmer to force a specified exception to occur.
• To throw (or raise) an exception, use the raise keyword
Example:
70
x = -1
if x < 0:
raise Exception ("Sorry, no numbers below zero")
5. Try–Except-Finally
• A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
• The finally clause is also executed “on the way out” when any other clause of
the try statement is left via a break, continue or return statement.
Syntax
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example: 1
x = "hello"
if not type(x) is int:
raise TypeError ("Only integers are allowed")
Example: 2
x = -1
if x < 0:
raise Exception ("Sorry, no numbers below zero")
*************************************X***********************************
71