Python Programming F-CSIT232
Python Programming F-CSIT232
)A
m
ity
U
ni
ve
r
Python Programming
si
ty
O
nl
in
e
e
in
© Amity University Press
nl
No parts of this publication may be reproduced, stored in a retrieval system or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording or otherwise
without the prior permission of the publisher.
O
Advisory Committee
ty
Chairman : Prof. Abhinash Kumar
Members : Prof. Arun Bisaria
si
Dr. Priya Mary Mathew
Mr. Alok Awtans
Dr. Coral J Barboza
r
ve
Dr. Monica Rose
Mr. Sachit Paliwal
ni
Published by Amity University Press for exclusive use of Amity Directorate of Distance and Online Education,
Amity University, Noida-201313
Contents
e
Page No.
in
Module -I: Basic Concepts of Python Programming 01
1.1 Introductory Concept to Python
1.1.1 Concept of Function Programming
nl
1.1.2 Concept of Object Oriented Programming
1.1.3 Notation (Pseudocode, Flowchart)
O
1.1.4 Values and Types: int, float, boolean, string
1.1.5 Variables, Expressions and Statements
1.1.6 Precedence of Operators, Operands
ty
1.1.7 String Literals, Escape Sequence and Comments
1.2 Working in Python
si
1.2.1 Python Interpreter, Script and Interactive Mode
1.2.2 Input, Processing and Output
1.2.3 Editing, Saving and Running a Script
r
ve
Module - II: Conditional and Looping Statements in Python 55
2.1 Conditional Statements
2.1.1 Conditional Statements, Modulus Operator
2.1.2 Conditional (if), Alternative (if-else), Chained Conditional (if-elif-else)
ni
e
3.1.3 Parameter and Arguments
in
3.1.4 Illustrative Programs: Exchange the Values of Two Variables using Functions
3.1.5 Type Conversion Function, Adding New Function
3.1.6 Math Function, Composition
nl
3.2 Recursion
3.2.1 Traversal with a Code Snippet
O
3.2.2 Comparison with a Code Snippet
3.2.3 Searching with a Code Snippet
3.3 Problem Solving
ty
3.3.1 Counting with a Code Snippet
3.3.2 Alternatives to Hiring Permanent Employees
si
3.3.3 Pre-defined String Functions
3.3.4 Use of IN Operator
4.3 Tuple
4.3.1 Tuples: Tuple Assignment, Tuples as Return Values
4.3.2 Variable Length Argument Tuples
4.3.3 Lists and Tuples
e
4.3.4 Dictionaries and Tuples
in
4.3.5 Comparing Tuples
4.3.6 Sequences of Sequences
nl
Module - V: Input/Output in Python 203
5.1 Basics of File Handling
5.1.1 Text Files and Their Formats, Reading and Writing Files
O
5.1.2 Accessing and Manipulating Files on the Disk
5.1.3 Accessing and Manipulating Directories on the Disk
5.1.4 Format Operator, Command Line Arguments
ty
5.1.5 Filenames and Paths
5.2 Exception Handling
si
5.2.1 Errors and Exceptions
5.2.2 Raising and Handling Exceptions
5.2.3 Try and Finally Statement
5.2.4 With Statement
r
ve
5.2.5 Catching Exceptions
5.3 Pickling
5.3.1 Working with Database
ni
5.3.4 Pipes
ity
m
)A
(c
(c
)A
m
ity
U
ni
ve
r si
ty
O
nl
in
e
Python Programming 1
e
Learning Objectives:
in
At the end of this module, you will be able to understand:
nl
●● Concept of Object Oriented Programming
●● Notation (Pseudocode, Flowchart)
O
●● Values and Types: int, float, boolean, string
●● Variables, Expressions and Statements
●● Precedence of Operators, Operands
ty
●● String Literals, Escape Sequence and Comments
●● Python Interpreter, Script and Interactive Mode
si
●● Input, Processing and Output
●● Editing, Saving and Running a Script
Introduction r
ve
Python is a powerful and easy-to-learn programming language. It has efficient high-
level data structures and an object-oriented programming approach that is simple but
effective. Python’s elegant syntax and dynamic typing, as well as its interpreted nature,
make it an excellent language for scripting and rapid application development across a
ni
The Python interpreter and extensive standard library are freely available for all major
platforms in source or binary form from the Python Web site, https://www.python.org/, and
U
may be freely distributed. The same site also has links to and distributions of a variety of
free Python modules, programmes, and tools, as well as additional documentation.
ity
m
language currently in use. Python code is easy to read and write, and it’s succinct without
being obscure. Python is a very expressive language, so we can usually write far fewer
lines of Python code than an equivalent application written in, say, C++ or Java.
programme can be run on Windows and Unix-like systems like Linux, BSD, and Mac
OS X by simply copying the program’s file or files to the target machine. There is
no need to “build” or compile the programme. Although it is possible to write Python
e
nearly all of Python’s standard library and most third-party libraries are cross-platform.
in
enables us to perform tasks like downloading a file from the Internet, unpacking a
compressed archive file, and setting up a web server with just a few lines of code.
nl
some of which provide more powerful and sophisticated facilities than the standard
library, such as the Twisted networking library and the NumPy numeric library, while
others provide functionality that is too specialised to be included in the standard library,
O
such as the SimPy simulation package. The Python Package Index, pypi.python.org/
pypi, hosts the majority of third-party libraries.
ty
programme in procedural, object-oriented, and, to a lesser extent, functional styles.
This book teaches Python’s functional programming features as well as how to write
procedural and object-oriented programmes.
si
Python does not translate its code into machine code, which is not understandable
by hardware. Information actually changes it to a format known as byte code. So,
compilation happens in Python, but it’s not into a machine language. It’s converted to
r
byte code (.pyc or.pyo), which the CPU can’t understand. To execute the byte codes,
we’ll need a programme called the Python Virtual Machine.
ve
ni
U
To build executable code, the Python source code passes through the following
steps:
ity
Step 1: A python source code or instruction is read by the python compiler. It then
examines the syntax of each line to ensure that the instruction is properly formatted. If
an error occurs, the translation is instantly halted and an error notice is displayed.
m
Step 2: Byte code is the intermediate language used by the compiler if there is no
error in the python instruction or source code, which means that the compiler translates
it into its equivalent form.
)A
Step 3: To use Python as an interpreter, bytes are transmitted to the Python Virtual
Machine (PVM). Python byte code is transformed into machine-executable code by
PVM. An error message is displayed if there is a problem with the interpretation.
Python source code is also available under the GNU General Public License, just like Perl
Notes
e
(GPL). This tutorial provides sufficient knowledge of the Python programming language.
in
Functional programming is a programming paradigm in which everything is bound
using pure mathematical functions. It’s a declarative programming approach. In contrast
nl
to an imperative style, which focuses on “how to solve,” it focuses on “what to solve.”
Instead of statements, it employs expressions. A statement is executed to assign
variables, whereas an expression is evaluated to produce a value. Those functions
O
have some unique characteristics, which are discussed further down.
ty
functions. It’s been dubbed the world’s tiniest programming language. It explains what it
means to be computable. Computable is anything that can be computed using lambda
calculus. In terms of computation, it is comparable to a Turing machine. It establishes
si
a theoretical framework for describing and evaluating functions. Almost all current
functional programming languages are built on top of it.
Purists argue that by limiting side effects, programmes will have fewer bugs, will be
easier to debug and test, and will be better suited to formal verification.
Alonzo Church developed the lambda calculus in the 1930s as a formal system
U
Church later developed the simply-typed lambda calculus, a weaker system that
extended the lambda calculus by assigning a type to all terms.
m
LISP, the first high-level functional programming language, was created by John
)A
McCarthy at Massachusetts Institute of Technology in the late 1950s for the IBM
700/7000 series of scientific computers (MIT). Church’s lambda notation was used
to define LISP functions, which was then extended with a label construct to allow for
recursive functions.
Lisp, though early Lisps were multi-paradigm languages that incorporated support for a
variety of programming styles as new paradigms emerged. Later dialects like Scheme
and Clojure, as well as offshoots like Dylan and Julia, attempted to simplify and rationalise
Notes
e
Lisp around a cleanly functional core, whereas Common Lisp was designed to preserve
and update the paradigmatic features of the numerous older dialects it replaced.
in
Functional programming has its own set of concepts and paradigms that aren’t found
in imperative programming (including object-oriented programming). However, because
programming languages cater to a variety of programming paradigms, some of these
nl
concepts may have been used by programmers using “mostly imperative” languages.
O
ty
r si
ve
ni
Pure functions: There are two main characteristics of these functions. First,
U
regardless of anything else, they always produce the same output for the same arguments.
Second, they don’t have any side effects, meaning they don’t change any
arguments, local/global variables, or input/output streams.
ity
Immutability is a later property. The value returned by a pure function is its only
output. They are predetermined.
Because pure functions have no side effects or hidden I/O, functional programming
programmes are simple to debug. Parallel/concurrent applications are also easier
m
to write with pure functions. A smart compiler can do a lot of things when the code
is written in this style: it can parallelize the instructions, wait to evaluate results until
they’re needed, and memorise the results because the results never change as long as
)A
e
in
nl
Referential transparency: Variables defined in functional programmes do not
change their value throughout the programme. Assignment statements are not used
O
in functional programmes. Instead of defining new variables, we define new variables
when we need to store a value. Because any variable can be replaced with its actual
value at any point during execution, there are no side effects. Any variable’s state is
constant at all times.
ty
Example of Referential Transparency:
si
Functions are First-Class and can be Higher-Order: First-class variables are
r
treated the same as first-class functions. Variables of the first class can be passed as
parameters to functions, returned from functions, or stored in data structures. Higher-order
ve
functions are those that accept other functions as arguments and can also return them.
Higher-order functions are those that can take or return other functions as arguments
or results. The differential operator {\displaystyle d/dx} d/dx, which returns the derivative of
a function {\displaystyle f}f, is an example of a higher-order function in calculus.
ni
Higher-order functions and first-class functions are similar in that they both accept
functions as arguments and results of other functions. The distinction is subtle: “higher-
U
Partially applying or currying a function to its arguments one at a time, with each
application returning a new function that accepts the next argument, is possible with
higher-order functions. This allows a programmer to express the successor function
m
for example, as the addition operator partially applied to the natural number one in a
concise manner.
)A
(c
Variables are Immutable: We can’t change a variable after it’s been initialised in
Notes
e
functional programming. We can create new variables but not modify existing variables, which
is very useful for maintaining state throughout a program’s runtime. We can be confident that
once we create a variable and set its value, the value of that variable will never change.
in
Advantages and Disadvantages of Functional programming
1. Pure functions are simpler to comprehend because they do not change their
nl
states and rely solely on the input they receive. The return value they provide
is whatever output they produce. Their function signature contains all relevant
information, such as their return type and arguments.
O
2. Functional programming languages’ ability to treat functions as values and pass them
as parameters to functions makes the code more readable and understandable.
3. It is simpler to test and debug. Pure functions don’t produce any changes and
ty
don’t take input or produce any hidden output because they only take arguments
and produce output. Because they use immutable values, it’s easier to spot
flaws in programmes written with pure functions.
si
4. Pure functions do not change variables or any other data outside of them, so
they are used to implement concurrency/parallelism.
5. It employs lazy evaluation, which avoids repeated evaluation by evaluating and
r
storing the value only when it is required.
ve
Disadvantages:
1. When writing pure functions, the readability of the code can suffer.
2. It can be intimidating to write programmes in a recursive style rather than using loops.
ni
3. Pure functions are simple to write but integrating them with the rest of the
application and I/O operations is difficult.
U
3. Loop statements and conditional statements like If-Else and Switch Statements
are not supported in functional programming languages. They use functions
and functional calls directly.
)A
The ability of an object’s own procedures to access and often modify the data
Notes
e
fields of the object is one of its features (objects have a notion of this or self). OOP is a
programming language that allows you to create computer programmes out of objects
that interact with one another. The most popular OOP languages are class-based,
in
which means that objects are instances of classes, which also determine their types.
Many of the most popular programming languages (such as C++, Java, Python,
nl
and others) are multi-paradigm and support object-oriented programming to some
extent, usually in conjunction with imperative, procedural programming. Java, C++, C#,
Python, R, PHP, Visual Basic.NET, JavaScript, Ruby, Perl, SIMSCRIPT, Object Pascal,
Objective-C, Dart, Swift, Scala, Kotlin, Common Lisp, MATLAB, and Smalltalk are all
O
important object-oriented languages.
ty
with its own set of attributes and behaviour.
si
of programming is well suited to large, complex, and frequently updated or maintained
programmes. This includes manufacturing and design software, as well as mobile
applications; for example, OOP can be used to simulate manufacturing systems.
r
An object-oriented program’s structure also makes it useful for collaborative
ve
development, where projects are divided into groups. Code reusability, scalability, and
efficiency are also advantages of OOP.
The first step in OOP is data modelling, which involves gathering all of the objects
a programmer wants to manipulate and determining how they relate to one another.
ni
Physical entities, such as a human being with properties such as name and
address, to small computer programmes, such as widgets, are examples of objects.
U
A feature of objects is that an object’s own procedures can access and often
modify the data fields of itself (objects have a notion of this or self). In OOP, computer
programs are designed by making them out of objects that interact with one another.
OOP languages are diverse, but the most popular ones are class-based, meaning that
)A
Many of the most widely used programming languages (such as C++, Java,
Python, etc.) are multi-paradigm and they support object-oriented programming
to a greater or lesser degree, typically in combination with imperative, procedural
(c
Programs must be designed. Nobody can just sit down at the pc and compose a
Notes
e
program of any complexity. The discipline called software engineering cares with the
development of correct, working, well-written programs. The programmer tends to use
accepted and proven methods for analysing the matter to be solved and for designing a
in
program to unravel that problem.
The procedural approach to programming was the de facto approach within the
youth of programming. Here, code is modularized supported a system’s processes. As an
nl
example, in developing a Hotel Application System, we might have considered processes
like the checking-in and Check-out of rooms, making reservations of rooms, cataloguing
of hotels room, and so on. Problem solving would involve the analysis of those processes
O
in terms of the procedural tasks administered and therefore the production of a system
whose representation is predicated on the procedural flow of the processes.
ty
the interactions within the problem space and the production of a system supported
these objects and their interactions.
si
interactions, a software application developed using the object-oriented programming
approach will end in the assembly of a computing system that features a closer
representation of the real-world problem domain than would be the case if the
procedural programming approach is employed.
r
ve
During the 1970s and into the 80s, the first software engineering methodology was
structured programming. The structured programming approach to program design was
supported the subsequent advice: to unravel an outsized problem, break the matter
into several pieces and work on each bit separately; to unravel each bit, treat it as a
replacement problem which may itself be weakened into smaller problems; eventually,
ni
you’ll work your way right down to problems which will be solved directly, without further
decomposition. This approach is named top-down programming.
There is nothing wrong with top-down programming. It’s a valuable and often-used
U
approach to problem-solving. However, it’s incomplete. For one thing, it deals almost
entirely with producing the instructions necessary to unravel a issue. But as time went
on, people realized that the planning of the info structures for a program was as least as
important because the design of subroutines and control structures. Top-down programming
ity
doesn’t give adequate consideration to the info that the program manipulates.
“plugged into” a system. The small print of what goes on inside the module aren’t
important to the system as an entire, as long because the module fulfils its assigned
role correctly. This is often called information hiding, and it’s one among the foremost
Amity Directorate of Distance & Online Education
Python Programming 9
e
Modules that would support this type of information-hiding became common in
programming languages within the early 1980s. Since then, a more advanced sort of
in
an equivalent idea has more or less appropriated software engineering. This latest
approach is named object-oriented programming, often abbreviated as OOP.
The central concept of object-oriented programming is that the object, which may
nl
be a quite module containing data and subroutines. The point-of-view in OOP is that an
object may be a quite independent entity that has an indoor state (the data it contains)
which can answer messages (calls to its subroutines). A list object for instance, features
O
a state consisting of an inventory of names and numbers. If you send it a message
telling it to feature a reputation, it’ll respond by modifying its state to reflect the change.
If you send it a message telling it to print itself, it’ll respond by printing out its list of
names and numbers.
ty
MIT was the first to use the terms “objects” and “oriented” in the modern sense
of object-oriented programming in the late 1950s and early 1960s. As early as 1960,
“object” could refer to identified items (LISP atoms) with properties (attributes) in the
si
artificial intelligence group’s environment; Alan Kay later cited a detailed understanding
of LISP internals as a strong influence on his thinking in 1966.
In addition, AED-0, an MIT ALGOL version, established a direct link between data
structures (“plexes” in that dialect) and procedures foreshadowing what would later be
ni
Simula introduced concepts like class and object, inheritance, and dynamic binding that
are now commonplace in object-oriented programming. Researchers working on physical
U
modelling, such as models to study and improve the movement of ships and their cargo
through cargo ports, primarily used the object-oriented Simula programming language.
●● Classes are user-defined data types that act as the blueprint for individual objects,
attributes and methods.
●● Objects are instances of a class created with specifically defined data. Objects
m
Objects will have data stored in the attributes field. Class attributes belong to the
class itself.
Principles of OOP
Notes
e
Encapsulation: This principle states that an object contains all important
information and only a subset of it is exposed. Each object’s implementation and state
in
are kept private within a defined class. This class is not accessible to other objects, and
they do not have the authority to change it. They can only use a limited set of public
functions and methods. This data-hiding feature improves programme security and
nl
prevents unintended data corruption.
Abstraction: Internal mechanisms that are relevant for the use of other objects
are only revealed by objects, and any unnecessary implementation code is hidden. The
O
functionality of the derived class can be expanded. This concept can make it easier for
developers to make changes or additions over time.
Inheritance: Code from other classes can be reused by classes. Developers can
ty
assign relationships and subclasses between objects, allowing them to reuse common
logic while maintaining a distinct hierarchy. This feature of OOP forces a more thorough
data analysis, shortens development time, and ensures greater accuracy.
si
Polymorphism: Objects are made to share behaviours and come in a variety of
shapes and sizes. The programme will figure out which meaning, or usage is required
for each execution of an object from a parent class, reducing the need for duplication of
r
code. After that, a child class is created, which extends the parent class’s functionality.
Different types of objects can pass through the same interface thanks to polymorphism.
ve
Benefits of OOP include:
Modularity: Encapsulation makes it possible for objects to be self-contained,
which simplifies troubleshooting and collaborative development.
ni
Reusability: Because inheritance allows code to be reused, a team does not have
to write the same code multiple times.
U
on their own.
Interface descriptions: Because message passing techniques are used for object
communication, external system descriptions are simple.
is assigned. Objects of various types can also pass through the same interface.
(c
e
in
nl
O
ty
1.1.3 Notation (Pseudocode, Flowchart)
si
Computers are used to solve problems, automate processes, and process data
and information. It is carried out by the computer using instructions received from
various programming languages such as C, C++, and a variety of others. A programme
r
is a set of instructions given to a computer to perform a task. A programme is nothing
ve
more than an algorithm expressed in a programming language. As previously stated,
writing a programme necessitates knowledge of the programming language. However,
an algorithm is a set of instructions that can be expressed independently of any
programming language. Algorithm can be defined in a variety of ways.
ni
(for example, if ‘n’ equals 4, it should add 1+2+3+4). If the algorithm for this problem
were written in natural language, it would look like this:
)A
Set the sum value to 0 and the count to 1 at first. Accept the user’s input as ‘on’.
If the value of ‘n’ is 0, the value of sum should also be 0. If the value is greater than
0, add the count until the input value ‘n’ is reached. Increase the count value after
each addition.
Even for this minor issue, it is clear that natural language is unstructured. The
(c
natural language algorithm will be difficult to understand while programming in the case
of a large problem.
The algorithm could then be written in formal languages like C, C++, and so
Notes
e
on. However, during the early stages of design, one would be thinking and writing
in a highly abstract manner. Using a programming language forces you to use
proper punctuation and syntax, which you can’t do at this stage of the design. The
in
programming language’s syntax should not be used in the algorithm.
nl
languages is required. Pseudo code is a type of notation that is commonly used to
write algorithms. It’s easy to read and doesn’t follow any grammatical rules. It is simple
to visualise the organisation of statements because it has a well-defined structure.
Because pseudo code resembles many programming languages, converting the
O
algorithm to programmes is simple.
The following is the pseudo code algorithm for the above problem:
ty
Step 1: Initialize the variable Count to 1 for counting the addition.
Step 3: Get the input value ‘Num’ for number of times sum has to be performed.
si
Step 4: Add Count with Sum and assign it to Sum.
Pseudocode
m
coding syntax. Although pseudocode is widely used, there is no set of rules for how it
should be implemented. In general, when writing pseudocode, the following rules are
frequently followed:
1. For arithmetic operations, the standard Fortran symbols (+, -, *, /, **) are used.
(c
e
A pseudocode to find the total of two numbers is as follows.
Begin
in
Set sum =0;
nl
Set sum = number1 + number 2;
Print sum;
O
End
ty
AreaofTrinagle()
Begin
si
Set area = 0.5 * base * height;
Print area;
End
r
ve
Flowchart
A flowchart is a diagram that depicts the flow of information through processing
systems. This means that by looking at a flow chart, one can learn about the operations
ni
that are performed and the order in which they are performed in a system. Algorithms
are simply a set of instructions for solving problems. As a result, a flow chart can
be used to depict an algorithm. A flowchart will show the operations that must be
U
A flow chart can be thought of as a blueprint for a design you’ve created to solve a
problem. If you’re going on a picnic with your friends for example, you should plan the
ity
activities you’ll do there. If you have an activity plan, you will know exactly when you will
do each activity. Similarly, if you have a problem that you want to solve with a computer,
or if you need to write a computer programme to solve a problem, it’s a good idea to
draw a flowchart first. A flowchart is a diagram that is drawn according to a set of rules.
m
Flowchart Symbol:
)A
e
can be the reult of a computation. The computation
would also be included in the rectangle.
in
A diamond indicates a point where a decision is made.
nl
An open-ended rectangle contains comment
O
statements. The comment is connected to the
program flow via a dashed line.
ty
A hexagon indicates the beginning of a repitition.
si
The double-lined rectangle indicates the use of an
algorithm specified outside the program, such as a
subroutine.
r
ve
Circles can be used to combine flow lines.
A flowchart is a diagram that depicts an algorithm. It clearly depicts the steps that
must be followed in order to arrive at a solution to a problem. Flowcharts may not be
U
very useful for simple problems, but they are extremely useful for understanding the
logic of complex and large problems. Flowcharts serve as a communication link
between programmers and the clients who will be served by the programme. You can
use a flowchart to explain your programme to others if you have one. It is simple to
ity
write the computer programme after the flowchart has been drawn. Flowcharts can aid
in the preparation of better documentation for a complicated problem.
Flowchart symbols are used to create flowcharts. There are some guidelines to
follow when drawing a flowchart. Here are some pointers on how to make a flowchart:
top to bottom.
4) A process symbol should only have one flow line coming out of it.
Notes
e
in
5) Only one flow line should enter the decision symbol (decision symbol), but there
may be two or three flow lines coming out of the decision symbol, one for each
nl
possible answer.
O
ty
si
6) Only one flow line should reach the end symbol in a flowchart.
r
ve
ni
7) Steps should be brief when written inside the processing symbol, and you can
use the annotation symbol to describe data or processing l steps more clearly if
necessary.
U
ity
Types of Flowcharts:
Notes
e
High-Level Flowchart
in
most important steps in a process. It depicts a “birds-eye view” of a process, such as
the one shown in the High-Level Flowchart of Prenatal Care figure. It can also include
the sub-steps and intermediate outputs of each step (the product or service produced).
nl
A flowchart like this provides a basic picture of the process and identifies the changes
that occur within it. Because of its focus on intermediate outputs, it is extremely useful
for identifying appropriate team members (those who are involved in the process) and
O
developing indicators for monitoring the process.
Most processes can be depicted in four or five boxes that represent the process’s
major steps or activities. In fact, using only a few boxes is a good idea because it forces
you to think about the most important steps. Other steps are frequently sub-steps of the
ty
more significant ones.
Detailed Flowchart
si
By mapping all of the steps and activities that occur in the process, the detailed
flowchart provides a detailed picture of the process. This type of flowchart depicts the
steps or activities of a process and includes elements such as decision points, waiting
r
periods, reworkable tasks, and feedback loops. This type of flowchart is useful for
ve
delving into specific areas of the process and looking for problems or inefficiencies. The
Detailed Flowchart of Patient Registration for example, shows the delays that occur
when the record clerk and clinical officer are unavailable to help clients.
A deployment flowchart depicts the steps and who is responsible for them. It
takes the form of a matrix, and it depicts the various participants as well as the flow
U
of steps among them. It’s most useful for figuring out who’s providing what inputs or
services to whom, as well as areas where multiple people are performing the same task
unnecessarily. See the Matrix Flowchart Deployment.
ity
e
effectively.
in
the logic of a system and steps involve in the solution, to all concerned particularly to
the client of system.
nl
Sample flowchart
A flowchart for computing N (N!) factorials. N! equals 1 * 2 * 3 *...* N. This flowchart
depicts a “loop and a half,” a situation described in introductory programming textbooks
O
that necessitates either duplication of a component (to be both inside and outside the
loop) or placing the component inside a loop branch.
ty
r si
ve
ni
U
If you’ve worked with lower-level languages like C or C++, you know that
Notes
e
implementing objects—also known as data structures—to represent the components in
your application’s domain is a big part of the job. You must create memory structures,
manage memory allocation, and implement search and access routines, among other
in
things. These tasks are as time-consuming (and error-prone) as they appear, and they
frequently detract from your program’s main objectives.
nl
The majority of this grunt work is eliminated in typical Python programmes.
Because Python includes powerful object types as a built-in feature, you won’t have to
worry about coding object implementations before you start solving problems. In fact,
you’re almost always better off using a built-in object rather than implementing your own
O
unless you have a need for special processing that built-in types don’t provide. Here are
some of the reasons for this:
Built-in objects make programs easy to write: Built-in types are frequently all
ty
you need to represent the structure of problem domains for simple tasks. You can use
powerful tools like collections (lists) and search tables (dictionaries) right away because
they are free. You can accomplish a lot with just Python’s built-in object types.
si
Built-in objects are components of extensions: You may need to create your
own objects using Python classes or C language interfaces for more complex tasks.
However, as you’ll see in later sections of this book, manually created objects are
r
frequently built on top of built-in types like lists and dictionaries. A stack data structure
ve
for example, could be represented by a class that manages or customises a built-in list.
Built-in objects are often more efficient than custom data structures: Python’s
built-in types use data structure algorithms that have already been optimised and are
implemented in C for speed. Although you can create similar object types on your own,
ni
you’ll find it difficult to match the level of performance provided by built-in object types.
Built-in objects are a standard part of the language: Python borrows from
both languages that have built-in tools (e.g., LISP) and languages that require the
U
standard; proprietary frameworks, on the other hand, tend to vary from site to site.
The built-in object types in Python, as well as some of the syntax used to code
their literals—that is, the expressions that produce these objects. If you’ve used other
languages, you’ll recognise some of these types; for example, numbers and strings
m
represent numeric and textual values, respectively, and files provide an interface for
processing files on your computer.
Numbers
Notes
e
Some of the object types in Table above will be familiar if you’ve done any
programming or scripting in the past. Even if you haven’t worked with numbers before,
in
they’re fairly simple. Integers (numbers without a fractional part), floating-point numbers
(numbers with a decimal point), and more exotic numeric types are all part of Python’s
core objects set (complex numbers with imaginary parts, fixed-precision decimals,
nl
rational fractions with numerator and denominator, and full featured sets).
Python’s basic number types are, well, basic, despite some more advanced
options. In Python, numbers can be used to perform standard mathematical operations.
O
The plus sign (+) performs addition, a star (*) performs multiplication, and two stars (**)
perform exponentiation for example:
ty
345
>>> 1.5 * 4 # Floating-point multiplication
6.0
si
>>> 2 ** 100 # 2 to the power 100
1267650600228229401496703205376
r
Take note of the final result: When large numbers like this are needed, Python 3.0’s
ve
integer type automatically provides extra precision (in 2.6, a separate long integer type
handles numbers too large for the normal integer type in similar ways). In Python, you
can compute 2 to the power 1,000,000 as an integer, but you shouldn’t try to print the
result—with over 300,000 digits, you might have to wait a while!
ni
Numeric data types in Python represent data with a numeric value. Integers,
floating numbers, and even complex numbers can be used as numerical values. In
Python, these values are represented by the int, float, and complex classes.
U
Integers – The int class represents this value. It contains whole numbers that are
either positive or negative (without fraction or decimal). There is no limit to how long an
integer value can be in Python.
ity
Float – The float class is used to represent this value. It’s a floating-point
representation of a real number. A decimal point is used to specify it. To specify
scientific notation, the characters e or E, followed by a positive or negative integer, can
be appended.
m
a = 10
print(“Type of a: “, type(a))
b = 4.80
print(“\nType of b: “, type(b))
(c
c = 4 + 8j
print(“\nType of c: “, type(c))
Output:
Notes
e
in
nl
Sequence Type
In Python, a sequence is an ordered collection of data types that are similar or
O
different. Multiple values can be stored in an organised and efficient manner using
sequences. Python has a number of sequence types:
●● String
●● List
ty
●● Tuple
1) String
si
Strings are arrays of bytes in Python that represent Unicode characters. A string is
made up of one or more characters enclosed in a single, double, or triple quote. There
is no character data type in Python; a character is a one-length string. The str class is
used to represent it. r
ve
Creating String
In Python, single quotes, double quotes, and even triple quotes can be used to
create strings.
ni
print(type(String1))
String1 = ‘’’Python
For
Life’’’
(c
Output:
Notes
e
in
nl
O
ty
2) List
r si
ve
Lists are ordered collections of data, similar to arrays, which are declared in other
languages. It’s very adaptable because list items don’t have to be of the same type.
Creating List
ni
In Python, you can make a list by simply putting the sequence inside square
brackets [].
U
print(List)
List = [‘Welcome To Python’]
print(“\nList with the use of String: “)
m
print(List)
List = [“Welcomt”, “To”, “Python”]
print(“\nList containing multiple values: “)
)A
print(List[0])
print(List[2])
List = [[‘Python’, ‘For’], [‘Python’]]
(c
print(“\nMulti-Dimensional List: “)
print(List)
Output
Notes
e
in
nl
O
ty
3) Tuple
Tuple is an ordered collection of Python objects, similar to list. The only difference
si
between a tuple and a list is that tuples are immutable, meaning that once created, they
cannot be changed. The tuple class is used to represent it.
Creating Tuple r
ve
Tuples are created in Python by placing a sequence of values separated by a
‘comma’, with or without the use of parentheses for data grouping. Tuples can have any
number of elements and any type of data (like strings, integers, list, etc.).
ni
Boolean
True or False are the two built-in values for this data type. True Boolean objects
are truthy (true), while False Boolean objects are false (false) (false). Non-Boolean
U
objects, on the other hand, can be evaluated in a Boolean context and determined to be
true or false. The class bool is used to represent it.
Note that only booleans with capital ‘T’ and ‘F’ are valid; otherwise, python will
throw an error.
ity
print(type(true))
Output
)A
(c
e
Variables
in
The ability to manipulate variables is one of the most powerful features of a
programming language. A variable is simply a name for a value.
nl
>>> message = “Welocme to Python”
>>> n = 20
O
>>> pi = 3.14159
There are three assignments in this example. The first assigns the string “Welocme
to Python” to the message variable. The second assigns the integer 20 to n, while the
ty
third assigns the floating-point number 3.14159 to pi.
In Python, variables do not need to be declared first. They’re ready to use right
away. Python variables, like most other programming languages, are case-sensitive.
si
a = 3
A = 4
print (a)
r
ve
print (A)
Output
ni
4
U
letters by convention, even though it’s legal. If you do, keep in mind that your case is
important. Bruce is a different variable than Bruce.
In a name, the underscore character (_) can appear. It’s frequently used in multi-
word names like my_name or price_of_tea_in_china.
m
76 Because it does not begin with a letter, the word “horses” is illegal. more$ is
Notes
e
illegal because it contains the dollar sign, which is an illegal character. What, on the
other hand, is the problem with class?
in
It turns out that one of the Python keywords is class. Keywords are used to define the
syntax rules and structure of the language, but they cannot be used as variable names.
nl
introduce or remove one or two):
O
ty
This is a list you might want to keep on hand. Check this list if the interpreter
complains about one of your variable names and you don’t know why.
si
Programmers usually name their variables in such a way that they are
understandable to human readers of the programme — this helps the programmer
r
document or remember what the variable is for.
ve
Expressions
An expression is a set of operators and operands that are combined to produce
a different value. In any programming language, an expression is evaluated according
to the order in which its operators are evaluated. As a result, if an expression contains
ni
multiple operators, the order in which they are executed determines which operation is
performed first. In Python, there are many different types of expressions. Let’s go over
each type and some exemplar codes:
U
1. Constant Expressions: These are the expressions that have constant values
only.
Example:
ity
# Constant Expressions
a = 16 + 1.3
m
print(a)
Output
)A
17.3
Notes
e
in
nl
O
ty
si
Example:
# Arithmetic Expressions r
ve
x = 50
y = 22
add = x + y
ni
sub = x - y
pro = x * y
U
div = x / y
print(add)
print(sub)
ity
print(pro)
print(div)
m
Output
72
28
)A
1100
2.272727
3. Integral Expressions: After all computations and type conversions, these are
(c
# Integral Expressions
Notes
e
a = 25
b = 42.0
in
c = a + int(b)
print(c)
nl
Output
67
O
4. Floating Expressions: These are the types of expressions that, after all
computations and type conversions, produce floating point numbers as a result.
# Floating Expressions
ty
a = 28
b = 6
si
c = a / b
print(c)
Output
r
ve
4.66
Example:
# Relational Expressions
a = 42
ity
b = 25
c = 70
d = 37
m
p = (a + b) >= (c - d)
print(p)
)A
Output
True
6. Logical Expressions: These are the types of expressions that have a True
(c
return False. When studying logical expressions, we come across some logical
Notes
e
operators that are frequently used in logical expressions. Here are some Python
logical operators:
in
nl
O
Example:
Let’s have a look at an exemplar code:
ty
A = (10 == 9)
B = (7 > 5)
si
# Logical Expressions
C = A and B
D = A or B
r
ve
E = not A
print(C)
print(D)
ni
print(E)
Output
U
False
True
True
ity
z = 12
w = z >> 2
)A
q = z << 1
print(w, q)
Output
(c
3 24
e
multiple types of expressions in a single expression.
Example:
in
# Combinational Expressions
a = 16
nl
b = 12
c = a + (b >> 1)
O
print(c)
Output
22
ty
Statements
Statements are instructions for execution written in source code. In the Python
si
programming language, there are various types of statements, such as assignment
statements, conditional statements, looping statements, and so on. All of this aids the
user in obtaining the desired result. An assignment statement for example, is n = 50.
r
Statements with multiple lines: Parentheses (), braces (), square brackets [],
ve
semi-colon (;), and the continuation character slash () can be used to extend Python
statements to one or more lines (\). These characters can be used when a programmer
needs to do long calculations and his statements don’t fit on a single line.
ni
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
ity
b = (1 * 2 * 3 + 7 + 8 + 9)
m
footballer = [‘MESSI’,
‘GRIZMANN’,
‘RONALDO’]
(c
x = {1 + 2 + 3 + 4 + 5 + 6 +
Notes
e
7 + 8 + 9}
in
Declared using semicolons(;) :
nl
Indentation
A block is made up of all of these statements. A block is a collection of statements
O
that serve a specific purpose. Braces are used to define a block of code in most
programming languages, including C, C++, and Java. Python’s use of indentation to
highlight code blocks is one of its distinguishing features. In Python, indentation is done
with whitespace. All statements with the same right-hand distance belong to the same
ty
code block. If a block needs to be nested more deeply, it is simply indented to the right.
Examine the following lines of code to gain a better understanding:
si
site = ‘gfg’
if site == ‘wtp’:
r
ve
print(‘Logging on to Welcome to python world...’)
else:
Output
U
All set !
the URL.’) are two separate code blocks. The two blocks of code in our example if-
statement are both indented four spaces. The final print(‘All set!’) is not indented, and
so it does not belong to the else-block.
m
Example: Solve
(c
10 + 20 * 30
Notes
e
in
nl
O
ty
si
The formula for 10 + 20 * 30 is 10 + (20 * 30), not (10 + 20) * 30.
Code
r
# Precedence of ‘+’ and ‘*’
ve
expr = 10 + 20 * 30
print(expr)
Output
ni
610
Example: Let’s look at an example of the logical ‘or’ and ‘and’ operators in
U
action. The ‘if’ block is executed even if the age is 0. Because the logical ‘and’ takes
precedence over the logical ‘or’.
name = “Atharv”
age = 0
else:
)A
print(“Good Bye!!”)
Output
Welcome to the world of python.
(c
As a result, we can use parenthesis() to run the ‘else’ block because it has the
highest precedence of all the operators.
e
name = “Atharv”
age = 0
in
if ( name == “Atharv” or name == “Tanvi” ) and age >= 2 :
nl
else :
print(“Good Bye!!”)
O
Output
Good Bye!!
ty
Operator Associativity is used to determine whether or not an expression contains
two or more operators with the same precedence. It can be done from the left to the
right or the right to the left.
si
For example, because ‘*’ and ‘/’ have the same precedence and associativity is Left
to Right, the expression “100 / 10 * 10” is treated as “(100 / 10) * 10.”
r
ve
ni
U
ity
print(100 / 10 * 10)
# (5 - 2) + 3 and not as 5 - (2 + 3)
print(5 - 2 + 3)
# left-right associativity
(c
print(5 - (2 + 3))
# 2 ** (3 ** 2) and not as (2 ** 3) ** 2
Notes
e
print(2 ** 3 ** 2)
in
Output
100
nl
0
512
O
Note: Operators Precedence and Associativity are two main characteristics of
operators that determine the evaluation order of sub-expressions in absence
of brackets.
ty
Operator Description Associativity
() Parentheses left-to-right
si
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – r
Addition/subtraction left-to-right
ve
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to
left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
ni
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
)A
Example:
Notes
e
# Demo for Numeric literals
x = 30
in
y = 30.3
z = 20+3j
nl
print(x, y, z)
Output
O
30 30.3 (20+3j)
ty
●● String literals
●● Numeric literals
●● Boolean literals
si
●● Literal Collections
●● Special literals
String literals r
ve
A string literal is generated by enclosing a text(a collection of characters) in
single(“), double(“), or triple(“) quotes. We can write multi-line strings or display in the
desired way by utilising triple quotes.
ni
Example:
s = ‘Welcome to Python’
U
# in double quotes
ity
t = “Welcome to Python”
# multi-line String
m
m = ‘’’Welocme
to
)A
Python’’’
print(s)
(c
print(t)
print(m)
Output
Notes
e
Welocme to Python
Welocme to Python
in
Welcome
to
nl
Python
Character literal
O
A single character is surrounded by single or double quotations in this sort of string literal.
Example:
ty
# character literal in single quote
v = ‘abc’
si
# character literal in double quotes
w = “xyz”
print(v)
r
ve
print(w)
Output
abc
ni
xyz
Numeric literals
U
There are three sorts of numeric literals, all of which are immutable:
●● Integer
●● Float
ity
●● Complex.
Integer:
The number 0 is included in both positive and negative numbers. There should be
m
Example:
)A
a = 0b10100
# Decimal Literal
(c
b = 50
# Octal Literal
c = 0o320
Notes
e
# Hexadecimal Literal
d = 0x12b
in
print(a, b, c, d)
Output:
nl
20 50 208 299
O
the programme above. The binary literal is ‘a,’ the decimal literal is ‘b,’ the octal literal
is ‘c,’ and the hexadecimal literal is ‘d.’ However, when the print function was used to
display the value or retrieve the output, they were converted to decimal.
ty
Float
These are real numbers having both integer and fractional parts.
si
Example:
a = 30.8
r
ve
b = 45.0
print(a, b)
Output
ni
30.8 45.0
Complex Literal
U
The numerals will be a + bj, where ‘a’ represents the real part and ‘b’ represents
the complex part.
Example:
ity
a = 12 + 5j
b = 15j
m
print(a, b)
)A
Output
(12+5j) 15j
Boolean literals
In Python, there are only two Boolean literals. They are both correct and incorrect.
(c
Example:
w = (1 == True)
Notes
e
x = (1 == False)
y = True + 3
in
z = False + 7
nl
print(“w is”, w)
print(“x is”, x)
O
print(“y:”, y)
print(“z:”, z)
ty
Output
w is True
si
x is False
y: 4
z: 7
r
ve
True indicates a value of 1 in Python, while False represents a value of 0. Because
1 equals True, ‘w’ is True and ‘x’ is False in the preceding case.
Example:
p = (1 == True)
ni
q = (2 == False)
r = (3 == True)
U
s = (1 == True)
a = True + 20
b = False + 20
ity
print(“p is”, x)
print(“q is”, y)
print(“r is”, r)
m
print(“a:”, a)
print(“b:”, b)
)A
Output
p is True
q is False
r is True
(c
a: 21
b: 20
Escape Sequence
Notes
e
The term “escape sequence” refers to a group of characters (typically prefixed
with an escape character) that have a non-literal meaning. As a result, the characters
in
that make up an escape sequence have a meaning other than the literal characters
that make up the sequence. A backslash is used as an escape character in most
programming languages. This character is used to start an escape sequence;
nl
any character (one or more) after it is interpreted as an escape sequence. A control
character is defined as an escape sequence that is assigned to a Non-Printable
Character or a Control Code.
O
Escape Character Meaning
\’ Single quote
\” Double quote
ty
\\ backslash
\n New line
\r Carriage Return
si
\t Horizontal tab
\b Backspace
\f
\v
form feed
vertical tab
r
ve
\0 Null character
\N{name} Unicode Character Database named Lookup
\uxxxxxxxx Unicode Character with 16-bit hex value XXXX
ni
above table may not apply to your preferred programming language. The above table
will not apply to the Windows Command Line Interpreter since it utilises a caret () to
escape characters.
detected, the sequence is removed from the string and the sequence’s translation is
used instead. If no match is detected, no lookup is performed, and the control sequence
is copied unchanged.
Comments
(c
Python programmers frequently use the comment system because things can
quickly become confusing without it. Developers provide useful information in the
form of comments to help the reader understand the source code. It explains the
Notes
e
logic used in the code, or at least a portion of it. When you are no longer around to
answer questions about your code, comments are usually helpful to someone who
is maintaining or improving it. These are frequently cited as a useful programming
in
convention that does not affect the program’s output but improves the program’s
readability. In Python, there are two types of comments:
nl
Comments on a single line: Python single line comments begin with the hashtag
symbol (#) and continue to the end of the line. If the comment is longer than one line,
add a hashtag to the next line and continue the conversation. Single-line comments in
Python have proven to be useful for providing quick explanations for variables, function
O
declarations, and expressions. Consider the following code snippet, which shows how
to use a single line comment:
ty
Code 1:
# This is a comment
si
print(“Welcome to Python”)
Code 2:
r
a, b = 1, 3 # Declaring two integers
ve
sum = a + b # adding two integers
Multi-Line Comments
Multiple-line comments aren’t available in Python. However, there are a variety of
methods for writing multiline comments.
U
# multiline comments
print(“Multiline comments”)
)A
Output
Multiline comments
Because Python ignores string literals that aren’t assigned to a variable, we can
use them as comments.
Example 1:
Notes
e
‘This will be ignored by Python’
We can see that there would be no output if we run the above code, thus we use
in
the strings with triple quotes(“””) as multiline comments.
nl
“”” Python program to demonstrate
multiline comments”””
O
print(“Multiline comments”)
Output
Multiline comments
ty
1.2 Working in Python
si
Python, like Java, is an object-oriented programming language. Python is an
interpreted programming language. Instead of a single long list of instructions, as was
common in functional programming languages, Python uses interchangeable code
r
modules. “cpython” is the name of the standard Python implementation. It is Python’s
default and most extensively used implementation.
ve
1.2.1 Python Interpreter, Script and Interactive Mode
So far, we’ve primarily discussed Python as a programming language. However,
ni
contained within it. In effect, the interpreter is a layer of software logic that sits between
your code and your machine’s computer hardware.
When you install the Python package on your computer, it creates a number
of components, the most basic of which are an interpreter and a support library. The
ity
run by this interpreter, regardless of its form. To do so, you’ll need to install a Python
interpreter on your computer.
py.exe launcher installed. Other ways to start Python can be found in Excursus: Setting
Notes
e
Environment Variables.
The interpreter exits with a zero exit status when you type an end-of-file character
in
(Control-D on Unix, Control-Z on Windows) at the primary prompt. If it doesn’t work,
type the following command to leave the interpreter: quit ().
On systems that implement the GNU Readline library, the interpreter’s line-editing
nl
features include interactive editing, history substitution, and code completion. Typing
Control-P to the first Python prompt you get is probably the simplest way to see if
command line editing is available. You have command line editing if it beeps; for an
O
introduction to the keys, see Appendix Interactive Input Editing and History Substitution.
If nothing happens or if P is echoed, command line editing is disabled; you can only
remove characters from the current line by pressing backspace.
ty
The interpreter works similarly to the Unix shell in that it reads and executes
commands interactively when called with standard input connected to a tty device;
when called with a file name parameter or with a file as standard input, it reads and
runs a script from that file.
si
The command python -c command [arg]..., which is similar to the shell’s -c option,
starts the interpreter by executing the statement(s) in command. Because Python
r
commands frequently contain spaces or other shell-specific characters, it’s best to
quote the command in its entirety with single quotes.
ve
Some Python modules can be used as scripts as well. These are accessed with
the command python -m module [arg]..., which runs the source file for module as if you
had typed its entire name on the command line.
ni
When using a script file, it’s occasionally handy to be able to run the script and then
switch to interactive mode. By supplying -i before the script, you can accomplish this.
U
>>> 2 + 2 * 3
8
>>> ‘Welcome to ‘ + ‘python’
m
‘Welcometopythin’
>>> max(5, 8, -4)
)A
8
>>> ‘hello’ + 2
TypeError: can only concatenate str (not “int”) to str
>>> ‘welocme’ + str(5)
(c
‘welcome5’
>>>
This is a fantastic way to try out Python features and learn how they function. If you
Notes
e
have some code in mind, firing up the interpreter and typing it in to see what it does can
be a quick and instructive way to learn more about it. You can copy/paste an expression
that works in the interpreter as a first draught of that line into your programme.
in
While you write a Python programme, you save it in a file called hello.py, where
you can write and edit a series of functions, comments, and other elements over many
nl
lines, just like you would when writing a paper. You wouldn’t want to write an entire
programme at the >>> prompt, which is intended for short sentences.
O
work” is what interactive means etymologically. The interactive mode is solely based
on this philosophy. When we input a command and press enter in interactive mode, the
output is displayed immediately.
The last command we give has an impact on the output of the code in interactive
ty
mode. For writing very small lines of code, interactive mode is incredibly useful.
It’s also known as the REPL in Python, which stands for Read Evaluate Print Loop.
The read function here takes the user’s input and stores it in memory. The Eval function
si
takes an input and evaluates it to provide the required output. The evaluated result is
printed using the Print function.
r
The loop function executes the loop during the execution of our programme and
finishes when it is completed. This mode is ideal for beginners in programming since it
ve
allows them to analyse their code line by line and fully comprehend how it is executed.
launch our software in interactive mode. With the help of an example, let’s learn how to
execute python code on the command prompt:
U
Example 1:
Type “python” in the command prompt to start python. Then, on the >>> prompt, type
the Python statement. We can see the output in the next line as we type and click enter.
ity
print(“Welcome to python”)
Output
m
Welcome to Python
Script Mode
Notes
e
Script is an etymological term for a writing system. A python programme can be written
in a file using the script mode. The command prompt can then be used to save and execute
in
this file. By opening the file, we can view the code at any moment, and editing becomes a
breeze because we can open and view the full code as many times as we like.
Script mode is ideal for writing large amounts of code. Experts in the programme
nl
prefer this option to interactive mode. The file created in the script is saved by default in
the Python installation folder, with the extension “.py” for python files.
O
The steps below will show you how to run a code in script mode.
Step 1: Using a text editor, create a file. You are free to use any text editor you like
ty
(Here I use notepad).
Step 2: After you’ve finished creating the code, save it as a “.py” file.
Step 3: Open the command prompt and change the command directory to the
si
location where your file is saved.
r
Step 5: On your command prompt, you’ll see the output.
ve
Difference between Interactive mode and Script mode
programme in which statements are mode. The Python interpreter reads the file,
typed into a command prompt and a runs it, and outputs the required result. In the
result is returned. command prompt, the programme is compiled.
U
The interactive mode is better for Longer programmes are better written in script
writing really small scripts. mode.
Code editing is possible; however, it is In script mode, it’s simple to make changes
ity
There is no way to store and reuse Code can be stored and reused at a later time.
code in the future.
It is more popular with beginners. It is preferred by professionals. Script mode is
)A
frequently used. It’s the big three in programming, and it’s how we usually work. We
take some input from a file, a user, etc., process that information (or data, as the case
may be), and then offer some output to the screen, a file, a web service, or other means.
Amity Directorate of Distance & Online Education
Python Programming 43
This Input Process Outcome chart is used by some computer programmers to track
Notes
e
what goes into a programme, how it is handled, and then what the output is.
However, we deal with this on several levels, not just while discussing a software.
in
We can examine a problem (get input), create a solution (process), and write a
programme for example (output). We can take a closer look at the output and convert
it to input. For example, we can use it to discover and rectify syntax problems. Once
nl
we have our software built, we verify for logic flaws until we are satisfied with the
computer’s response.
O
A developer may want to solicit user input at some point during the development of
the project. Python has an input() method that can be used for this.
Syntax:
ty
input(‘prompt’)
where prompt is an optional string that appears on the string when input is being taken.
si
Example 1: Python receives user input and displays a message.
print(“Hello, “ + name)
print(type(name))
ni
Output
U
Hello, ATHARV
<class ‘str’>
ity
Note: Python takes all the input as a string input by default. To convert it to any
other data type we have to convert the input explicitly. For example, to convert
the input to int or float we have to use the int() and float() method respectively.
m
add = num + 1
# Output
(c
print(add)
Output
Notes
e
Provide a number: 35
36
in
How to Display Output in Python
Python provides the print() function to display output to the standard output
nl
devices.
O
Parameters:
value(s): Any value, and as many as you like. Will be converted to string before
printed
ty
sep=’separator’: (Optional) Specify how to separate the objects, if there is
more than one.Default :’ ‘
si
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
r
flush: (Optional) A Boolean, specifying if the output is flushed (True) or buffered
(False). Default: False
ve
Returns: It returns output to the screen.
# print() method
print(“Welcometopython”)
U
Output
ity
Welcometopython
Welcome to python
In the sample above, we can see that there is a space between each letter in the
m
second print statement, and the print statement always adds a new line character at
the end of the string. This is because the sep parameter is printed after each character,
while the end parameter is printed at the end of the string. Let’s see what we can do
)A
Example: Python Print output with custom sep and end parameter
# print() method
e
print(‘Welcome’, ‘To’, ‘Python’, sep=”#”)
in
Output
Welcome to Python@Welcome#to#Python
nl
1.2.3 Editing, Saving and Running a Script
The Python programming language is a well-known high-level programming
language. A Python script is essentially a file that contains Python code. The extension
O
of a python script file is ‘.py’, or ‘.pyw’ if it is being run on a Windows machine. A python
interpreter must be downloaded and installed in order to run a python script.
ty
print(‘ Welcome to Python ‘)
The ‘print()’ function is used to print any text included in parenthesis. We can use a
si
single quote, as seen in the preceding script, or a double quote to type the text we wish
to be printed.
If you’re coming from another language, you’ll notice there’s no semicolon at the
r
conclusion of the statement since Python doesn’t need you to declare the line’s end.
ve
Also, to run a simple python script, we don’t need to include or import any files.
There are several ways to launch a Python script, but before we get into the various
options, we must first determine whether or not a Python interpreter is installed on the
machine. So open ‘cmd’ (Command Prompt) in Windows and type the following command.
ni
python –V
The version number of the Python interpreter installed will be displayed, or an error
U
1. Interactive Mode
2. Command Line
(c
1. Interactive Mode:
Notes
e
You can run your script in Interactive Mode line by line in a sequence.
To enter interactive mode, open Command Prompt on your Windows PC and type
in
‘python’ followed by the Enter key.
nl
O
ty
Example 1:
si
Run the following line in the interactive mode:
Output
r
ve
ni
U
Example 2:
ity
name = “Aakash”
Output
)A
(c
Example 3:
Notes
e
Run the following line one by one in the interactive mode:
a = 1
in
b = 3
if a > b:
nl
print(“a is Greater”)
else:
O
print(“b is Greater”)
Output
ty
r si
ve
ni
Note: To exit from this mode, press ‘Ctrl+Z and then press ‘Enter’ or type
‘exit()’ and then press Enter.
U
2. Command Line
To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’
keyword before the file name in the command prompt.
ity
python Demo.py
these steps:
Search for and install the extensions ‘Python’ and ‘Code Runner’ under the extension
)A
Create a new file called ‘Demo.py’ and paste the code below into it.
print(‘Hello World!’)
Then, right-click anywhere in the text field and choose ‘Run Code’ from the menu,
(c
Output
Notes
e
in
nl
IDE (PyCharm)
O
You must do the following to launch Python scripts in an IDE (Integrated
Development Environment) such as PyCharm:
ty
●● Give the project a name, such as ‘GfG,’ and then click Create.
●● Choose the root directory for the project we named in the previous step.
Right-click it, select New, and then choose ‘Python file’. Then give the file the
si
name ‘hello’ (you can specify any name as per your project requirement). In
the project root directory, a file named ‘hello.py’ will be created.
●● It’s important to note that you don’t have to mention the extension because it
r
will be taken care of automatically.
ve
ni
U
●● Right-click and choose ‘Run File in Python Console’ to run this python script.
This will display the output in a console box at the bottom of the screen. The
Green Play Button in the upper right corner of the IDE can also be used to run.
m
)A
(c
Notes
e
in
nl
O
ty
Output r si
ve
ni
U
Summary
ity
e
natural language and programming.
●● In Python, a sequence is an ordered collection of data types that are similar or different.
in
Multiple values can be stored in an organised and efficient manner using sequences.
●● A string literal is generated by enclosing a text (a collection of characters) in
single(“), double(“), or triple(“) quotes.
nl
●● Python uses indentation to define blocks of code. Indentations are simply spaces
or tabs used as an indicator that is part of the indent code child. As used in curly
braces C, C++, and Java.
O
●● As python is interpreted language, we can work with the python interactively. The
default shell we get with the windows installation the Python IDLE is an Interactive
python environment. It is a kind of python playground.
ty
●● The interpreter is the program you’ll need to run Python code and scripts.
Technically, the interpreter is a layer of software that works between your program
and your computer hardware to get your code running.
si
●● Script mode is where the actual work happens. Interactive mode is useful to test
out the code but once we got our desired result, we are going to keep the code in
the file and can execute it whenever we want and also save it for future use.
●● r
The usual order of operations (PEDMAS) is followed by the interpreter.
ve
(Parenthesis-Exponentiation-Division-Multiplication-Addition-Subraction)
●● Script mode (although I have never heard it called this), is where one of more
python instructions are listed in a text file, so that the file can be executed outside
of the python console.
ni
●● Python takes all the input as a string input by default. To convert it to any other
data type we have to convert the input explicitly.
U
●● Python’s standard distribution includes IDLE as the default IDE, and you can use
it to write, debug, modify, and run your modules and scripts. Other IDEs such as
Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts
from inside the environment.
ity
Glossary
●● PVM: Python Virtual Machine
●● CPU: Central Processing Unit
m
●● Script Mode: The Python application is written in a file in script mode. The Python
interpreter reads the file, runs it, and outputs the required result. In the command
prompt, the programme is compiled.
Amity Directorate of Distance & Online Education
Python Programming 51
●● The ‘print()’ function is used to print any text included in parenthesis. We can use
Notes
e
a single quote, as seen in the preceding script, or a double quote to type the text
we wish to be printed.
in
●● GPL: General Public License
●● I/O: Input/Output
●● OOP: Object-oriented programming
nl
●● VM: Virtual machines
●● Escape sequence: The term “escape sequence” refers to a group of characters
O
(typically prefixed with an escape character) that have a non-literal meaning.
●● String: Strings are arrays of bytes in Python that represent Unicode characters. A string
is made up of one or more characters enclosed in a single, double, or triple quote.
ty
●● Tuple: Tuple is an ordered collection of Python objects, similar to list. The only
difference between a tuple and a list is that tuples are immutable, meaning that
once created, they cannot be changed.
si
●● List: Lists are ordered collections of data, similar to arrays, which are declared in
other languages.
●● Int: A data type for representing numbers with no fractional component. Int is short
r
for integer and represents a number with a fixed number of bits (commonly 32).
ve
●● Float: The float class is used to represent this value. It’s a floating-point
representation of a real number. A decimal point is used to specify it
●● Statement: A single command in a programming language.
ni
a. Object-oriented programming
b. Structured programming
c. Functional programming
m
a. No
b. Yes
c. Machine dependent
d. None of the above
(c
b. #
Notes
e
c. !
d. /*
in
4. Which one of the following has the same precedence level?
a. Addition and Subtraction
nl
b. Multiplication, Division and Addition
c. Multiplication, Division, Addition and Subtraction
O
d. Addition and Multiplication
5. What do we use to define a block of code in Python language?
a. Key
ty
b. Brackets
c. Indentation
si
d. None of these
6. Which of the following is not a keyword in Python language?
a. val
b. raise
r
ve
c. try
d. with
7. Which of the following precedence order is correct in Python?
ni
class Name:
def __init__(javatpoint):
javajavatpoint = java
m
name1=Name(“ABC”)
name2=name1
)A
a. It will throw the error as multiple references to the same object is not possible
b. id(name1) and id(name2) will have same value
c. Both name1 and name2 will have reference to two different objects of class
Name
(c
e
a. Interactive Mode
b. Command Line
in
c. Text Editor (VS Code)
d. All of the above
nl
10. The term ______________ refers to a group of characters (typically prefixed with an
escape character) that have a non-literal meaning.
a. Escape Sequence
O
b. Running Sequence
c. Halt Sequence
ty
d. Merge Sequence
Exercise
si
1. Explain Recursion.
2. What are the advantages and disadvantages of functional programming?
3. Explain OOPs and its principles.
4. Why are flow charts important?
r
ve
5. Explain built-in objects.
6. Explain Python Interpreter.
7. What are the advantages and disadvantages of Script and Interactive Mode?
ni
10. What are the differences between Interactive mode and Script mode?
Learning Activities
ity
1. Understand the flow chart creation process and practice flow chart of any flow
(condition based flow).
2. Write a program that creates a sentence by storing the words of the sentence in
separate variables and then put them together to form the sentence using string
m
1. d
2. b
3. b
4. a
(c
5. c
6. a
7. a
Notes
e
8. b
9. d
in
10. a
nl
1. Data Structures and Algorithms with Python Undergraduate Topics in Computer
Science by Kent Lee, Steve Hubbard
O
2. Introduction to Programming Using Python by Daniel Liang
3. Programming in Python 3: A Complete Introduction to the Python Language by Mark
4. Hamilton, Naomi “The A-Z of Programming Languages: Python
ty
5. Summerfield, Mark (2009). Programming in Python 3 (2nd ed.)
6. Pilgrim, Mark (2009). Dive into Python 3
si
7. Head-First Python (2nd edition) by Paul Barry
8. Learning with Python: How to Think Like a Computer Scientist by Allen
Downey, Jeff Elkner, and Chris Meyers
9. r
A Byte of Python’ by C.H. Swaroop
ve
10. Python Cookbook’ by David Beazley and Brian K. Jones
ni
U
ity
m
)A
(c
e
in Python
in
Learning Objectives:
At the end of this module, you will be able to understand:
nl
●● Conditional Statements, Modulus Operator
●● Conditional (if), Alternative (if-else), Chained Conditional (if-elif-else)
O
●● Boolean Expression, Logical Expression
●● Code Snippet Showing the Use of If Statement
●● Code Snippet Showing the Use of Alternative (if-else)
ty
●● Code Snippet Showing the Use of Chained Conditional (if-elif-else)
●● While for statement, enhanced for statement
●● Code Snippet Showing the Use of while statement
si
●● Code Snippet Showing the Use of for statement
●● Code Snippet Showing the Use of enhanced for statement
●● Break Statement
r
ve
●● Continue Statement
●● Code Snippet Showing the Use of break statement
●● Code Snippet Showing the Use of continue statement
ni
Introduction
U
The while statement in Python is the language’s most general iteration mechanism.
Simply said, it executes a block of (usually indented) statements repeatedly as long as
a test at the top continues to evaluate to a true value. Because control loops back to the
beginning of the statement until the test is false, it’s called a “loop.” Control goes to the
ity
statement after the while block when the test is false. The result is that while the test at
the top is true, the loop’s body is executed repeatedly; if the test is false to begin with,
the body never runs.
In Python, the for loop is a general sequence iterator that may iterate across any
m
ordered sequence object. The for statement works with strings, lists, tuples, and other
built-in iterables, as well as new objects that we’ll construct later with classes. We briefly
discussed it when we looked at sequence object types; now we’ll go over it in more detail.
)A
e
In Python, if else elif statement is used for decision making.
in
if statement
The if condition is the most basic decision-making condition. It is used to determine
if a statement or a block of statements will be executed or not, i.e., if a condition is true,
nl
a block of statements will be executed; otherwise, it will not.
Syntax:
O
if condition:
# Statements to execute if
# condition is true
ty
After examination, the condition will be either true or false. If the value is true, the
if statement will execute the block of statements below it; otherwise, it will not. We can
also use a condition using the bracket ‘(‘ ‘)’.
si
Python utilises indentation to distinguish blocks, as we all know. As seen in the
example below, the block under an if statement will be identified:
if condition: r
ve
statement1
statement2
ni
# its block.
ity
m
)A
(c
Modulus Operator
Notes
e
The Python modulus operator, like other programming languages, does the same
thing to find the modulus of a given number. The operator is a mathematical symbol that
in
can be used to perform various operations on two integers, such as (+, -, * /) addition,
subtraction, multiplication, and division, and return the result in the form of an integer
or a float number. An operator instructs the compiler to take particular actions based on
nl
the operator symbol that has been provided to the specified number.
When we see a ‘%’ the first thing that springs to mind is the “Percentage-symbol,”
however this sign has a different name and meaning when viewed through the lens of
O
computer language. After dividing one integer by another, the modulo operation(percent)
finds the remainder or signed remainder (called the modulus of the operation).
ty
division of a by n, where an is the dividend and n is the divisor, given two positive
numbers, a and n.
The modulo operator in Python is used to get the remainder of a division. Along
si
with +, –, /, *, **, and //, the modulo operator (percent) is considered an arithmetic
operation. Both operands of this modulo operator must be integers in most languages.
However, Python Modulo is adaptable in this situation. Integer or float operands are
acceptable.
r
ve
Expression:
X%Y
Example:
# inputs
U
X = 13
Y = 5
Z = X % Y
# inputs
m
M = 15.0
N = 7.0
)A
# when dividing M by N, in O
O = M % N
(c
Output
Notes
e
13 mod 5 = 3
in
Let’s write a program to get the remainder of two numbers using the while loop and
modulus (%) operator in Python.
nl
Demo_python.py
while True: # if the while condition is true if block is executed
O
a = input (‘Do you want to continue or not (Y / N)? ‘)
ty
break
si
b = int(input (‘ Second number is: ‘)) # second number
print(a, ‘ % ‘, b, ‘ = ‘, a % b) # perform a % b
r
print(b, ‘ % ‘, a, ‘ = ‘, b % a) # perform b % a
ve
Output
ni
U
ity
m
)A
(c
e
In simple terms, the Python if statement selects actions to perform. It’s the primary
selection tool in Python and represents much of the logic a Python program possesses.
in
It’s also our first compound statement. Like all compound Python statements, the if
statement may contain other statements, including other ifs. In fact, Python lets you
combine statements in a program sequentially (so that they execute one after another),
nl
and in an arbitrarily nested fashion (so that they execute only under certain conditions).
If Statement Syntax
if test expression:
O
statement(s)
●● The programme examines the test expression and only executes the
ty
statement(s) if the test expression returns True.
●● The statement(s) are not executed if the test expression is False.
●● The indentation in Python indicates the content of the if statement. The body
si
begins with an indentation and ends with the first unindented line.
●● Non-zero numbers are interpreted as True in Python. False is read as None
and 0.
General Format
r
ve
The Python if statement is typical of if statements in most procedural languages. It
takes the form of an if test, followed by one or more optional elif (“else if”) tests and a
final optional else block. The tests and the else part each have an associated block of
nested statements, indented under a header line. When the if statement runs, Python
ni
executes the block of code associated with the first test that evaluates to true, or the
else block if all tests prove false. The general form of an if statement looks like this:
U
if <test1>: # if test
<statements2>
<statements3>
m
If-else
If a condition is true, the if statement will execute a block of statements; if the
)A
condition is false, the if statement will not. But what if the condition is false and we
want to do something else? This is when the otherwise statement comes in. When the
condition is false, we can combine the else statement with the if statement to execute a
block of code.
(c
if (condition):
# condition is true
Notes
e
else:
in
# condition is false
nl
O
ty
r si
ve
ni
nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, Python allows us to
ity
nest if statements within if statements, i.e., we can place an if statement inside another
if statement.
Syntax:
m
if (condition1):
if (condition2):
Notes
e
in
nl
O
ty
si
Figure: Flowchart of python Nested if Statement
if-elif-else ladder
r
Here, a user can decide among multiple options. The if statements are executed
ve
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will be executed.
Syntax:
ni
if (condition):
statement
U
elif (condition):
statement
ity
else:
m
statement
)A
(c
Notes
e
in
nl
O
ty
r si
ve
Figure: Flow Chart of Python if else elif statements
ni
●● Elif stands for “else if.” It enables us to check for several expressions at the
same time.
U
●● If the if condition is False, the next elif block’s condition is checked, and so on.
●● The body of else is executed if all of the conditions are False.
●● According to the condition, just one of the numerous if...elif...else blocks is executed.
ity
●● There can only be one other block in the if block. It can, however, have
several elif blocks.
Every programming language has booleans which are straightforward and easy to
use ideas. The concept of “true” or “false” is represented by a boolean. There are many
times while writing an algorithm or any programme when we wish to execute different
)A
code in different conditions. Booleans make it simple and effective for our code to
accomplish precisely that. A boolean value is frequently returned as a consequence of
some sort of comparison action.
Two Boolean keywords exist: Operators for True and False: In Python, operators
(c
are special symbols that are used to execute arithmetic and logical calculations.
Operands are the values on which the operation will be performed. The operation is
denoted by an operator (for example, +, -, /, *, percent, etc.).
The Python Boolean type is one of Python’s built-in data types. It’s used to
Notes
e
represent the truth value of an expression. For example, the expression 1 <= 2 is
True, while the expression 0 == 1 is False. Understanding how Python Boolean values
behave is important to programming well in Python.
in
Comparison Operators
Values are compared using comparison operators. After computing the condition, it
nl
returns either True or False.
O
> Greater than - True if left operand is greater than the right x>y
< Less than-True if left operand is less than the right x<y
== Equal to - True if both operands are equal x==y
ty
!= Not equal to - True if operands are not equal X !=y
>= Greater than or equal to - True if left operand is greater than x>=y
or equal to the right
si
<= Less than or equal to - True if left operand is less than or x<=y
equal to the right
Logical Operators r
ve
There are Three Logical operators: and, or, not.
A B A and B
True True True
False True False
m
The or Operator
Unless both of its inputs are False, the or operator’s value is True. The truth table
below can also be used to define the or operator:
(c
A B A and B
Notes
e
True True True
False True True
in
True False True
False False False
nl
The not Operator
Not is the only Boolean operator with only one argument. It accepts one parameter
O
and returns the polar opposite: False for True and True for False. In a truth table, it
looks like this:
A Not A
ty
True False
False True
si
This table shows that not returns the argument’s opposite truth value. Not short-
circuits because it just takes one argument. Before returning its response, it assesses
its argument.
Example r
ve
def check_Empty(list_name):
print(bool(list_name))
if __name__ == “__main__”:
ni
my_list =[]
U
check_Empty(my_list)
my_list1 =[1, 2, 3]
ity
check_Empty(my_list1)
Output
False
m
True
number = 8
if number > 0:
(c
nummber = -1
Notes
e
if number > 0:
in
print(“Welcome to Python.”)
Output
nl
8 is a positive number
O
Welcome to Python.
ty
●● If this evaluates to True, the body of if is executed.
●● When the variable number equals 3, the test expression is true, and the
statements in the body of the if statement are performed.
si
●● If the variable number equals -1, the test expression is false, and the
statements within the if body are skipped.
●● The print() statement is not contained within the if block (unindented). As a
r
result, regardless of the test expression, it is run.
ve
Example 2: python program to illustrate If statement
x = 10
ni
if (x > 8):
print(“Welcome to Python”)
U
Output
Welcome to Python
ity
x = 20
if (x < 15):
)A
Output
Notes
e
x is greater than 15
in
Welcome to Python
nl
# Explicit function
def DSum(n):
O
sum = 0
ty
sum += int(ele)
return sum
si
# Initializing list
r
ve
# Using the function on odd elements of the list
print(newList)
U
Output
[16, 3, 18, 18]
appropriate message
num = 10
if num >= 0:
m
print(“Welcome to Python”)
else:
)A
Output
Welcome to Python
(c
# If num value is -1
num = -1
if num >= 0:
Notes
e
print(“Welcome to Python”)
else:
in
print(“Welcome to pytnon if else demo”)
Output
nl
Welcome to Python if else demo
O
2.1.6 Code Snippet Showing the Use of Chained Conditional (if-elif-else)
Program 1: ‘’’In this program, we check if the number is positive or negative or
zero and display an appropriate message’’’
ty
number = 8
if num > 0:
si
print(“Positive number If block executed”)
elif num == 0:
r
print(“Zero elif block executed”)
ve
else:
Output
ni
Case 2: If is number == 0
U
Output
Zero elif block executed
ity
Case 3: If number is -8
Output
Negative number else block executed
m
Program 2:
value = 100
)A
if value == 200:
print value
(c
print value
Notes
e
elif value == 100:
in
print value
else:
nl
print “4 - Got a false expression value”
print value
O
print “Welcome to Python”
Output
ty
3 - Got a true expression value
100
si
Welcome to Python
The Python language has two looping constructs—statements that repeat an action
ni
repeatedly. The while statement is the first of them, and it allows you to create general
loops. The for statement, on the other hand, is used to walk through the items in a
sequence object and perform a block of code for each one.
U
while Loops
ity
The while statement in Python is the language’s most general iteration mechanism.
Simply said, it executes a block of (usually indented) statements repeatedly as long as
a test at the top continues to evaluate to a true value. Because control loops back to the
beginning of the statement until the test is false, it’s called a “loop.” Control goes to the
m
statement after the while block when the test is false. The result is that while the test at
the top is true, the loop’s body is executed repeatedly; if the test is false to begin with,
the body never runs.
)A
General Format
The while statement, in its most complicated form, includes a header line
containing a test expression, a body of one or more indented statements, and an
optional else portion that is performed if control exits the loop without encountering a
(c
break statement. Until the test produces a false value, Python continues to evaluate the
test at the top and execute the statements nested in the loop body:
e
<statements1> # Loop body
in
<statements2> # Run if didn’t exit loop with break
The else clause is not required. The while block’s suite is executed as long as
nl
the boolean expression is True. The loop ends if the boolean expression is False or
becomes False, and the suite is executed if the optional else clause is present. If a
continue statement is run within the while block’s suite, control is instantly restored to
O
the top of the loop, and the boolean expression is assessed again. Any optional else
clause’s suite is skipped if the loop does not finish normally.
Because the otherwise clause’s suite is always executed if the loop closes
ty
normally, the name is a little misleading. The otherwise clause’s suite is not executed
if the loop is broken out of by a break statement, a return statement (if the loop is in a
function or method), or an exception is raised. (If an exception occurs, Python bypasses
the else clause and searches for an appropriate exception handler—more on this in the
si
next section.) On the plus side, the else clause behaves the same in while loops for...in
loops and try...except blocks.
r
ve
ni
U
count = 0
count = count + 1
Output
Welcome to the world of python
for Loops
Notes
e
In Python, the for loop is a general sequence iterator that may iterate across any
ordered sequence object. The for statement works with strings, lists, tuples, and other
in
built-in iterables, as well as new objects that we’ll construct later with classes. We
briefly discussed it when we looked at sequence object types; now we’ll go over it in
more detail.
nl
General Format
A header line in the Python for loop provides an assignment target (or targets),
O
as well as the object you want to walk through. The header is followed by a block of
statements that you want to repeat (usually indented):
ty
<statements> # Repeated loop body: use target
else:
si
When Python performs a for loop, it assigns each item in the sequence object to
the target and runs the loop body for each one. The assignment target is commonly
r
used in the loop body to refer to the current item in the sequence as if it were a cursor
stepping through the sequence.
ve
A (potentially new) variable in the scope where the for statement is coded is
normally the name used as the assignment target in a for header line. There’s nothing
unique about it; it can even be changed inside the loop’s body, but when control returns
ni
to the top of the loop, it will automatically be set to the next item in the sequence.
Unless the loop ends with a break statement, this variable generally corresponds to the
last item visited, which is the last item in the sequence.
U
The for statement also has an optional else block, which is executed if the loop
finishes without hitting a break statement, just like in a while loop (i.e., if all items in the
sequence have been visited). The break and continue statements work the same way in
a for loop as they do in a while loop. The whole format of the for loop is as follows:
ity
<statements>
else:
)A
Notes
e
in
nl
O
ty
Figure: For loop Statement Flowchart
si
Examples
Now, let’s type a few for loops interactively to see how they’re utilised in practice.
Basic Usage
r
ve
A for loop, as previously stated, can step through any type of sequence object. For
example, in our first example, we’ll assign the name x to each of the three elements in a
list, one by one, from left to right, and then run the print statement for each. The name x
ni
refers to the current item in the list inside the print statement (the loop body):
...
Output
ity
The sum and product of all the elements in a list are computed in the next
two instances. We’ll meet utilities that apply operations like + and * to items in
a list automatically later in this chapter and later in the book, but it’s typically just as
m
>>> sum = 0
)A
...
(c
>>> sum
Output
Notes
e
15
>>> prod = 1
in
>>> for item in [1, 2, 3, 4,5]: prod *= item
...
nl
>>> prod
Output
O
120
Nested Loops: The Python programming language allows you to nest loops inside
loops. A few examples are provided in the next section to demonstrate the concept.
ty
for iterator_var in sequence:
si
statements(s)
statements(s)
r
Code: Python program to illustrate nested for loops in Python
ve
import print_function
for j in range(i):
ni
print(i, end=’ ‘)
print()
U
Output
1
ity
2 2
3 3 3
4 4 4 4
m
a = [1, 2, 3, 4, 5]
while a:
print(a.pop())
(c
Output
Notes
e
5
in
3
nl
1
In the preceding example, we ran a while loop through a list that will continue to run
O
until an element in the list is found.
ty
block consists of a single sentence. Semicolons can be used to separate numerous
statements in the block that makes up the loop body (;).
si
demo = 0
Code 3: While loop with else: Python program to demonstrate while-else loop
ity
a = 0
while a < 4:
a += 1
print(i)
m
while i < 4:
i += 1
print(i)
break
(c
Output
Notes
e
1
in
3
nl
No Break
O
2.2.3 Code Snippet Showing the Use of for Statement
ty
print(“List Iteration”)
si
for i in l:
print(i)
r
print(“\nTuple Iteration”)
ve
t = (“Welcome”, “To”, “Python”)
for i in t:
print(i)
ni
print(“\nString Iteration”)
s = “Python”
U
for i in s :
print(i)
ity
print(“\nDictionary Iteration”)
d = dict()
d[‘mno’] = 123
m
d[‘pqr’] = 345
for i in d :
print(“\nSet Iteration”)
set1 = {1,2,3,4,5,6}
for i in set1:
(c
print(i),
Output
Notes
e
List Iteration
Welcome
in
to
Python
nl
Tuple Iteration
Welcome
O
to
Python
ty
String Iteration
si
T
O
r
ve
N
Dictionary Iteration
ni
mno 123
pqr 345
sequence’s index. The fundamental concept is to calculate the list’s length first, then
loop over the sequence within that range.
print list[index]
Output
)A
Welcome
To
Python
(c
Using the else statement with for loops: Similar to the while loop, we can use the
else statement with for loops. However, because there is no condition in the for loop
that will cause the execution to end, the otherwise block will be run immediately after
Notes
e
the for block.
in
Code 2: Python program to illustrate combining else with for
nl
for index in range(len(list)):
print list[index]
O
else:
ty
Output:
Welcome
To
si
Python
C++, Java, and so on) in favour of if conditional statements. With for loops, Python also
allows us to employ the else condition.
Note: When the loop is not terminated by a break statement, the else block directly
U
print(i)
print(“Without Break\n”)
print(i)
break
print(“Without Break”)
(c
Output
Notes
e
1
in
3
No Break
nl
1
O
Code 2: Python for loop with range function: Python Program to show range()
basics printing a number
for a in range(10):
ty
print(a, end=” “)
print()
si
# using range for iteration
for a in range(len(loop)): r
ve
print(loop[a], end=” “)
print()
addition = 0
addition = addition + i
Output
0 1 2 3 4 5 6 7 8 9
10 20 30 40
m
generated in a scope are deleted when execution exits that scope. The following control
statements are supported by Python.
●● Break statement
Notes
e
●● Continue statement
●● Pass statement
in
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until the test expression is false, but sometimes
we wish to terminate the current iteration or even the whole loop without checking
nl
test expression.
O
The break statement is used to end a loop or statement in which it appears. The
control will then move to the statements that follow the break statement, if any are
present. If the break statement is present in the nested loop, only those loops that
ty
contain the break statement are terminated.
Syntax:
si
Break
r
ve
ni
U
ity
m
The working of break statement in for loop and while loop is shown below.
)A
(c
Notes
e
in
nl
O
ty
si
Working of the break statement
The break statement causes an immediate exit from a loop. Because the code that
follows it in the loop is not executed if the break is reached, you can also sometimes
r
avoid nesting by including a break. For example, here is a simple interactive loop that
ve
inputs data with input (known as raw_input in Python 2.6) and exits when the user
enters “stop” for the name request:
Example
ni
...
Output
Please Enter Name: Tanvi
m
e
Like the break statement, continue is a loop control statement. The continue
statement is the polar opposite of the break statement in that it forces the loop to
in
perform the next iteration rather than ending it.
The continue statement, as the name implies forces the loop to continue or execute
the next iteration. When the continue statement is used in a loop, the code inside the
nl
loop that follows the continue statement is skipped, and the loop’s next iteration begins.
O
ty
r si
ve
Figure: Flowchart of continue Statement
ni
The for and while loops’ use of the continue command is demonstrated below.
U
ity
m
)A
The continue statement jumps to the top of a loop right away. It can also help
you avoid statement nesting in some cases. Continue to skip odd numbers in the
next example. This code displays all even values less than ten that are larger than or
(c
equal to zero. Because 0 denotes false and percent denotes the remainder of division
operator, this loop counts down to 0 while ignoring integers that aren’t multiples of 2
(printing 8 6 4 2 0):
Amity Directorate of Distance & Online Education
Python Programming 81
x = 10
Notes
e
while x:
x = x−1 # Or, x -= 1
in
if x % 2 != 0: continue # Odd? -- skip print
print(x, end=’ ‘)
nl
You don’t need to nest the print statement within an if test since continue jumps to
the top of the loop; the print is only accessed if the continue isn’t run. This should sound
comparable to a “goto” in other languages. Although Python lacks a “goto” command,
O
because continue allows you to bounce around in a programme, all of the readability
and maintainability concerns that you might have heard about goto apply. Continue
should definitely be used sparingly at first, especially if you’re new to Python. The last
ty
example for example, may be clearer if the print was nested beneath the if:
x = 10
while x:
si
x = x−1
if x % 2 == 0: # Even? -- print
print(x, end=’ ‘)
r
ve
Pass statement
The pass statement, as its name implies, does nothing. When a statement is
required syntactically but no command or code is to be executed, the pass statement
ni
is used in Python. It’s similar to a null operation in that if it’s run, nothing happens. The
pass statement can be used to create empty loops as well. Pass can also be used to
represent an empty control statement, function, or class.
U
Syntax:
pass
ity
s = “python”
# Empty loop
m
for i in s:
pass
# Empty function
def fun():
pass
(c
fun()
Notes
e
# Pass statement
for i in s:
in
if i == ‘t’:
print(‘Pass executed’)
nl
pass
print(i)
O
Output
p
ty
y
pass executed
si
t
o
r
ve
n
the characters until you reach the letter ‘e’ or’s’. It is mentioned that you must perform
this with a loop, and that you may only use one loop.
Here’s when the break statement comes into play. We can iterate over a string
U
using either a while loop or a for loop, and compare the value of iterator with ‘e’ or’s’
each time. If it’s a ‘e’ or an’s,’ we’ll break the loop with the break statement.
s = ‘Welcometopython’
for letter in s:
m
print(letter)
break
print()
i = 0
e
print(s[i])
in
if s[i] == ‘e’ or s[i] == ‘s’:
break
nl
i += 1
O
Output
w
ty
e
l
c
si
o
Out of for loop
r
ve
w
e
Out of while loop
ni
Code 2:
variable = 10
U
variable = variable -1
ity
if variable == 5:
break
Output
Current variable value : 10
)A
Welcome to python
e
Consider the following scenario: you need to develop a programme that prints
numbers from 1 to 10, but not 6. It is mentioned that you must perform this with a loop,
in
and that you may only use one loop.
Here’s when the continue statement comes into play. We can run a loop from 1
to 10 and compare the value of iterator with 6 each time. If it equals 6, we’ll use the
nl
continue statement to skip to the next iteration without writing anything; otherwise, the
value will be printed.
The following is how the aforementioned concept was put into action:
O
# Python program to demonstrate continue statement loop from 1 to 10
ty
# If i is equals to 7,
si
# continue to next iteration
# without printing
if i == 7:
r
ve
continue
else:
# of i
print(i, end = “ “)
U
Output
1 2 3 4 5 6 8 9 10
ity
Code 2:
for letter in ‘Python’:
if letter == ‘y’:
m
continue
Output
Current Letter : P
Current Letter : t
Current Letter : h
(c
Current Letter : o
Current Letter : n
Amity Directorate of Distance & Online Education
Python Programming 85
Code 3:
Notes
e
variable = 10
in
variable = variable -1
if variable == 5:
nl
continue
O
print “Welcome to Python Demo”
Output
ty
Current variable value : 10
Current variable value : 9
Current variable value : 8
si
Current variable value : 7
Current variable value : 6
Current variable value : 4 r
ve
Current variable value : 3
Current variable value : 2
Current variable value : 1
ni
Summary
U
contain other statements, including other ifs. In fact, Python allows you to nest
statements sequentially (so they run one after the other) (so that they execute only
under certain conditions).
)A
●● If a condition is true, the if statement will execute a block of statements. But what
if the condition is false? Then comes the otherwise statement. If the condition is
false, the else statement and the if statement can be used to run code.
●● An if statement that targets another if statement is nested. An if statement inside
(c
another if statement. Yes, Python allows us to nest if statements, i.e., we can nest
if statements.
●● The if statements run from top to bottom. If one of the if conditions is true, the
Notes
e
statement associated with that if is performed, bypassing the remainder of the
ladder. No criteria are met, hence the else statement is performed.
in
●● Every programming language has booleans, which are simple ideas. A boolean
represents “true” or “false”. When writing an algorithm or a programme, we often
want to run different code in different situations. Our code can use Booleans to do
nl
just that. A boolean value is typically returned as a result of a comparison.
●● Boolean keywords: True and False operators: Operators are special symbols in
Python that perform arithmetic and logical calculations. Operands are the values
O
that will be operated on. An operator (for example, +, -, /, *, percent) denotes
the operation. Python’s built-in Boolean data type. It represents an expression’s
truth value. For example, 1 = 2 is True, but 0 = 1 is False. Understanding Python
Boolean values is critical to good Python programming.
ty
●● Python’s while statement is its most general iteration mechanism. Simply put, it
repeats a block of (typically indented) statements as long as the top test evaluates
to true. Control cycles back to the beginning of the sentence until the test fails. If
si
the test fails, control moves to the statement after the while block. If the top test is
true, the loop’s body repeats endlessly; if it is false, the body never runs.
●● The for loop iterates across any ordered sequence object in Python. Objects that
r
we’ll create later with classes can be iterated using the for statement. We touched
ve
on it briefly when looking at sequence object types; now we’ll dig deeper.
●● In a for loop, Python assigns the target to each item in the sequence and runs the
loop body for each. The assignment target is typically used in the loop body to
refer to the current item in the sequence.
ni
●● The assignment target in a for header line is usually a (possibly new) variable in
the scope where the for statement is coded. Changing it inside the loop’s body is
possible, but when control returns to the loop’s top, it will automatically be set to
U
the next item in the sequence. Unless the loop finishes with a break, this variable
refers to the final item visited in the sequence.
●● Loops are used to automate and repeat tasks in Python. You may choose to exit
ity
the loop, skip one iteration, or ignore the condition. Use loop control statements
to do this. Change the execution sequence of loop control statements When an
execution quits a scope, all automated objects are removed. Python supports the
following control statements.
m
a) Break
b) Continue
c) Pass
)A
●● The break statement is used to end a loop or statement in which it appears. The
control will then move to the statements that follow the break statement, if any are
present. If the break statement is present in the nested loop, only those loops that
contain the break statement are terminated.
(c
●● The continue statement forces the loop to iterate. When used in a loop, the code
after the continue statement is skipped, and the loop’s next iteration begins.
●● The pass statement does nothing. The pass statement is used in Python when
Notes
e
a statement is required but no command or code is to be run. It’s like a null
operation in that it does nothing. Pass can also be used to construct empty loops.
Pass can also represent a blank control statement, function, or class.
in
Glossary
●● Elif: else if
nl
●● Logical Operators: There are Three Logical operators: and, or, not.
●● and Operator: There are two arguments for the and operator. Unless both inputs
O
are True, it evaluates to False.
●● or Operator: Unless both of its inputs are False, the or operator’s value is True
●● not Operator: Not is the only Boolean operator with only one argument. It accepts
ty
one parameter and returns the polar opposite: False for True and True for False.
●● while Loops: it executes a block of (usually indented) statements repeatedly as
long as a test at the top continues to evaluate to a true value.
si
●● for Loops: The for loop iterates across any ordered sequence object in Python.
Objects that we’ll create later with classes can be iterated using the for statement.
●●
r
Nested Loops: Loops inside loops are termed as nested loops.
ve
●● Python for loop with range function: Python Program to show range() basics
printing a number.
●● Break statement: The break statement is used to end a loop or statement in
which it appears
ni
●● Continue Statement: The continue statement, as the name implies forces the
loop to continue or execute the next iteration.
●● Pass statement: When a statement is required syntactically but no command or
U
we wish to terminate the current iteration or even the whole loop without checking
test expression.
c. Or
d. Modulo
e. none of the above.
2. In Python, _ _ _ _ _ _ statement is used for decision making.
(c
a. for
b. while
c. do while
Notes
e
e. if else elif
3. Values are compared using_ _ _ _ _ _ operators.
in
a. conditional
b. logical
nl
c. comparison
d. none of the above
O
4. _ _ _ _ _ _ _ _ _are the values on which the operation will be performed.
a. operands
b. operators
ty
c. operations
d. all of the above
si
5. What will be the output of the given below program:
# inputs
X = 10
Y = 4 r
ve
# Stores the remainder obtained when dividing X by Y, in Z
Z = X % Y
print(X, “mod”, Y, “=”,Z, sep = “ “)
ni
# inputs
M = 25.0
U
N = 6.0
# Stores the remainder obtained
# when dividing M by N, in O
ity
O = M % N
print(M, “mod”, N, “=”,O, sep = “ “)
a. 13 mod 5 = 3
m
c. 10 mod 4 = 0
25.0 mod 6.0 = 0
d. 10 mod 4 = 3
(c
e
long as a test at the top continues to evaluate to a true value.
a. Do while
in
b. for
c. while
nl
d. none of the above
7. The_ __ _ _ _ _ loop is a general sequence iterator that may iterate across any
ordered sequence object.
O
a. for
b. while
c. do while
ty
d. all of the above
8. What will be the output of following program:
si
import print_function
for j in range(i): r
ve
print(i, end=’ ‘)
print()
a. 1
ni
22
333
U
4444
b. 2
33
ity
444
5555
c. 11
m
222
3333
)A
4444
d. 22
33
444
(c
5555
e
a = [1, 2, 3, 4, 5]
while a:
in
print(a.pop()).
a. 1
nl
2
3
O
4
5
b. 5
ty
4
3
si
2
1
c. 2
r
ve
3
4
5
ni
print(a, end=” “)
print()
ity
for a in range(len(loop)):
m
print(loop[a], end=” “)
print()
)A
addition = 0
addition = addition + i
(c
a. 0123456789
Notes
e
10 15 20 25
Addition of first 10 numbers: 35
in
b. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
10 20 30 40
nl
Addition of first 10 numbers: 50
c. 1 2 3 4 5 6 7 8 9 10 11 12 13 14
O
15 20 25 30
Addition of first 10 numbers: 30
d. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
ty
15 20 25 30
Addition of first 10 numbers: 45
si
11. The _ _ _ _ _ _statement is used to end a loop or statement in which it appears.
a. break
b. for
c. continue
r
ve
d. none of the above
12. The_ _ _ _ _ statement forces the loop to continue or execute the next iteration.
a. break
ni
b. pass
c. continue
U
a. Continue
b. Pass
c. Break
m
# If i is equals to 9,
# without printing
if i == 9:
Notes
e
continue
else:
in
# otherwise print the value
# of i
nl
print(i, end = “ “)
a. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
O
b. 1 2 3 4 5 6 8 9 10 11 12 13 14 15
c. 1 2 3 4 5 6 7 8 9 11 12 13 14 15
d. 1 2 3 4 5 6 7 8 10 11 12 13 14
ty
15. What will be the output of the given below program:
variable = 9
si
while variable> 0:
print ‘Current variable value :’, variable
r
variable = variable -1
if variable == 4:
ve
break
print “Welcome to python”
Welcome to python
d. None of the above
Exercise
Notes
e
1. Define conditional statements.
2. Explain modulus operator.
in
3. What do you mean by conditional (if), alternative (if-else), chained conditional (if-elif-
else)?
nl
4. Define boolean expression and logical expression.
5. Explain while loop.
6. Explain for statement and enhanced for statement.
O
7. Explain break statement.
8. Explain continue statement.
ty
Learning Activities
1 Create a Python program showing the use of if statement.
si
2 Create a Python program showing the Use of Alternative (if-else).
3 Create a Python program showing Use of Chained Conditional (if-elif-else).
4 Create a Python program showing the use of while statement.
5
r
Create a Python program showing the use of for statement.
ve
6 Create a Python program showing the use of enhanced for statement.
1 c
2 d
3 c
U
4 a
5 b
ity
6 c
7 a
8 a
9 c
m
10 d
11 a
)A
12 c
13 a
14 d
(c
15 a
e
1. Learn Python the Hard Way, Zed Shaw
2. Python Cookbook: Recipes for Mastering Python 3, Brian K. Jones and David
in
M. Beazley
3. Python for Everybody: Exploring Data Using Python 3, Charles Severance
nl
4. Think Python: An Introduction to Software Design, Allen B. Downey
5. Programming Python, Mark Lutz
6. Dive into Python, Mark Pilgrim
O
ty
r si
ve
ni
U
ity
m
)A
(c
e
Learning Objectives:
in
At the end of this module, you will be able to understand:
●● Concept of Functions
nl
●● Function Definition and Use, Flow of Execution
●● Parameter and Arguments
O
●● Illustrative Programs: Exchange the Values of Two Variables using Functions
●● Type Conversion Function, Adding New Function
●● Math Function, Composition
ty
●● Traversal with a Code Snippet
●● Comparison with a Code Snippet
si
●● Searching with a Code Snippet
●● Counting with a Code Snippet
●● Alternatives to Hiring Permanent Employees
●● Pre-defined String Functions
r
ve
●● Use of IN Operator
Introduction
ni
from time to time. When we code an action as a function, we have a universally helpful
tool that we can utilise in a variety of situations.
Tri recursion() is a function that we have defined to call itself in this example
(“recurse”). The data is the k variable, which decrements (-1) each time we recurse.
When the criterion is not larger than 0, the recursion finishes (i.e. when it is 0).
)A
It can take some time for a new developer to figure out how this works; the best
approach to find out is to test and tweak it.
Tail-Recursion
A special sort of recursion in which a function’s last procedure is a recursive call.
(c
Instead of establishing a new stack frame, the loop can be avoided by processing the
request in the current stack frame and returning the output. The compiler may optimise
tail-recursion, making it better than non-tail recursive functions.
e
function to optimise a programme?
When we look at the function below to calculate the factorial of n, we can see that
in
it appears to be a tail-recursive function at first glance, however it is actually a non-tail-
recursive function. If we look closely, we can see that Recur facto(n-1) returns a value
that is utilised in Recur facto(n), indicating that the call to Recur facto(n-1) is not the last
nl
thing Recur facto does (n).
O
More fundamentally, functions are a replacement for cutting and pasting programming:
instead of having numerous redundant copies of an operation’s code, we may factor it into a
single function. By doing so, we drastically reduce our future work: if the operation needs to
be updated later, we only have one copy to update, rather than several.
ty
Python’s most fundamental programme structure for maximising code reuse and
decreasing code redundancy is functions.
si
3.1.1 Concept of Functions
As we’ll see, functions are also a design tool that lets us split complex systems into
r
manageable parts. Table below summarizes the primary function-related tools.
ve
Table: Function-related statements and expressions
Statement Example
calls myfunc(‘atharv’, ‘tanvi’, ‘sid’)
ni
languages like C. Here’s a quick rundown of the key concepts behind Python functions.
1. def is executable code: A new statement, the def, is used to write Python
functions. Unlike functions in compiled languages like C, def is an executable
)A
statement, which means your function doesn’t exist until Python gets to it and
runs it. In fact, nesting def statements inside if statements, while loops, and
even other defs is acceptable (and even advantageous). Def statements are
coded in module files and are automatically invoked to construct functions
when a module file is first imported in normal operation.
(c
2. def creates an object and assigns it to a name: Python creates a new function
object and assigns it to the function’s name when it reaches and executes a def
statement. The function name, like all assignments, becomes a reference to the
Notes
e
function object. The name of a function isn’t special; as you’ll see, the function
object can be given different names, put in a list, and so on. To capture data,
function objects can also have arbitrary user-defined characteristics added to them.
in
3. lambda creates an object but returns it as a result: The lambda expression,
a feature that allows us to in-line function declarations in areas where a def
statement won’t work syntactically (this is a more advanced concept), can also
nl
be used to construct functions.
4. return sends a result object back to the caller: When a function is called, the
O
caller must wait for the function to complete its task before returning control to
the caller. Return statements are used by functions that compute a value and
return it to the caller; the returned value becomes the result of the function call.
5. yield sends a result object back to the caller but remembers where it left
ty
off: The yield statement can also be used by generator functions to return a
value and suspend their state so that they can be restarted later to create a
succession of results over time.
si
6. global declares module-level variables that are to be assigned: By default,
any names assigned to a function are temporary and only exist while the
function is running. Functions must list a name in a global statement to assign
r
it to the surrounding module. Names are always searched up in scopes, which
ve
are storage locations for variables, and assignments bind names to scopes.
7. nonlocal declares enclosing function variables that are to be assigned: A
function can also assign a name that exists within the scope of a syntactically
enclosing def declaration using the nonlocal statement, which was introduced
ni
in Python 3.0. This eliminates the need for common global names and allows
enclosing functions to serve as a repository for state (information remembered
when a function is invoked).
U
of an argument within a function does not change the caller’s equivalent name
but changing passed-in mutable objects can change the caller’s shared objects.
9. Arguments, return values, and variables are not declared: Functions, like
everything else in Python, have no type limitations. In fact, there is no requirement
m
to specify anything about a function ahead of time: you can send in any type of
argument, return any type of object, and so on. As a result, a single function
can be applied to a wide range of object types—any objects with a compatible
)A
def Statements
The def statement creates a function object and assigns it to a name. Its general
format is as follows:
(c
<statements>
Def, like all compound Python statements, starts with a header line and then a
Notes
e
block of statements, which are usually indented (or a simple statement after the colon).
The body of the function is the statement block, which is the code Python performs
each time the function is called.
in
The def header line contains a function name for which the function object is
assigned, as well as a list of zero or more arguments (also known as parameters)
nl
enclosed in parentheses. The object names given in parenthesis at the moment of call
are assigned to the argument names in the header.
O
def (arg1, arg2,... argN):
...
ty
return
The return statement in Python can appear anywhere in the body of a function; it
terminates the function call and returns a result to the caller. The return statement is
si
made up of an object expression that returns the outcome of the function. The function
quits if the control flow falls off the end of the function body if the return statement is not
present. A function that does not include a return statement returns the None object by
r
default, however this result is normally ignored.
ve
def Executes at Runtime
The Python def statement is a genuine executable statement in that it generates a
new function object and names it. (Remember that with Python, we just have runtime;
there is no separate compile time.) A def can exist anywhere a statement can, including
ni
nested in other statements, because it’s a statement. Although defs are usually called
when the module containing them is imported, it’s quite permissible to nest a function
def inside an if statement to choose between different definitions:
U
if test:
def func(): # Define func this way
ity
...
else:
def func(): # Or else this way
...
m
...
func() # Call the version selected and built
)A
One way to think about this code is that the def is similar to a = statement in that it
just assigns a name at runtime. Python functions, unlike those in compiled languages
like C, do not need to be fully defined before the programme can start. Defines aren’t
evaluated until they’re reached and run, and the code inside defs isn’t evaluated until
the functions are invoked later.
(c
Because function definition takes place during runtime, the function name is
unremarkable. It’s the object to which it refers that matters:
e
othername() # Call func again
The function was given a new name and was called using that name.
in
Functions, like everything else in Python, are essentially objects that are deliberately
stored in memory during programme execution. In fact, functions allow arbitrary
nl
characteristics to be added to record information for later use, in addition to calls:
O
func.attr = value # Attach attributes
ty
Apart from such runtime notions (which are most unfamiliar to programmers with
backgrounds in traditional compiled languages), Python functions are simple to utilise.
Let’s start with a real-world scenario to show the fundamentals. As you can see, a
si
function definition (the def that creates a function) and a call (an expression that tells
Python to run the function’s body) are two sides of the same coin.
Definition r
ve
Here’s an interactively typed definition for the times function, which returns the
product of its two arguments:
...
Python produces a new function object that packages the function’s code and
U
assigns the object to the name times when it reaches and performs this def. Normally,
a statement like this is coded in a module file and executed when the enclosing file is
imported; however, for anything this little, the interactive prompt suffices.
ity
Calls
You can call (run) the function in your programme after the def has completed by
putting parentheses after the function’s name. One or more object arguments may be
provided (assigned) to the names in the function’s header via the parentheses:
m
8
)A
This expression sends two arguments to the times function. As previously stated,
arguments are supplied by assignment, therefore the value 2 is assigned to the name
x in the function header, the value 4 is allocated to y, and the method’s body is run.
The body of this function is simply a return statement that returns the result as the
(c
call expression’s value. The resultant object was printed interactively (like in other
languages, 2 * 4 equals 8 in Python), but we could assign it to a variable if we needed
to use it later. Consider the following scenario:
e
>>> x
12.56
in
Now see what happens when the function is called a third time, with objects of
quite different types handed in:
nl
times(‘Python’, 4) # Functions are “typeless”
‘ PythonPythonPythonPython ‘
O
This time, our function has an entirely different meaning (Monty Python reference
again intended). Instead of two numbers, a string and an integer are supplied to x and y
in this third call. Because the types of variables, arguments, and return values are never
declared in Python, we can use times to multiply integers or repeat sequences.
ty
3.1.2 Function Definition and Use, Flow of Execution
In computer programming, a function is a named section of a code that performs
si
a specific task. This typically involves taking some input, manipulating the input and
returning an output.
r
Python Functions are a group of related statements that are used to accomplish
a computational, logical, or evaluative activity in Python. The goal is to group together
ve
some often performed actions and create a function, so that instead of writing the same
code over and over for different inputs, we may call the function and reuse the code
contained within it.
ni
Built-in and user-defined functions are both possible. It aids in keeping the
programme concise, non-repetitive, and well-organized.
You can create functions to offer the functionality you need. To define a function in
U
●● The term def is followed by the function name and parentheses (()) in a
function block.
ity
●● Every function’s code block begins with a colon (:) and is indented.
●● The return [expression] statement leaves a function and optionally returns an
expression to the caller. Return None is the same as a return statement with
)A
no arguments.
Uses of Function
Let’s obtain a clear sense of what functions are all about before we dive into the
intricacies. Functions are a common tool for structuring programmes. You might have
(c
seen them earlier in other languages, where they were referred to as subroutines or
procedures. Functions, in a nutshell, fulfil two fundamental development roles:
Maximizing code reuse and minimizing redundancy: Python functions, like other
Notes
e
programming languages, are the simplest method to package logic that you may want
to utilise in multiple places and at different times. Until now, all of the code we’ve written
has run instantly. Functions allow us to aggregate and generalise code such that it can
in
be reused indefinitely. Python functions are the most basic factoring tool in the language
since they allow us to code an operation once and use it many times: they help us to
eliminate code repetition in our programmes and hence reduce maintenance effort.
nl
Procedural decomposition: Functions can also be used to divide systems into
components with clearly defined roles. To create a pizza from scratch for example,
you would begin by preparing the dough, rolling it out, topping it, baking it, and so on.
O
Functions would allow you separate the main “create pizza” work into chunks if you
were programming a pizza-making robot—one function for each subtask in the process.
It’s easier to accomplish smaller tasks one at a time rather than the complete procedure
ty
all at once. Functions, in general, are about procedure—how to do something rather
than who you’re doing it for.
Syntax:
si
def function_name(parameters):
“””docstring”””
statement(s) r
ve
return expression
Docstrings
The docstring, short for documentation string, is the first string after the function
ni
document your code unless you remember what you had for dinner the night before.
A docstring appears immediately below the function header in the example above.
To allow the docstring to span multiple lines, we usually use triple quotes. The __doc__
attribute of the function makes this string available to us.
ity
Creating a Function
The def keyword can be used to build a Python function.
m
def fun():
Output
Welcome to world of Python
(c
Calling a Function
Notes
e
After constructing a function, we may call it by using the function’s name followed
by parenthesis containing the function’s parameters.
in
Example: Python Calling Function
nl
def fun():
O
# Driver code to call a function
fun()
Output
ty
Welcome to world of Python
Arguments of a Function
si
After constructing a function, we may call it by using the function’s name followed
by parenthesis containing the function’s parameters.
r
Example: Python Function with arguments
ve
In this example, we’ll write a basic function to determine whether the integer
handed in as an input is even or odd.
def evenOdd(a):
if (a % 2 == 0):
U
print(“even”)
else:
ity
print(“odd”)
evenOdd(22)
m
evenOdd(31)
Output
)A
even
odd
(c
Notes
e
in
nl
O
Function works in Python
Types of Functions
ty
Basically, we can divide functions into the following two types:
si
Some of the pre-defined built-in functions in python are:
Built-in functions are functions that come pre-installed with Python. Library
functions are when we employ functions written by others in the form of a library.
User-defined functions encompass all other functions that we create on our own.
m
e
Parameters:
in
The variable defined within the parentheses during function definition is referred to
as a parameter. When we declare a function, they are simply written.
nl
def sum(a,b):
print(a+b)
O
sum(1,2)
Arguments
ty
When a function is called, an argument is a value that is supplied to it. It could be
a variable, value, or object that is supplied as input to a function or method. They are
written when the function is called.
si
Here’s a breakdown of the most important aspects to remember when giving
arguments to functions:
caller: When the function executes in the scope of the function, the argument
names in the function header become new, local names. In the caller’s scope,
there is no aliasing between function argument names and variable names.
U
Immutable arguments are effectively passed “by value”: Integers and strings
are passed by object reference rather than copying, but because you can’t edit
immutable objects in-place anyhow, the result is similar to copying.
)A
Mutable arguments are effectively passed “by pointer.” Objects like lists and
dictionaries are passed by object reference, which is analogous to how C passes arrays
as pointers—mutable objects, like C arrays, can be updated in-place in the function.
even simpler—it entails simply assigning objects to names, and it works regardless of
whether the objects are changeable or not.
e
Arguments to Python functions can be of two types:
1. Positional Arguments
in
2. Keyword Arguments
Positional Arguments:
nl
Positional arguments must be listed in the correct order when the function is called
for example, the first argument must always be listed first when the function is called,
O
the second argument must be called second, and so on.
Example:
def person_name(maiden_name,last_name):
ty
print(maiden_name+last_name)
si
# Second name is Atharv place second
person_name(“Tanvi”,”Atharv”)
Output r
ve
TanviAtharv
Keyword Arguments:
Keyword Arguments are arguments that are preceded by a keyword and an equal to
ni
sign and are passed to a function or method. Because the values are expressly assigned,
the order of a keyword argument in relation to another keyword argument is irrelevant.
U
def person_name(maiden_name,last_name):
print(maiden_name+last_name)
person_name(second_name=”Atharv”,first_name=”Tanvi”)
Output
TanviAtaharv
m
Imagine a function that processes a set of passed-in objects and allows a tracing
flag to be passed:
e
process(X, Y, notify=True) # override flag default
We have to use both *args and **args and manually inspect the keywords if we
in
don’t use keyword-only arguments, yet keyword-only arguments need less code. If
passed, the following ensures that no positional argument is wrongly matched against
notify and requires that it be a keyword:
nl
*args and **kwargs in Python
We can use special symbols in Python to pass a variable number of arguments to
O
a function. There are two other symbols to be aware of:
ty
r si
ve
Note: “We use the “wildcard” or “*” notation like this - *args OR **kwargs-as our
function’s argument when we have doubts about the number of arguments we
should pass in a function.”
ni
1.) *args
In Python function definitions, the special syntax *args is used to pass a variable
number of arguments to a function. It’s used to pass a variable-length, non-keyworded
U
argument list.
●● You can use *args to take in more arguments than the number of formal
arguments you defined previously. Any number of additional arguments can
be tacked on to your current formal parameters with *args (including zero
extra arguments).
m
●● For instance, we’d like to create a multiply function that can take any number of
arguments and multiply them all together. *args can be used to accomplish this.
●● When we use the *, the variable we associate with the * becomes an iterable,
)A
which means we can iterate over it, perform higher-order functions like map
and filter, and so on.
# Python program to illustrate *args for variable number of arguments
def myFun(*argv):
for arg in argv:
(c
print (arg)
myFun(‘Hello’, ‘Welcome’, ‘to’, ‘Python’)
Output
Notes
e
Hello
Welcome
in
to
Python
nl
# Python program to illustrate *args with first extra argument
O
print (“First argument :”, arg1)
ty
print(“Next argument through *argv :”, arg)
si
Output
First argument : Hello
r
ve
Next argument through *argv : Welcome
2.)**kwargs
**kwargs is a special syntax used in Python function definitions to pass a
U
●● When you pass a variable into a function as a keyword argument, you give it a name.
ity
●● The kwargs can be thought of as a dictionary that maps each term to the
value we pass along with it. That’s why there doesn’t appear to be any
sequence in which the kwargs were printed out when we iterate over them.
Example for usage of **kwargs:
m
def myFun(**kwargs):
# Driver code
Output
Notes
e
last == Python
mid == to
in
first == Welcome
nl
def myFun(arg1, arg2, arg3):
print(“arg1:”, arg1)
O
print(“arg2:”, arg2)
print(“arg3:”, arg3)
ty
# Now we can use *args or **kwargs to
si
args = (“Welcome”, “to”, “Python”)
myFun(*args)
r
ve
kwargs = {“arg1” : “Welcome”, “arg2” : “to”, “arg3” : “Python”}
myFun(**kwargs)
ni
Output
arg1: Welcome
U
arg2: to
arg3: Python
arg1: Welcome
ity
arg2: to
arg3: Python
m
def exchange(x,y):
x,y=y,x
Amity Directorate of Distance & Online Education
Python Programming 109
return x,y
Notes
e
a=int(input(“Enter Number: “))
in
b=int(input(“Enter Number: “))
a,b=exchange(a,b)
nl
print(“After exchanging a becomes :”,a)
print(“After exchanging b becomes :”,b)
O
Output
Enter Number : 20
Enter Number : 30
ty
Before exchanging a : 20
Before exchanging b : 30
After exchanging a becomes : 30
si
After exchanging b becomes : 20
x,y=y,x
print(“After exchanging a becomes :”,x)
U
exchange(a,b)
m
Output
Enter Number : 200
)A
e
def swap():
in
y=int(input(“Enter number : “))
nl
print(“Before exchanging b :”,y)
O
x,y=y,x
return x,y
ty
a,b=swap()
si
Output
Enter Number : 15
r
ve
Enter Number : 18
Before exchanging a : 15
Before exchanging b : 18
ni
x,y=y,x
)A
swap()
Output
Notes
e
Enter Number : 15
Enter Number : 18
in
Before exchanging a : 15
Before exchanging b : 18
nl
After exchanging a becomes : 18
O
3.1.5 Type Conversion Function, Adding New Function
Python has type conversion functions that allow you to convert one data type to another
ty
directly, which is important in both everyday programming and competitive programming. The
purpose of this page is to provide information on a few conversion functions.
si
●● Implicit Type Conversion
●● Explicit Type Conversion
Let’s discuss them in detail.
r
ve
Implicit Type Conversion
The Python interpreter automatically changes one data type to another without the
user’s intervention through implicit type conversion of data types. See the examples
ni
Example
a = 10
U
print(“a is of type:”,type(a))
b = 10.6
ity
print(“b is of type:”,type(b))
a = x + y
print(a)
m
print(“a is of type:”,type(a))
Output
)A
20.6
(c
As we can see, the type of ‘a’ was automatically changed from “integer” to “float”
Notes
e
type. This is a simple example of Python’s implicit type conversion.
in
In Python’s Explicit Type Conversion, the data type is manually modified by the user to
suit their needs. The following sections describe various types of explicit type conversion:
nl
1. int(a, base): Any data type can be converted to an integer with this function. If
the data type is a string, ‘Base’ defines the base in which string is stored.
2. float(): Any data format can be converted to a floating-point number with this
O
function.
# Python program to exhibit Type conversion using int(), float()
# initializing string
ty
s = “10010”
si
c = int(s,2)
print (c) r
ve
# printing string converting to float
e = float(s)
print (e)
Output
U
s = ‘4’
c = ord(s)
(c
print (c)
Notes
e
# printing integer converting to hexadecimal string
c = hex(56)
in
print (“After converting 56 to hexadecimal string : “,end=””)
print (c)
nl
# printing integer converting to octal string
c = oct(56)
O
print (“After converting 56 to octal string : “,end=””)
print (c)
ty
Output
After converting character to integer : 52
si
After converting 56 to hexadecimal string : 0x38
# initializing string
U
s = ‘Python’
c = tuple(s)
ity
print (c)
c = set(s)
print (c)
c = list(s)
(c
print (c)
Output
Notes
e
After converting string to tuple : (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
in
After converting string to list : [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
nl
10. str() : To convert an integer to a string, use this function.
11. complex(real,imag): Real numbers are converted to complex(real,imag)
O
numbers using this function.
# Python code to demonstrate Type conversion
ty
# initializing integers
x = 1
si
y = 2
# initializing tuple
r
tup = ((‘x’, 1) ,(‘y’, 2), (‘g’, 3))
ve
# printing integer converting to complex number
z = complex(1,2)
print (z)
z = str(x)
print (z)
ity
z = dict(tup)
print (z)
)A
Output
After converting integer to complex number : (1+2j)
12. chr(number): This method converts an integer to its ASCII character equivalent.
e
x = chr(76)
y = chr(77)
in
print(x)
nl
print(y)
Output
O
L
ty
Adding New Function
We’ve only used the functions that come with Python so far, but other functions can
be added as well. The name of a new function and the sequence of statements that run
si
when the function is called are specified in a function definition. Once we’ve defined a
function, we can use it repeatedly throughout our programme.
Here is an example:
r
ve
def print_statement():
print(“Welcome to Python”)
print(‘Add a Function.’)
ni
This is a function definition, hence the term def is used. The function’s name is
print lyrics. Function names must follow the same restrictions as variable names:
letters, numbers, and various punctuation marks are acceptable, but the first character
U
must not be a number. A keyword cannot be used as a function name, and a variable
and a function with the same name should be avoided.
This function does not take any arguments, as indicated by the empty parentheses
ity
after its name. We’ll develop functions that take parameters as inputs later.
incorporate mathematical calculations into the project. Python has a math module that
can handle similar calculations. Basic operations such as addition(+), subtraction(-),
multiplication(*), and division(/) are covered by the Math module, as well as advanced
)A
In this post, we’ll go over the math module from beginning to end, with the help of a
large dataset comprising functions that are described with good examples.
The value of different constants such as pi and tau can be found in the Math
module. Having such constants allows us to save time by not having to write the value
of each constant every time we want to use it, and with excellent precision. The math
Notes
e
module provides the following constants:
●● Euler’s Number
in
●● Pi
●● Tau
●● Infinity
nl
●● Not a Number (NaN)
Constant Description
O
math.e Returns Euler’s number (2.7182...)
math.inf Returns a floating-point positive infinity
math.nan Returns a floating-point NaN (Not a Number) value
ty
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)
si
Math Methods
Method Description
mat.acos()
math.acosh()
r
Returns the arc cosine of a number
Returns the inverse hyperbolic cosine of a number
ve
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
ni
math.dist*() Returns the Euclidean distance between two points (p and q),
where p and q are the coordinates of that point
)A
e
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
in
math.fsum() Returns the sum of all items in any iterable (tuples, arrays,
lists, etc.)
math.gamma() Returns the gamma function at x
nl
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
O
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number if infinite or not
ty
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.Idexp() Returns the inverse of math.frexp() which is x*(2**i) of the given
si
numbers x and i
math.Igamaa() Returns the log gamma value of x
math.log() Returns the natural logarithm of number, or the logarithm of
number to base r
ve
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
ni
math.perm() Returns the number of ways to choose k items with order and
without repetition
math.pow() Returns the value of x to the power of y
U
Example:
Notes
e
# Python code to demonstrate the working of factorial()
in
# importing “math” for mathematical operations
import math
nl
x = 6
O
print(“The factorial of 6 is : “, end=””)
print(math.factorial(x))
ty
Output
The factorial of 6 is : 720
si
Power functions can be expressed as x^n where n is the power of x whereas
logarithmic functions are considered as the inverse of exponential functions.
Example:
import math
test_int = 4
test_neg_int = -3
ity
test_float = 0.00
print (math.exp(test_int))
print (math.exp(test_neg_int))
)A
print (math.exp(test_float))
Output
54.598150033144236
(c
0.049787068367863944
1.0
e
●● The log() method returns the base b logarithmic value of a. The computed
value is of the natural log if the basis is not specified.
in
●● The log2(a) function calculates the value of log an in base two. This value is
more accurate than the function’s value from earlier.
●● The log10(a) function returns the result of log an in base ten. This value is
nl
more accurate than the function’s value from earlier.
# Python code to demonstrate the working of logarithm
O
# importing “math” for mathematical operations
import math
ty
print (“The value of log 2 with base 3 is : “, end=””)
print (math.log(2,3))
si
# returning the log2 of 16
print (math.log2(16)) r
ve
# returning the log10 of 10000
print (math.log10(10000))
ni
Output
The value of log 2 with base 3 is : 0.6309297535714574
U
the argument and the output of the G(x) function becomes the input of the F() function.
def add(x):
return x + 2
def multiply(x):
return x * 2
Notes
e
# To add 2 to a number and then multiply by 2, print the
result of the add and multiply combination.
in
print(“Adding 2 to 5 and multiplying the result with 2: “,
multiply(add(5)))
nl
Output
Adding 2 to 5 and multiplying the result with 2: 14
O
Explanation
On input 5, the add() method is invoked first. The output of add() is 7, which is
supplied as the input to multiply(), which multiplies it by 2 and returns 14 as the result.
ty
A better method to put composition into practice
si
make a custom function that combines any two functions.
r
def composite_function(f, g):
return lambda x : f(g(x))
ve
# Function to add 2
def add(x):
return x + 2
ni
# Function to multiply 2
def multiply(x):
U
return x * 2
Output
Adding 2 to 5 and multiplying the result with 2: 14
)A
3.2 Recursion
When using recursion, the developer must exercise extreme caution because it is
all too easy to write a function that never terminates or consumes excessive quantities of
(c
memory or computing power. Recursion, on the other hand, can be a tremendously efficient
and mathematically elegant technique to programming when implemented correctly.
e
●● Recursion can be used to break down a complex function into smaller sub-problems.
●● Recursion is more efficient than nested iteration for creating sequences.
in
●● The use of recursive functions makes the code appear simple and efficient.
nl
●● Recursive calls consume a lot of memory and time, making it inefficient to use.
●● Debugging recursive functions is difficult.
●● The logic of recursion can be difficult to comprehend at times.
O
Syntax:
ty
|
| (recursive call)
si
func() ----
●● In-order Traversal
●● Pre-order Traversal
U
●● Post-order Traversal
In-order Traversal: The left subtree is visited first, followed by the root, and finally
the right subtree in this traversal strategy. Always keep in mind that any Demo could be
a subtree in and of itself.
ity
The Demo class is used in the following python programme to build place holders
for the root Demo, as well as the left and right Demos. Then, to add data to the tree, we
develop an insert function. Finally, the inorder traversal logic is achieved by constructing
an empty list and first adding the left Demo, then the root or parent Demo. To finish the
m
inorder traversal, the left Demo is added last. This procedure is repeated for each sub-
tree until all Demos have been explored.
)A
class Demo:
self.data = data
# Insert Demo
e
if self.data:
if data < self.data:
in
if self.left is None:
self.left = Demo(data)
else:
nl
self.left.insert(data)
elif data > self.data:
O
if self.right is None:
self.right = Demo(data)
else:
ty
self.right.insert(data)
else:
self.data = data
si
# Print the Tree
def PrintTree(self):
r
if self.left:
ve
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
ni
# Inorder traversal
# Left -> Root -> Right
U
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
m
root = Demo(27)
root.insert(14)
)A
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
(c
root.insert(42)
print(root.inorderTraversal(root))
Output
Notes
e
[10, 14, 19, 27, 31, 35, 42]
in
Pre-order Traversal
The root Demo is visited first, followed by the left subtree, and ultimately the right
subtree in this traversal strategy.
nl
The Demo class is used in the following python programme to build place holders
for the root Demo, as well as the left and right Demos. Then, to add data to the tree,
we develop an insert function. Finally, the Pre-order traversal logic is achieved by
O
constructing an empty list and first inserting the root Demo, then the left Demo. To finish
the Pre-order traversal, the correct Demo is added last. This procedure is repeated for
each sub-tree until all Demos have been explored.
ty
class Demo:
si
self.right = None
self.data = data
# Insert Demo r
ve
def insert(self, data):
if self.data:
if data < self.data:
ni
if self.left is None:
self.left = Demo(data)
else:
U
self.left.insert(data)
elif data > self.data:
if self.right is None:
ity
self.right = Demo(data)
else:
self.right.insert(data)
m
else:
self.data = data
)A
print( self.data),
if self.right:
self.right.PrintTree()
Notes
e
# Preorder traversal Root -> Left ->Right
def PreorderTraversal(self, root):
in
res = []
if root:
nl
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
O
return res
root = Demo(27)
root.insert(14)
ty
root.insert(35)
root.insert(10)
si
root.insert(19)
root.insert(31)
root.insert(42)
r
print(root.PreorderTraversal(root))
ve
Output
[27, 14, 10, 19, 35, 31, 42]
ni
Post-order Traversal
The root Demo is visited last in this traversal strategy, hence the name. The left
subtree is traversed first, followed by the right subtree, and ultimately the root Demo.
U
The Demo class is used in the following python programme to build place holders
for the root Demo, as well as the left and right Demos. Then, to add data to the tree,
we develop an insert function. Finally, the Post-order traversal logic is implemented
ity
by constructing an empty list and then adding the left Demo, then the right Demo.
To complete the Post-order traversal, the root or parent Demo is added last. This
procedure is repeated for each sub-tree until all Demos have been explored.
class Demo:
m
self.right = None
self.data = data
# Insert Demo
def insert(self, data):
(c
if self.data:
if data < self.data:
Amity Directorate of Distance & Online Education
Python Programming 125
if self.left is None:
Notes
e
self.left = Demo(data)
else:
in
self.left.insert(data)
elif data > self.data:
nl
if self.right is None:
self.right = Demo(data)
else:
O
self.right.insert(data)
else:
self.data = data
ty
# Print the Tree
def PrintTree(self):
si
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
r
ve
self.right.PrintTree()
# Postorder traversal
# Left ->Right -> Root
ni
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
ity
res.append(root.data)
return res
root = Demo(27)
root.insert(14)
m
root.insert(35)
root.insert(10)
)A
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PostorderTraversal(root))
(c
Output
Notes
e
[10, 19, 14, 31, 42, 35, 27]
in
3.2.2 Comparison with a Code Snippet
In Python, both “is” and “==” are used to compare objects. The operator “==”
compares two items’ values, whereas “is” determines whether two objects are identical
nl
(In other words two references to same object).
O
# “==”
ty
x2 = [10, 20, 30]
si
if x1 == x2:
print(“Yes”)
else: r
ve
print(“No”)
Output
ni
Yes
The “==” operator does not indicate if x1 and x2 are referring to the same object.
For this, we use the word “is.”
U
else:
print(“No”)
# It creates another reference x3 to same list.
)A
x3 = x1
# So we get “Yes” here
if x1 is x3:
(c
print(“Yes”)
else:
print(“No”)
Notes
e
# “==” would also produce yes anyway
if x1 == x3:
in
print(“Yes”)
else:
nl
print(“No”)
Output
O
No
Yes
Yes
ty
3.2.3 Searching with a Code Snippet
Using recursion, find the node with the highest value in a Binary Search Tree.
r si
ve
ni
Output: 22
U
class Node:
ity
self.data = data
self.left = None
m
self.right = None
# Helper function that allocates a new node with the given data and None left and
)A
right pointers.
def newNode(data):
node = Node(0)
(c
node.data = data
node.left = None
node.right = None
Notes
e
return (node)
# Give a binary search tree and a number, inserts a new node with the given
in
number in the correct place in the tree. Returns the new root pointer which the caller
should then use (the standard trick to avoid using reference parameters).
nl
def insert(node,data):
# 1. If the tree is empty,
# return a new, single node
O
if (node == None):
return (newNode(data))
else :
ty
# 2. Otherwise, recur down the tree
if (data <= node.data):
node.left = insert(node.left, data)
si
else:
node.right = insert(node.right, data)
r
# return the (unchanged) node pointer */
ve
return node
# Function to return the minimum node
# in the given binary search tree
ni
def maxValue(node):
if (node.right == None):
return node.data
U
return maxValue(node.right)
# Driver Code
if __name__==’__main__’:
ity
Output
62
e
A Python string is a collection of Unicode characters surrounded by quotation
marks. In this post, we’ll look at Python’s in-built functions, which are functions that
in
work on strings.
nl
The count() method in Python is an intrinsic function that returns the number of
occurrences of a substring in a supplied string.
O
Syntax:
Parameters:
ty
The count() function has one compulsory and two optional parameters.
Mandatory parameter:
si
substring-string whose count is to be found.
Optional Parameters:
r
start (Optional)-starting index within the string where the search starts.
ve
end (Optional)-ending index within the string where the search ends.
Return Value:
print(string.count(“python”))
Output
2
(c
e
# Python program to demonstrate the use of
in
# string in which occurrence will be checked
nl
# counts the number of times substring occurs in
O
# an integer
print(string.count(“Python”, 0, 5))
ty
print(string.count(“Python”, 0, 15))
Output
si
0
r
3.3.2 Stack Diagram for Recursive Functions
ve
Recursion is the process of a function calling itself directly or indirectly, and the
associated function is known as a recursive function. Certain problems can be solved
quickly using the recursive algorithm.
ni
A Mathematical Interpretation
Consider the difficulty of a programmer determining the sum of the first n natural
numbers. There are numerous approaches, but the simplest is to just add the integers
U
f(n) = 1 + 2 + 3 +……..+ n
ity
f(n) = 1 n=1
The difference between approaches (1) and (2) is that in approach (2), the function
)A
“ f() “ is called inside the function, which is known as recursion, and the function that
contains recursion is known as recursive function. In the end, this is a great tool in the
hands of programmers to code some problems in a much easier and efficient way.
When a function is called from main(), memory on the stack is allocated to it. When
(c
a recursive function calls itself, the memory for the called function is allocated on top of
the memory allocated to the calling function, and each function call creates a new copy
of the local variables. When the function reaches the base case, it returns its value to
Amity Directorate of Distance & Online Education
Python Programming 131
the function that called it, memory is released, and the process resumes.
Notes
e
# A Python 3 program to demonstrate working of recursion
def printFun(test):
in
if (test < 1):
nl
return
else:
print(test, end=” “)
O
printFun(test-1) # statement 2
print(test, end=” “)
return
ty
# Driver Code
test = 3
si
printFun(test)
Output
3 2 1 1 2 3 r
ve
When main() calls printFun(3), memory is allocated to printFun(3), a local variable
test is set to 3, and statements 1 through 4 are pushed onto the stack, as shown in
the picture below. It starts with the number ‘3’. In statement 2, memory is allocated to
printFun(2), a local variable test is set to 2, and statements 1 through 4 are pushed to
ni
the top of the stack. printFun(1) calls printFun(2), and printFun(1) calls printFun(2) (0).
printFun(0) jumps to the if statement and then back to printFun(0) (1). The
remaining printFun(1) statements are run before returning to printFun(2) and so forth.
U
Values from 3 to 1 are printed in the output, followed by 1 to 3. The memory stack is
depicted in the diagram below.
A stack diagram might be handy for keeping track of which variables can be used
ity
where. Stack diagrams, like state diagrams, indicate the value of each variable as well
as the function to which each variable belongs.
A frame is used to represent each function. A frame is a box that contains the
arguments and variables of a function as well as the name of the function.
m
When a function solves a problem, it can call a lot of other functions in the process.
When a function calls itself, this is an example of this. This is referred to as recursion.
(c
A stack diagram was used to describe the state of a programme during a function
call in stack diagrams. A recursive function can be deduced using the same diagram.
Python creates a new function frame each time a function is called, which holds the
Notes
e
function’s local variables and parameters. There could be multiple frames on the stack
at the same time for a recursive function.
in
We used a stack diagram to represent the state of a program during a function call.
The same kind of diagram can help interpret a recursive function.
Every time a function gets called, Python creates a new function frame, which
nl
contains the function’s local variables and parameters. For a recursive function, there
might be more than one frame on the stack at the same time.
O
ty
si
The frame for main is at the top of the stack, as is customary. We didn’t create any
r
variables in __main__ or pass any arguments to it, so it’s empty.
ve
The parameter n has different values in each of the four countdown frames. The
basic case is the bottom of the stack, with n=0. There are no additional frames because
it does not make a recursive call.
ni
to manage textual data. Python Strings are immutable Unicode point sequences. In
Python, the simplest and most straightforward method is to create strings. In Python,
we simply enclose a text in single and double quotations to make a string. Single and
double quotes statements are treated the same in Python.
ity
e
index() Returns the position of the first occurrence of a substring in a string
in
isalnum() Checks whether all the characters in a given string is alphanumeric or not
isalpha() Returns “True” if all characters in the string are alphabets
isdecimal() Returns true if all characters in a string are decimal
nl
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
O
islower() Checks if all characters in the string are lowercase
isnumeric() Returns “True” if all characters in the string are numeric characters
isprintable() Returns “True” if all characters in the string are printable or the string
ty
is empty
isspace() Returns “True” if all characters in the string are whitespace characters
istitle() Returns “True” if the string is a title cased string
si
isupper() Checks if all characters in the string are uppercase
join() Returns a concatenated String
Ijust() r
Left aligns the string according to the width specified
ve
lower() Converts all uppercase characters in a string into lowercase
Istrip() Returns the string with leading characters removed
maketrans() Returns a translation table
ni
rindex() Returns the highest index of the substring inside the string
rjust() Right aligns the string according to the width specified
rpartition() Split the given string into three parts
ity
rsplit() Split the string from the right by the specified separator
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
m
zfill() Returns a copy of the string with ‘0’ characters padded to the left
side of the string
e
The below functions are used to change the case of the strings.
in
●● upper(): All lowercase characters in a string are converted to uppercase.
●● title(): Change the case of a string to that of a title.
nl
Example: Changing the case of Python Strings.
O
text = ‘Welcome to Python’
ty
print(“\nConverted String:”)
print(text.upper())
si
# lower() function to convert
r
print(“\nConverted String:”)
ve
print(text.lower())
print(“\nConverted String:”)
print(text.title())
U
print(“\nOriginal String”)
print(text)
ity
Output:
Converted String:
WELOCME TO PYTHON
m
Converted String:
)A
welocme to python
Converted String:
(c
Welocme To Python
Original String
welocme To pytHON Notes
e
3.3.4 Use of IN Operator
in
Operators that validate a value’s membership are known as membership
operators. It checks for sequence membership, such as strings, lists, or tuples.
nl
in operator: The ‘in’ operator is used to determine whether a value is present in a
sequence. If a variable is found in the supplied sequence, evaluate to true; otherwise,
evaluate to false.
O
# Python program to illustrate Finding common member in list
ty
list1=[1,2,3,4,5]
list2=[6,7,8,9]
si
if item in list2:
print(“overlapping”)
else:
r
ve
print(“not overlapping”)
Output
ni
not overlapping
def overlapping(list1,list2):
m
c=0
d=0
)A
for i in list1:
c+=1
for i in list2:
(c
d+=1
for i in range(0,c):
for j in range(0,d):
Notes
e
if(list1[i]==list2[j]):
return 1
in
return 0
list1=[1,2,3,4,5]
nl
list2=[6,7,8,9]
if(overlapping(list1,list2)):
O
print(“overlapping”)
else:
ty
print(“not overlapping”)
Output
si
not overlapping
y = 20
if ( x not in list ):
else:
if ( y in list ):
else:
m
Output
)A
Summary
(c
●● The count() method in Python is an intrinsic function that returns the number of
occurrences of a substring in a supplied string.
●● Recursion is the process of a function calling itself directly or indirectly, and the
Notes
e
associated function is known as a recursive function. Certain problems can be
solved quickly using the recursive algorithm.
in
●● When a function is called from main(), memory on the stack is allocated to it.
When a recursive function calls itself, the memory for the called function is
allocated on top of the memory allocated to the calling function, and each function
call creates a new copy of the local variables. When the function reaches the base
nl
case, it returns its value to the function that called it, memory is released, and the
process resumes.
O
●● Recursion is a programming paradigm that comes in handy when a work may be
organically divided into numerous smaller tasks of the same type. Alternatively,
when a task can be broken down into a basic action and a simpler form of the
same task. Alternatively, as we’ll see shortly, to deal with certain data structures.
ty
●● in operator: The ‘in’ operator is used to determine whether a value is present in
a sequence. If a variable is found in the supplied sequence, evaluate to true;
otherwise, evaluate to false.
si
●● A special sort of recursion in which a function’s last procedure is a recursive call.
Instead of establishing a new stack frame, the loop can be avoided by processing
the request in the current stack frame and returning the output. The compiler may
r
optimise tail-recursion, making it better than non-tail recursive functions.
ve
●● When working on financial or scientific projects, it is sometimes necessary to
incorporate mathematical calculations into the project. Python has a math module that
can handle similar calculations. Basic operations such as addition(+), subtraction(-),
multiplication(*), and division(/) are covered by the Math module, as well as advanced
ni
●● Python has a built-in type sequence called string. In Python, strings can be used to
manage textual data. Python Strings are immutable Unicode point sequences. In
Python, the simplest and most straightforward method is to create strings.
●● To define a function in Python, follow these simple guidelines.
m
●● The term def is followed by the function name and parentheses (()) in a
function block.
●● These parentheses should include any input parameters or arguments. Within
)A
Glossary
Notes
e
Parameters:
in
The count() function has one compulsory and two optional parameters.
Mandatory parameter:
nl
Optional Parameters:
start (Optional)-starting index within the string where the search starts.
O
end (Optional)-ending index within the string where the search ends.
Return Value:
ty
count() method returns an integer that denotes number of times a substring
occurs in a given string.
●● capitalize(): Converts the first character of the string to a capital (uppercase) letter
si
●● casefold(): Implements caseless string matching
●● center(): Pad the string with the specified character.
●● r
count(): Returns the number of occurrences of a substring in the string.
ve
●● encode(): Encodes strings with the specified encoded scheme
●● endswith(): Returns “True” if a string ends with the given suffix
●● expandtabs(): Specifies the amount of space to be substituted with the “\t” symbol
ni
in the string
●● find(): Returns the lowest index of the substring if it is found
●● format(): Formats the string for printing it to console
U
●● isalnum(): Checks whether all the characters in a given string is alphanumeric or not
●● isalpha(): Returns “True” if all characters in the string are alphabets
●● isdecimal(): Returns true if all characters in a string are decimal
●● def Executes at Runtime: The Python def statement is a genuine executable
m
c. Modulo
d. None of the above.
Amity Directorate of Distance & Online Education
Python Programming 139
2. The _ _ _ _ _ _ _ _ _, short for documentation string, is the first string after the
Notes
e
function header. It’s a short explanation of what a function does.
a. docstring
in
b. mocstring
c. datastring
nl
d. dostring
3. What does it mean when there are empty parentheses after a function name?
a. It lets you know whether a function is self-defined or included in a Python module.
O
b. It means that the function does not return anything.
c. It lets you know that nothing will print.
ty
d. It indicates that a function doesn’t take any arguments.
4. What is the first line of a function definition called? What is every line after the first
line called?
si
a. body; header
b. title; body
c. header; body r
ve
d. initialization; body
5. Consider the code below. Which statement is true?
def printWeather():
ni
print(“It is sunny!”)
c. merge
d. none of the above
7. The _ _ _ _ _ _ _ _ _ method in Python is an intrinsic function that returns the number
)A
c. stringcount()
d. all of the above
e
a. lower()
b. upper()
in
c. title()
d. None of the above
nl
9. The process of combining two or more functions in such a way that the output of one
becomes the input of the next, and so on, is known as function_ _ _ _ _ _ _ _.
a. Complex
O
b. Composition
c. Concatenate
ty
d. Cubic
10. math.e returns:
a. Floating point
si
b. Returns Pi
c. Returns Tau
d. Returns Euler Numberr
ve
Exercise
1. Define the concept of functions.
2. Define the flow of execution.
ni
Learning Activities
m
1. Draw a stack diagram for print n with s = ‘Hello’ and n=2 as an exercise. Then create
a do n function that accepts a function object and a number, n, as parameters and
)A
e
1. b
2. a
in
3. d
4. c
nl
5. a
6. a
O
7. a
8. a
9. b
ty
10. d
si
1. The Ultimate Python Programming Guide from Beginner To Intermediate,
William Alvin Newton
2. Python Programming: A Practical Approach, Vijay Kumar Sharma, Vimal Kumar
3. Learn Python the Hard Way, Zed Shaw
r
ve
4. Python Cookbook: Recipes for Mastering Python 3, Brian K. Jones and David
M. Beazley
5. Python for Everybody: Exploring Data Using Python 3, Charles Severance
ni
e
Learning Objectives:
in
At the end of this module, you will be able to understand:
nl
●● List Operation: Traversing a List, List Slicing
●● List Methods, Deleting elements from list
O
●● Map, Filter and Reduce
●● List and String
●● Objects and Values
ty
●● List Arguments
●● Dictionary: Introduction
si
●● Dictionary as a Set of Counters
●● Dictionary Operations and Methods
●● Memos, Global Variable
●● Long Integers
r
ve
●● Tuples: Tuple Assignment, Tuples as Return Values
●● Variable Length Argument Tuples
●● Lists and Tuples
ni
●● Comparing Tuples
●● Sequences of Sequences
U
Introduction
In Python, lists are ordered and have a count. A list’s elements are indexed in a
ity
specific order, with 0 serving as the first index. Each element in the list has its own
separate spot in the list, allowing duplication of elements in the list while maintaining the
credibility of each member.
Creating a list
m
In Python, you may make a list by simply putting the sequence inside square
brackets[]. A list, unlike Sets, does not require a built-in function to be created.
)A
print(List)
# Creating a List of numbers
e
print(“\nList of numbers: “)
print(List)
in
# Creating a List of strings and accessing using index
nl
List = [“Welcome”, “To”, “Python”]
print(“\nList Items: “)
print(List[0])
O
print(List[2])
# Creating a Multi-Dimensional List (By Nesting a list inside a List)
List = [[‘Welcome’, ‘To’], [‘Python’]]
ty
print(“\nMulti-Dimensional List: “)
print(List)
si
Output
Blank List:
[] r
ve
List of numbers:
[20, 21, 22]
ni
List Items:
Welcome
U
Python
Multi-Dimensional List:
[[‘Welcome’, ‘To’], [‘Python’]]
ity
Creating a Dictionary
A Dictionary is built in Python by enclosing a succession of entries in curly braces
and separating them with a comma. The Dictionary stores pairs of values, one of which is
m
the Key and the other is the Key:value pair element. In a dictionary, values can be of any
data type and can be replicated, but keys cannot be copied and must be immutable.
print(Dict)
(c
e
print(“\nDictionary with the use of Mixed Keys: “)
print(Dict)
in
Output
Dictionary with the use of Integer Keys:
nl
{1: ‘Welcome’, 2: ‘To’, 3: ‘Python’}
Dictionary with the use of Mixed Keys:
O
{1: [1, 2, 3, 4], ‘Name’: ‘Python’}
The tuple object (pronounced “toople” or “tuhple,” depending on who you ask) is
roughly like a list that cannot be changed—tuples are sequences, like lists, but they are
ty
immutable, like strings. Syntactically, they are coded in parentheses instead of square
brackets, and they support arbitrary types, arbitrary nesting, and the usual sequence
operations:
si
>>> T = (1, 2, 3, 4) # A 4-item tuple
>>> len(T) # Length
4
>> T + (5, 6)
r # Concatenation
ve
(1, 2, 3, 4, 5, 6)
>>> T[0] # Indexing, slicing, and more
1
ni
4.1 List
U
Lists are similar to dynamically scaled arrays (vector in C++ and Array List in Java)
that are declared in other languages. Lists don’t have to be homogeneous all the time,
which makes it Python’s most powerful tool. Data types such as Integers, Strings, and
Objects can all be found in a single list. Lists are changeable, which means they can be
ity
operator meaning
m
+ concatenation
* repetition
<string>[] indexing
)A
<string>[:] slicing
len(<string>) length
for <var> in <string> iteration through characters
(c
The operations in the table above aren’t strictly speaking string operations. It’s a
set of operations that can be applied on sequences. Python lists are a type of sequence
as well. As shown in the following session, we can additionally index, slice, and
Notes
e
concatenate lists.
in
nl
O
Lists are more general than strings, which is one of their advantages. Lists can be
ty
sequences of arbitrary things, but strings are always sequences of characters. A list of
numbers or a list of strings can be created. You can even combine the two and make a
list that includes both numbers and strings:
si
We can redo our month abbreviation programme from the previous part using a list
of strings to make it even simpler:
r
ve
ni
U
ity
There are a few things to keep in mind concerning this programme. We’ve made
a lookup table out of a collection of strings called months. The list-creation code
is separated into two lines. In most cases, a Python statement is written on a single
m
line, however Python recognises that the list isn’t complete until the closing bracket “] “
appears. The code is better readable when the statement is split across two lines.
Lists, like strings, are indexed from 0 to 1, therefore the value months [OJ is the
)A
string “Jan” in this list. The nth month is usually positioned at n-1. I didn’t bother putting
this computation in a separate step because it’s so simple; the term months [n-1] is
used directly in the print statement.
This solution to the abbreviation problem is not only easier to implement, but
(c
it is also more adaptable. It would be simple to alter the programme to print out the
complete month’s name for example. All we need is a fresh lookup list definition.
Notes
e
in
While both strings and lists are sequences, there is a significant distinction
between them. Lists can be changed. This means that an assignment statement can
change the value of an item in a list. Strings, on the other hand, are not changeable “in
place.” Here’s an example encounter that exemplifies the distinction:
nl
O
ty
r si
The first line generates a four-number list. The value 15 is returned by indexing
position 2. (as usual, indexes start at 0). The item at position 2 is given the value 0 in
ve
the next command. When you evaluate the list after the assignment, you’ll notice that
the new value has taken the place of the old. A comparable operation on a string results
in an error. Lists are mutable, but not strings.
ni
The + operator can be used to concatenate lists in Python, and the * operator can
be used to construct a repeated series of list items. As an example,
ity
m
)A
There are two lists built with numbers as items (1-2). To make a new list, the list 1
and list 2 lists are combined. The new list contains all of the items from both lists (3).
On the list, you can use the multiplication operator. The items are repeated the number
of times you request, and the contents of list 1 are repeated three times in (4). The
(c
== operator (5) is used to compare the contents of the lists list 1 and list 2, and the
result is Boolean False because the entries in both lists are different. The in and not in
membership operators can be used to check for the presence of an item in the list. It
Notes
e
returns a True or False Boolean value. As an example,
in
nl
If an item is present in the list, the in operator returns True (1); otherwise, it returns
False (2).
O
The list() Function
To make a list, use the built-in list() method. The list() method has the following syntax:
ty
List([sequence])
The sequence can be a string, a tuple, or a list. An empty list is constructed if the
optional sequence is not given. As an example,
si
1. >>> quote = “How you doing?”
2. >>> string_to_list = list(quote)
3. >>> string_to_list
r
ve
[‘H’, ‘o’, ‘w’, ‘’, ‘y’, ‘o’, ‘u’, ‘’, ‘d’, ‘o’, ‘i’, ‘n’, ‘g’, ‘?’]
4. >>>friends = [“j”, “o”, “e”, “y”]
5. >>>friends + quote
ni
●● The list() function is used to transform the string variable quote into a list.
●● Let’s check whether we can concatenate a string with a list now.
●● The outcome is a TypeError: can only concatenate list (not “str”) to list
m
Traversing a List
You can go through each item in a list using a for loop. Program to Demonstrate
List Traversal The for loop is used in the following way:
e
4. for each_food_item in [“waffles”, “sandwich”, “burger”, “fries”]:
5. print(f”I like to eat {each_food_item}”)
in
Output
I like to eat waffles
nl
I like to eat sandwich
O
I like to eat fries
ty
I like to eat sandwich
si
The for statement makes it simple to loop through a list of things.
(1) A list variable is created, and the for loop specifies the list variable
r
(2). You can define a list directly in the for loop instead of using a list variable
ve
(3). Using range() and the len() method, you may get the index value of each item
in the list.
Program to Display the Index Values of Items in List:
ni
Output
The index value of ‘google’ is 0
ity
To get the index value of each item in the list, provide the list name as an argument
to the len() function, and the resulting value as an argument to the range() function.
)A
List Comprehensions
List literals are commonly used to build small lists, although longer lists are
normally created programmatically. We can use list(range(n)) for a list of integers, or
(c
range() if we just require an integer iterator, but for other lists, a for...in loop is quite
frequent. Let’s say we wanted to make a list of all the leap years in a specific range. We
could start with something like this:
Amity Directorate of Distance & Online Education
Python Programming 149
Notes
e
in
The iterator returned by the built-in range() function produces the integers n, n +
1,..., m - 1 when given two integer arguments, range() 141 n and m.
nl
Of course, we could use a list literal if we knew the exact range ahead of time, such
as jumps = [1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936].
O
A list comprehension is an expression and a loop with an optional condition
included in brackets, where the loop generates list items and the condition filters out
unwanted things. The most basic type of list comprehension is as follows:
ty
[item for item in iterable]
This will return a list of all the items in the iterable and is similar to list in terms
of semantics (iterable). We may utilise expressions and attach a condition to list
si
comprehensions, which makes them more interesting and powerful. This leads us to the
two general syntaxes for list comprehensions:
The thing will usually be or be involved in the expression. Naturally, the list
comprehension does not require the temp variable that the for... in loop version does.
U
We can now use a list comprehension to alter the function to generate the jumps
list. The code will be developed in three stages. We’ll start by making a list of all the
years in the given range:
ity
In this case, using a list comprehension reduced the code from four to two lines—a
minor save, but one that may build up quickly in large projects.
or iterables, and the syntax for list comprehensions requires an iterable. It’s the same
as having nested for...in loops. For example, we could use nested for... in loops to
produce all conceivable clothing label codes for given sets of sexes, sizes, and colours,
Notes
e
but avoiding labels for full-figured females who the fashion industry usually ignores:
in
nl
O
The equation s+z+c is used to create each item in the list. Also for list
ty
comprehension, we utilised somewhat different reasoning, skipping invalid sex/size
combinations in the innermost loop, whereas the nested for...in loops version skips
invalid combinations in the intermediate loop. Using one or more for... in loops, any list
si
comprehension can be rebuilt.
List Slicing
r
Python supports list slicing, which allows you to extract a portion of a list by
ve
specifying an index range and the colon (:) operator, which is also a list. The list slicing
syntax is as follows:
ni
where start and stop are both integers (positive or negative values). List slicing
U
extracts a section of the list from the start index value to the stop index value,
including the start index value but excluding the stop index value. Step is an optional
parameter that provides the increment value to slice by. The positive and negative index
breakdown for the list fruits is provided below.
ity
m
3. >>> fruits[:3]
[‘grapefruit’, ‘pineapple’, ‘blueberries’]
4. >>> fruits[2:]
[‘blueberries’, ‘mango’, ‘banana’]
(c
5. >>> fruits[1:4:2]
[‘pineapple’, ‘mango’]
6. >>> fruits[:]
Notes
e
[‘grapefruit’, ‘pineapple’, ‘blueberries’, ‘mango’, ‘banana’]
7. >>> fruits[::2]
in
[‘grapefruit’, ‘blueberries’, ‘banana’]
8. >>> fruits[::-1]
[‘banana’, ‘mango’, ‘blueberries’, ‘pineapple’, ‘grapefruit’]
nl
9. >>> fruits[-3:-1]
[‘blueberries’, ‘mango’]
Slicing is applied to all items in the fruits list with an index value of 1 to 3but
O
excluding the index value of 3. There is no need to supply the index value of zero if you
only wish to access the first items. You can specify only the stop index value instead of
the start index value. Similarly, if you wish to retrieve the most recent stop items, you
simply need to give the start index value and not the stop value. When the stop index
ty
value is skipped, the number of things accessed increases until the last item is reached.
When both the start and stop index values are omitted and only the colon operator is
specified within the brackets, the whole list is displayed. Python understands that the number
si
after the second colon indicates that you want to specify your slicing increment. Python sets
this increment to 1 by default, but the number after the second colon allows you to specify a
different value. The use of a double colon, as seen in, signifies that there is no value for the
r
start index and no value for the stop index, and the items are jumped two steps.
ve
Starting with an index value of zero, every second item in the list is extracted. A
double colon followed by an index value of 1 can be used to display all items in a list in
reverse order. For start and stop index values, negative index values can also be utilised.
When you add or remove things, the list size changes dynamically, so there’s no
need for you to keep track of it. By supplying the list function to dir, you may retrieve a
U
list of all the methods in the table below that are related with the list ().
ity
m
)A
(c
Notes
e
in
nl
Various methods associated with list is displayed in above snip.
O
append(): This method is used to append and add elements to a List. It’s used to
add elements to the List’s last place.
Syntax:
ty
list.append (element)
# Adds List Element as value of List.
List = [‘Mathematics’, ‘chemistry’, 1997, 2000]
si
List.append(20544)
print(List)
Output:
r
ve
[‘Mathematics’, ‘chemistry’, 1997, 2000, 20544]
Syntax:
ni
list.insert(<position, element)
Example
U
List.insert(2,10087)
print(List)
Output:
m
extend(): List1 is extended by adding the contents of List2 to the end of List1.
)A
Syntax:
List1.extend(List2)
Example
List1 = [1, 2, 3]
(c
List2 = [2, 3, 4, 5]
# Add List2 to List1
Amity Directorate of Distance & Online Education
Python Programming 153
List1.extend(List2)
Notes
e
print(List1)
# Add List1 to List2 now
in
List2.extend(List1)
print(List2)
nl
Output:
O
sum() : Calculates sum of all the elements of List.
Syntax:
ty
sum(List)
Example
si
List = [1, 2, 3, 4, 5]
print(sum(List))
Output: r
ve
15
Syntax:
ni
List.count(element)
Example
U
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
ity
Output:
4
Syntax:
len(list_name)
Example
)A
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output:
(c
10
index(): The index of the first occurrence is returned. The Start and End indexes
Notes
e
aren’t required.
Syntax:
in
List.index(element[,start[,end]])
Example:
nl
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
O
Output:
1
reverse(): Ascending order should be used to sort the given data structure (both
ty
tuple and list). If nothing is supplied through sorted, key and reverse flag are not
required parameters, and reverse flag is set to False ().
si
Syntax:
sorted([list[,key[,Reverse_Flag]]])
r
list.sort([key,[Reverse_flag]])
ve
Example:
List.sort(reverse=True)
print(List)
Output:
ity
are extensively used to construct functional programming style solutions. These are
what are known as higher-order functions, which take a collection and a function that
will be applied to that collection in multiple ways. Filter(), map(), and reduce() are three
)A
Map
Python also has a higher-order function called map. The specified function
is applied to all items in the iterable(s) passed to Map. It returns a new iterable that
(c
contains the results of the applied function. It’s the functional counterpart of a for loop
applied to an iterable that collects the results of each iteration around the for loop.
The map function is extremely common in functional programming, and it is well worth
Notes
e
learning. map’s function signature is map (function, iterable, ...)
Anything that implements the iterable protocol is the second input to the map function.
in
The function given as the second argument to the map function is applied to
each item in the iterable. The function’s return value is subsequently gathered into the
iterable object returned by map.
nl
A function that adds one to a number is applied to a list of integers in the following example:
O
print(‘data:’, data)
ty
# using the map function
d1 = list(map(lambda i: i + 1, data))
si
print(‘d1’, d1)
def add_one(i):
return i + 1
r
# Apply the add_one function to each element in the
ve
# list using the map function
d2 = list(map(add_one, data))
print(‘d2:’, d2)
ni
Output
data: [1, 3, 5, 2, 7, 4, 10]
U
d1 [2, 4, 6, 3, 8, 5, 11]
d2: [2, 4, 6, 3, 8, 5, 11]
The function to be applied, like the filter() function, can be defined in line as a
ity
lambda or named function, as in add one (). Both can be used; the advantage of the
named add one() function is that it makes the function’s intent plain; nevertheless, it
pollutes the namespace of defined functions.
It’s worth noting that the map function can take multiple iterables. If more than one
m
iterable is supplied to map, the function must have the same number of parameters
as the iterables. If you wish to combine data from two or more collections into a single
collection, this capability comes in handy.
)A
Let’s say we want to add numbers from one list to numbers from another list. We
can build a function that takes two parameters and returns the result of adding the two
numbers together:
data1 = [1, 3, 5, 7]
(c
data2 = [2, 4, 6, 8]
result = list(map(lambda x, y: x + y, data1, data2)) print(result)
Output
Notes
e
[3, 7, 11, 15]
In the same way that the filter function can process built-in types like numbers, the
in
function passed to map can also process user-defined types like the class Person. For
instance, if we wanted to collect all of the ages for a Person list, we could write:
nl
data = [Person(‘John’, 54), Person(‘Phoebe’, 21),
Person(‘Adam’, 19)]
ages = list(map(lambda p: p.age, data))
O
print(ages)
Output:
ty
[54, 21, 19]
Filter
si
The filter() function is a higher-order function that takes in a function to filter
elements from a collection. The filter() function creates a new iterable with only the
elements selected by the test function.
r
To put it another way, the function sent to filter() is used to test all of the items in
the collection passed to it. Those for which the test filter returns True are included in
ve
the list of values returned. The result is a new iterable with all of the list’s members that
pass the test method. It’s worth noting that the order of the elements is preserved.
filter(function, iterable)
The second argument to the filter function is anything that implements the iterable
U
protocol, which includes all Lists, Tuples, Sets, and dictionaries, as well as a variety of
additional kinds.
The test function is a lambda (a function created in line) or the name of an existing
function that is provided in as the first argument. An iterable will be returned as a result,
ity
Here are some examples of how to use filter with a simple integer list:
print(‘data:’, data)
# Filter for even numbers using a lambda function
d1 = list(filter(lambda i: i % 2 == 0, data))
)A
print(‘d1:’, d1)
def is_even(i):
return i % 2 == 0
# Filter for even numbers using a named function
(c
d2 = list(filter(is_even, data))
print(‘d2:’, d2)
Amity Directorate of Distance & Online Education
Python Programming 157
Output
Notes
e
Data: [1, 3, 5, 2, 7, 4, 10]
d1: [2, 4, 10]
in
d2: [2, 4, 10]
One distinction between the two instances is that the second example’s test function
nl
is explicitly labelled (i.e. is even()), indicating that the function is testing the integer to see
if it is even or not. The in-line lambda function accomplishes the same thing, but to figure
out what it’s doing, you’ll need to know what the test function is doing.
O
It’s also worth noting that introducing a named function like is even() can pollute
the module’s namespace because there’s now a function that others could use, even
though the code’s original author never expected anyone else to use the is even()
method. This is why lambda functions (as well as map() and reduce()) are frequently
ty
used with filter().
Of course, you are not confined to using the built-in kinds like as integers,
real numbers, or strings; you can use any type. If we have a class called Person for
si
example:
class Person:
def __init__(self, name, age): r
ve
self.name = name
self.age = age
def __str__(self):
ni
Then we can create a list of instances of the class Person and then filter out all
U
for p in data:
print(p, end=’, ‘)
print(‘\n-----’)
m
for p in d3:
print(p, end=’, ‘)
Output
Person(Amit, 54), Person(Rituj, 21), Person(Sid, 19),
(c
-----
Person(Niki, 21), Person(Megan, 19),
Reduce
Notes
e
The reduce() method is the last higher-order function we’ll look at that may be used
with data collections.
in
The reduce() function takes an iterable and applies a function on each element,
combining the results into a single result.
nl
This function was part of the Python 2 language’s core, however it was not included
in Python 3. This is due in part to Guido van Rossum’s belief (probably true) that
reduce’s applicability is limited, but where it is beneficial, it is extremely useful. Although
it must be stated that some developers try to cram reduce() into situations that make the
O
implementation extremely difficult to comprehend—remember to keep things simple.
ty
sequence, and returns the result of applying some operation to these parameters. This
is something that is sometimes misinterpreted with reduce(). The functools.reduce
function has the following signature: functools.reduce (function, iterable[, initializer])
si
It’s worth noting that an initialiser can be provided as an option to provide an initial
value for the outcome. Reduce() can be used to sum all the values in a list for example:
from func tools import reduce
r
data = [1, 3, 5, 2, 7, 4, 10]
ve
result = reduce(lambda total, value: total + value, data)
print(result)
ni
Reduce() can be used with other kinds as well, despite the fact that it appears to be
only helpful for numbers like integers. Let’s say we want to compute the average age of
U
a group of people. We might use reduce to add all of the ages together and then divide
by the length of the data set we’re working with:
Person(‘Adam’, 19)]
total_age = reduce(lambda running_total, person: running_total
+ person.age, data, 0)
m
We have a data list of three people in this code sample. The reduction function
)A
is then used to apply a lambda to the data list. The lambda takes a running total and
adds the age of a person to it. This running total is started with the value zero. When
we apply the lambda to the data list, we get 54, 21 and 19 as a result. The final value
is then divided by the length of the data list (3) using the / operator, which returns a
whole integer using floor() division (rather than a real number such as 3.11). Finally, the
(c
Average age: 31
Amity Directorate of Distance & Online Education
Python Programming 159
e
Using pop()
in
The pop method is used to remove an element from a list at a specific index. As
an optional input to pop, the index of the element to remove is provided. Pop removes
the last element from the list if the argument is missing. The only outcome of the pop
method is the value that was removed from the list. When this value is needed for a
nl
later calculation, call pop on the right side of an assignment statement to save it into a
variable. Attempting to delete an element from an index that is beyond the end of the
list, as well as applying pop to an empty list, is an error.
O
The remove method can also be used to delete a value from a list. The value to
remove is the only parameter it has (rather than the index of the value to remove).
When the delete method is used, the first occurrence of the argument is removed from
ty
the list. If the value supplied to delete does not exist in the list, an error will be reported.
Consider the following illustration. It makes a list, then removes two of its entries.
Because 1.62 and 1.41 were removed from the list, the first print statement displays
si
[2.71, 3.14]. Because 1.41 was the final member in the list when the pop technique was
applied to it, the second print statement displays it.
r
ve
ni
Example:
‘Rituj’, ‘Moni’]
print(“Original List is :”, lst)
ity
Output:
)A
refers to a data item that isn’t a collection, it unbinds the object reference from the data
Notes
e
item and deletes it. Consider the following scenario:
>>> X = 8143 # object ref. ‘X’ created; int of value 8143 created
in
>>> X
8143
nl
>>> del X # object ref. ‘X’ deleted; int ready for garbage collection
>>> X
Traceback (most recent call last):
O
...
NameError: name ‘X’ is not defined
If no other object references refer to the data item to which an object reference
ty
refers, Python schedules the data item to be garbage-collected. Garbage collection
can be unpredictable (depending on the Python implementation), so we’ll have to take
care of it ourselves if any cleanup is required. Python has two options for dealing with
si
nondeterminism. To ensure that cleanup is completed, one option is to use a try...
finally block, while another is to use a with statement. Only the object reference to the
collection is removed when del is used on a collection data type like a tuple or a list.
r
If no other object references relate to the collection, the collection and its items (and
those items that are themselves collections for their items, recursively) are scheduled
ve
for garbage collection.
Del can be applied to individual items or slices in changeable collections like lists,
using the slice operator [ in both cases. They are scheduled for garbage collection if the
ni
item or items referred to are removed from the collection and there are no further object
references referring to them.
Example:
U
# using del statement to delete item (Orchids at index 1) from the list
m
del lst[1]
print(“After deleting the item :”, lst)
)A
Output:
Original List is: [Amit’, ‘Sid’, ‘Alok’, ‘Tanvi’, ‘Rituj’, ‘Moni’]
After deleting the item [Amit’, ‘Sid’, ‘Alok’, ‘Tanvi’, ‘Rituj’]
Using remove()
(c
In a list, remove() deletes the first instance of a value. This method should be used
when the value to be deleted is known in advance, independent of the index. This is
e
Example:
# Python 3 code to
in
# remove an item from list
# using function remove()
nl
lst = [Amit’, ‘Sid’, ‘Alok’, ‘Tanvi’,
‘Rituj’, ‘Moni’]
O
print(“Original List is :”, lst)
ty
lst.remove(‘Orchids’)
print(“After deleting the item :”, lst)
si
Output:
Original List is: [Amit’, ‘Sid’, ‘Alok’, ‘Tanvi’, ‘Rituj’, ‘Moni’]
List
A list is a collection of elements separated by commas and enclosed in square
ni
lists are ordered and have a definite sequence, and lists are indexed using 0 as the
first index. Each element in the list has a distinct spot in the list, allowing duplication of
elements in the list while maintaining each piece’s creditability. The list class is used to
represent it.
ity
food = []
To add something to the end of a list, we can use the append function:
food.append(“ham”)
print(food)
The outcome of these two lines is as follows:
(c
[‘ham’]
Now, let’s add a couple more items:
food.append(“cheese”)
Notes
e
food.append(“ice cream”)
print(food)
in
Which results in the following list being printed:
[‘ham’, ‘cheese’, ‘ice cream’]
nl
Removing an Item from a List
To remove an item from a list, use the remove method:
food.remove(“ham”)
O
print(food)
Specifically, this removes the FIRST instance of the item listed in the parentheses,
resulting in the following output:
ty
[‘cheese’, ‘ice cream’]
To more specifically illustrate this issue, consider adding the following segment of code:
si
food.append(“ice cream”)
food.append(“cheese”)
r
food.append(“ice cream”)
ve
food.append(“cheese”)
food.remove(“ice cream”)
print(food)
ni
Output
[‘cheese’, ‘ice cream’, ‘cheese’, ‘ice cream’, ‘cheese’]
U
Note that it’s now clear that the first occurrence of “ice cream” was removed.
Just like strings, we can index into a list in the exact same manner:
print(food[0])
ity
print(food[1])
print(food[-1])
Output
m
cheese
ice cream
cheese
)A
Non-negative indexes start counting from the beginning of the string, thus the first
two items in the list were printed first, and negative indexes start counting from the end
of the string, so the last line printed the list’s last member.
String
(c
Single quote marks (e.g., “hello”) or double quotation marks (e.g., “python course”) are
Notes
e
used to contain string values. The quotations are not part of the string; they are utilised
by the interpreter to indicate the start and end of the string. There is no character data
type in Python; instead, a character is a one-length string. The str class is used to
in
represent it. Strings have a number of features, including:
●● Even if the string has a numeric value, no numerical operations can be done on it.
nl
●● A string has a specified length. The built-in function len() can be used to
determine the length.
●● A string can be indexed. With the square bracket operator, you can get a
O
single character at a specific location in a string.
●● A slice operation can be used to get a sub-string (slice) of a string.
●● Strings are immutable, which means you can’t change them once they’ve
ty
been created.
The most natural way to initialize a string variable is through the input statement:
si
In this case, whatever the user types will be saved in the name field.
There are several ways to access parts of a string, check the string for letters, and
r
change the string once it has been saved in a variable.
ve
Checking for the presence of a letter in a string
Using the in operator, Python provides a very simple approach to verify if a letter, or
any other character for that matter, is in the string:
ni
This is a Boolean expression that returns True if the supplied character appears
in the string and False if it does not appear. This will look for a character as well as a
substring, or a group of characters within a larger string. The phrase ‘put’ in ‘computer’
evaluates to true since the fourth, fifth, and sixth letters of the word are all ‘put.’
m
for i in range(len(name)):
if name[i] == ‘t’:
Amity Directorate of Distance & Online Education
164 Python Programming
flag = True
Notes
e
if flag:
print(“You have an t in your name.”)
in
We can easily count the number of times a specific character appears in a string
using indexing. The previous section of code has been changed to output the number of
times the letter ‘t’ appears in the string entered by the user:
nl
name = input(“Please enter your name.\n”)
count = 0
O
for i in range(len(name)):
if name[i] == ‘t’:
count = count + 1
ty
print(“You have an t in your name”, count, “times.”)
Indexing into a String – Negative Indexes
si
Negative indexes into a string are also supported in Python, which is a feature that
many other languages lack. Python will start counting from the end of a string if you
give it a negative integer as an index. Here are the appropriate indexes for the string
hello for example:
r
ve
index -5 -4 -3 -2 -1
string ‘h’ ‘e’ ‘l’ ‘l’ ‘o’
Negative indexes aren’t essential; however, they can be useful when you need to
ni
find a character a certain number of positions from the end of a string. You’d have to
do the math yourself if you didn’t have negative indexing, using the len function and
subtracting. Here’s a simple illustration of how negative indexing makes a programme
easier to understand. In the next application, we’ll ask the user to enter a string made
U
Maintaining two indexes will be the essential method here: one from the front,
ity
counting from 0, and one from the back, counting backwards from -1. We want to see
if the characters on the front and back of the card match. If we find a mismatch, we
know our string isn’t a palindrome right away. We can break the string halfway through.
Because the range function only accepts numbers, we must determine the location
m
def main():
word = input(“Please enter a string, uppercase letters only.\n”)
)A
back = -1
isPal = True
for i in range(len(word)//2):
(c
if word[i] != word[back]:
isPal = False
break
Notes
e
back = back - 1
if isPal:
in
print(word,”is a palindrome.”)
else:
nl
print(word,”is not a palindrome.”)
main()
O
Slicing a String
Slicing is the process of extracting a substring from a given string. Giving both the
starting and ending indexes of a substring is an explicit way to denote it. The ending
value is not included in the set of values represented in a slice in Python, just as it is not
ty
included in the set of values described in the range function. As a result, the beginning
index is inclusive and the ending index is exclusive. The slice word[2:4] would be “ll”
and the slice word[1:2] would simply be “e” if the string word was “hello.”
si
Strings with negative indices can also be sliced. The requirements for slicing
when both indexes are supplied should be clarified by this IDLE transcript:>>> word =
“PYTHONISCOOL”
>>> print(word[2:7])
r
ve
THONI
>>> print(word[6:6])
>>> print(word[4:2])
ni
>>> print(word[5:11])
NISCOO
U
>>> print(word[8:12])
COOL
>>>
ity
>>> print(word[-7:-2])
NISCO
>>> print(word[-9:8])
m
HONIS
>>> print(word[-3:-7])
>>>
)A
If you try to slice a string with the starting index pointing to a position before or after
the ending index, the result is an empty string with no characters.
Only one index can be used to slice a string. If only one index is provided, Python
must determine whether it is the beginning or end of the slice. It assumes that the
(c
omitted index must refer to the string’s beginning or end, respectively. These examples
should help you understand how to slice using only one index:
>>> print(word[8:])
Notes
e
COOL
>>> print(word[-6:])
in
ISCOOL
>>> print(word[:6])
nl
PYTHON
>>> print(word[:-4])
PYTHONIS
O
>>>
We’ve seen string concatenation previously, but only briefly. The plus sign (+) is
used to do this. When two strings are “added,” the first string is stuck first, followed
ty
by the second string. This comes in handy when printing and, more importantly, when
using the input statement, which only accepts a single string as a parameter. Here’s a
quick example of string concatenation in action:
si
first = input(“Please enter your first name.\n”)
last = input(“Please enter your last name.\n”)
r
full = first+” “+last
ve
print(full)
Both operands must be strings for Python to recognise that you want string
concatenation. If you try to write “hello” + 7 for example, you’ll get a syntax error since
strings and integers can’t be added or concatenated.
ni
of what is stated. There are other versions, however the one used here will follow the
following rules1:
●● Take the first consonant cluster, cut and paste it to the end of the word, and
ity
add “ay” after it for words that start with a consonant and end with a vowel.
●● Add “way” after words that begin with a vowel.
●● Keep vowels out of terms with no vowels since they are likely difficult to grasp
as is.
m
Our initial objective will be to locate the first vowel’s index, if one exists. We must
avoid committing an index out of limits error, which occurs when we attempt to index
the string at an incorrect index. This is accomplished by first ensuring that the index is
)A
within the proper bounds before indexing the string with it. We can perform this in one
check thanks to short-circuiting. Python will not evaluate the second part of a Boolean
expression with a and if the first part is False.
We divide our work into the three situations indicated above once we’ve identified
this index, utilising slicing and string concatenation as needed.
(c
def main():
Notes
e
VOWELS = “AEIOU”
ans = “yes”
in
# Allow multiple cases.
while ans == “yes”:
mystr = input(“Enter a word, all uppercase letters.\n”)
nl
# Pig Latin Rule - Find first vowel
index = 0
O
while index < len(mystr) and (not mystr[index] in VOWELS):
index = index+1
# Just add “way” to words that start with a vowel.
ty
if index == 0:
print(mystr+”WAY”)
# Move first consonant cluster to end and add “ay”
si
elif index < len(mystr):
print(mystr[index:]+mystr[:index]+”AY”)
r
# If there are no vowels, just keep it as is!!!
ve
else:
print(mystr)
ans = input(“Would you like to translate another word?\n”)
ni
main()
The user can test numerous terms using the outer loop. The inner loop searches
for the first index that has a vowel. Note that we could have produced a string
U
containing consonants to see if mystr[index] was in it, but because typing out the
vowels was faster, we selected this approach and utilised the not operator. To produce
the output string, the proper slicing and concatenating is done in each of the three
circumstances. Notice how well the slicing works in the second case, because we can
ity
use the same index to describe both slices, thereby “reorganising” the word..
represent all data in a Python programme. (In a sense, code is also represented as
objects, as per Von Neumann’s model of a “stored programme computer.”)
Every object has a unique identity, a certain type, and a specific value. The identity
)A
of an object does not change once it is created; you can think of it as the object’s
memory address. The ‘is’ operator compares the identities of two objects, and the id()
function produces an integer that represents the identity of that object.
The type of an object dictates the operations it supports (for example, “does it have
(c
a length?”) as well as the available values for objects of that kind. The type() function
returns the type of an object (which is an object itself). The type of an object, like its
identity, is immutable. 1
Amity Directorate of Distance & Online Education
168 Python Programming
Some objects’ worth might fluctuate. Objects with mutable values are referred to
Notes
e
as mutable; objects with immutable values are referred to as immutable. (The value of
an immutable container object containing a reference to a mutable object can change
when the latter’s value changes; nonetheless, the container remains immutable
in
because the collection of objects it contains cannot be modified.) Immutability isn’t
the same as having an unchangeable value; it’s a little more nuanced.) The type of
an object determines its mutability; for example, numbers, strings, and tuples are
nl
immutable, whereas dictionaries and lists are mutable.
O
omit garbage collection entirely – how garbage collection is implemented is a matter of
implementation quality, as long as no items are collected that are still reachable.
ty
technique with (optional) delayed detection of cyclically linked trash, which collects most
objects as soon as they become inaccessible but does not guarantee that garbage with
circular references gets collected. Controlling the collection of cyclic trash may be found
in the gc module’s documentation. Python may change, and other implementations may
si
behave differently. When items become unreachable, don’t rely on them being finalised
right away (so you should always close files explicitly).
r
It’s worth noting that using the implementation’s tracing or debugging features may
keep items alive that would otherwise be collected. It’s also worth noting that using a
ve
‘try...except’ statement to catch an exception may keep objects alive.
Some objects refer to “external” resources like open files or windows. These
resources are freed when the object is garbage-collected, but because garbage
collection isn’t always assured, such objects give an explicit means to release
ni
the external resource, usually using the close() method. It is strongly advised that
programmes explicitly close such objects. The ‘try...finally’ and ‘with’ statements provide
easy ways to accomplish this.
U
Containers refer to items that contain references to other objects. Tuples, lists,
and dictionaries are examples of containers. The references are part of the value of a
container. When we talk about a container’s value, we usually mean the values of the
ity
contained objects, not their identities; yet, when we talk about a container’s mutability,
we only mean the identities of the immediately enclosed objects. If an immutable
container (such as a tuple) contains a reference to a changeable object, the value of the
immutable container changes as the mutable object changes.
m
Almost every aspect of object behaviour is influenced by type. Even the relevance
of object identity is influenced in some ways: operations that calculate new values
for immutable types may actually return a reference to any existing object with the
same type and value, whereas this is not allowed for mutable objects. For example,
)A
depending on the implementation, after a = 1; b = 1, a and b may or may not refer to the
same object with the value one, but after c = []; d = [], c and d are guaranteed to refer to
two different, unique, newly generated empty lists. (Note that c = d = [] gives both c and
d the same object.)
(c
a = ‘banana’
b = ‘banana’
Notes
e
We know a and b both refer to a string, but we’re not sure if they’re the same
string. There are two possible states, as depicted in the diagram below.
in
nl
Figure: State diagram
O
a and b relate to two separate objects with the same value in one circumstance.
They are referring to the same object in the second situation.
The is operator can be used to determine whether two variables correspond to the
same object:
ty
>>> a = ‘banana’
>>> b = ‘banana’
si
>>> a is b
True
r
Python only produced one string object in this case, and both a and b refer to it.
When you make two lists, however, you get two objects:
ve
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
ni
False
The two lists are equal in this situation because they have the same elements, but
they are not identical because they are not the same thing. Two items are equal if they
m
are identical, but they are not always identical if they are equivalent.
We’ve been using the terms “object” and “value” interchangeably up to this point,
but it’s more exact to say that an object has a value. When you evaluate [1, 2, 3], you
)A
receive a list object with a sequence of integers as its value. We say a list has the same
value as another if its elements are the same, but it is not the same thing.
4.1.8 Aliasing
(c
If a refers to an object and you assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
Notes
e
>>> b = a
>>> b is a
in
True
nl
O
Figure: State diagram
ty
A reference is a connection between a variable and an object. There are two
references to the same object in this example.
Because an object with multiple references has many names, we refer to it as aliased.
si
Changes made to one alias affect the other if the aliased object is mutable:
>>> b[0] = 42
>>> a r
ve
[42, 2, 3]
Because an object with multiple references has many names, we refer to it as aliased.
Changes made to one alias affect the other if the aliased object is mutable:
U
a = ‘banana’
b = ‘banana’
It almost never makes a difference whether a and b refer to the same string or not.
ity
def delete_head(t):
)A
del t[0]
>>> delete_head(letters)
>>> letters
[‘b’, ‘c’]
Notes
e
The parameter t and the variable letters are aliases for the same object. The stack
diagram looks like below
in
nl
O
Figure: Stack diagram
We drew the list between the two frames because it is shared by both.
ty
It’s crucial to distinguish between operations that modify existing lists and those
that create new ones. The append method for example, updates a list, whereas the +
operator produces a new list:
si
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> t1
[1, 2, 3]
r
ve
>>> t2
None
ni
>>> t3 = t1 + [4]
>>> t1
U
[1, 2, 3]
>>> t3
[1, 2, 3, 4]
ity
>>> t1
The + operator creates a new list and leaves the original list unchanged.
This difference is important when you write functions that are supposed to modify
m
lists. For example, this function does not delete the head of a list:
def bad_delete_head(t):
)A
t = t[1:] # WRONG!
The slice operator creates a new list and the assignment makes t refer to it, but
that doesn’t affect the caller.
>>> t4 = [1, 2, 3]
(c
>>> bad_delete_head(t4)
>>> t4
[1, 2, 3]
Notes
e
t and t4 refer to the same list at the start of bad delete head. t refers to a new list at
the conclusion, but t4 refers to the original, unmodified list.
in
Write a function that builds and returns a new list as an alternative. For example,
tail retrieves all of a list’s elements except the first:
nl
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is used:
O
>>> letters = [‘a’, ‘b’, ‘c’]
>>> rest = tail(letters)
ty
>>> rest
[‘b’, ‘c’]
si
4.2 Dictionary
In Python, a dictionary is an unordered collection of data values that can be used
to store data values like a map. Unlike other Data Types, which can only carry a single
r
value as an element, Dictionary can hold a key:value pair. The dictionary includes a
ve
key-value pair to make it more efficient.
lists as ordered collections of objects, dictionaries are similar; the main difference is that
items in dictionaries are stored and retrieved by key rather than positional offset. While
lists can perform similar functions to arrays in other languages, dictionaries replace
U
records, search tables, and any other aggregation in which item names are more
important than item positions.
For example, dictionaries can replace many of the searching methods and data
ity
dictionaries:
e
Items in a dictionary aren’t preserved in any specific order, unlike those in a list;
in fact, Python pseudo-randomizes their left-to-right order to provide fast search. The
in
symbolic (rather than physical) positions of entries in a dictionary are provided by keys.
nl
Dictionaries, like lists, can grow and shrink in place (without making new copies),
contain items of any type, and support nesting to any depth (they can contain lists,
other dictionaries, and so on). A single value can be linked with each key, but that value
O
can be a collection of several objects if necessary, and a given value can be stored
under any number of keys.
ty
You may mutably alter dictionaries by assigning to indexes, but they don’t support
the sequence operations that operate on strings and lists. Because dictionaries
are unsorted collections, operations that need a defined positional order (such as
si
concatenation and slicing) are ineffective. Dictionary objects are the sole built-in, core
type members of the mapping category, which includes objects that map keys to values.
Imported modules in Python create other mappings.
Python uses optimal hashing techniques to locate keys, making retrieval speedy.
Dictionaries, like lists, keep track of object references (not copies, unless you ask for
them explicitly).
U
as a guideline As of Python 3.3, the table Common dictionary literals and operations
covers some of the most common and representative dictionary operations. For a
complete list, consult the library manual or use a dir(dict) or help(dict) command—dict is
ity
the type name. A dictionary is written as a set of key:value pairs separated by commas
and surrounded in curly braces when coded as a literal expression. 4 You can nest
dictionaries by simply coding one as a value inside another dictionary, a list, or a tuple.
m
)A
(c
Operation Interpretation
Notes
e
D = {} Empty dictionary
D = {‘name’: ‘Bob’, ‘age’: 40} Two-item dictionary
in
E = { ‘cto’: {‘name’: ‘Bob’, ‘age’: 40}} Nesting
D = dict(name=’Bob’, age=40) alternative construction techniques:
nl
D = dict([(‘name’, ‘Bob’), (‘age’, 40)]) keywords, key/value pairs, zipped key/value pairs, key lists
D = dict(zip(keyslist, valueslist))
O
D = dict.fromkeys([‘name’, ‘age’])
D[‘name’] Indexing by key
E[‘cto’][‘age’]
ty
‘age’ in D Membership: key present test
D.keys() Methods: all keys,
D.values() all values,
si
D.items() all key+value tuples,
D.copy() copy (top-level),
D.clear() r clear (remove all items),
ve
D.update(D2) merge by keys,
D.get(key, default?) fetch by key, if absent default (or None),
D.pop(key, default?) remove by key, if absent default (or error)
ni
●● There are 26 variables in total, one for each letter of the alphabet.
(c
Then, using a chained conditional, you could scan the string and increment the
corresponding number for each character.
e
Then, using the built-in function ord, transform each character to a number, use
the number as an index within the list, and increment the appropriate counter.
in
●● You could make a dictionary with keys that are characters and counters that
are counters.
You would add an item to the dictionary the first time you saw a character. The
nl
value of an existing item would then be increased.
Each of these options does the same calculation, but they do so in a different method.
O
An implementation is a method of carrying out a computation; some are better than
others. One advantage of the dictionary approach is that we don’t have to know which
letters will appear in the string ahead of time, and we simply have to create room for the
ones that will.
ty
Example:
word = ‘brontosaurus’
si
d = dict()
for c in word:
if c not in d:
d[c] = 1
r
ve
else:
d[c] = d[c] + 1
print(d)
ni
The for loop loops through the string. If the character c is not in the dictionary at the
end of the loop, we create a new item with the key c and the value 1 as the starting value
(since we have seen this letter once). We increment d[c] if c is already in the dictionary.
ity
Output:
m
The dictionary is assigned to the variable D, and the value of the key’spam’ is 2,
Notes
e
and so on. To index dictionaries by key, we use the same square bracket syntax we
used to index lists by offset, but this time it indicates access by key rather than position.
in
The left-to-right arrangement of keys in a dictionary, like sets, will nearly always be
different from what you typed. This is on purpose: keys must be reordered in memory
to perform rapid key lookup (a.k.a. hashing). That’s why dictionaries don’t support
nl
operations that presume a fixed left-to-right order (e.g., slicing, concatenation); you can
only get values by key, not by position. Technically, the ordering is pseudo-random—
not it’s completely random (you might be able to figure it out if you have Python’s
source code and a lot of time on your hands), but it’s arbitrary and can vary by version,
O
platform, and even interactive session in Python 3.3.
The built-in len function also works with dictionaries; it returns the number of things
contained in the dictionary, or the length of its keys list, in this case. The keys function
ty
retrieves all the keys in the dictionary, and the dictionary in membership operator
allows you to test for key existence. The latter of these can be beneficial for processing
dictionaries in order, but the order of the keys list should not be relied upon. Because
si
the keys result can be used as a regular list, it can always be sorted if order is important
(more on dictionaries and sorting later):
r
ve
Pay attention to the second expression in this list. The in membership test for strings
ni
and lists also works on dictionaries, checking whether a key is stored in the dictionary, as
previously indicated. This works because dictionaries define iterators that automatically
step over their key lists. Iterators for other types are provided that represent their usual
U
applications; for example, files include iterators that read line by line.
Take note of the last example in this list’s syntax. In Python 3.X, we must
encapsulate it in a list call for similar reasons: keys returns an iterable object rather than
an actual list. Although the list call isn’t required in certain other instances, it causes it to
ity
without having to build new ones. To change or create an item, simply assign a value to
a key. Deleting the entry linked with the key supplied as an index is also possible with the
del statement. In this example, notice how a list is nestled inside a dictionary (the value of
)A
the key ‘ham’). In Python, all collection data types can nest inside each other at will:
(c
Notes
e
in
nl
O
Assigning to an existing index in a dictionary alters its associated value, just like
lists. In contrast to lists, whenever you provide a new dictionary key (one that hasn’t
ty
been allocated previously), you generate a new entry in the dictionary, just as you did
in the preceding example with the key ‘brunch.’ This doesn’t work for lists because you
can only assign to existing list offsets—any offset beyond the end of a list is considered
si
out of bounds and raises an error in Python. Instead, you should utilise techniques like
the append method or slice assignment to grow a list.
Dictionary Methods r
ve
Dictionary techniques offer a wide range of type-specific features. The dictionary
values and items methods for example, return all of the dictionary’s values and
(key,value) pair tuples, respectively; they, together with keys, are handy in loops that
need to step through each dictionary entry one by one.
ni
In 3.X, these two methods for keys also return iterable objects, so wrap them in a
list call to collect all of their values at once for display:
U
ity
You won’t be able to forecast what will be in a dictionary before the programme is
begun, much less when it’s coded, in practical programmes that collect data as they
run. If the key doesn’t exist, the get method gives a default value—None or a passed-
in default—instead of an error. When your software can’t predict contents ahead of
m
time, it’s a simple approach to fill in a default for a key that isn’t present and prevent a
missing-key error:
)A
(c
dictionaries). It combines the keys and values of two dictionaries into one, overwriting
Notes
e
values of the same key if there is a conflict:
in
nl
Notice how the key order in the last result is all over the place; that’s just how
dictionaries work. Finally, the dictionary pop method removes a key from a dictionary
and returns the value that it previously held. It’s similar to the list pop method, but
O
instead of an optional position, it takes a key:
ty
r si
ve
ni
U
Let’s look at an example of a dictionary that is more realistic. The following example
constructs a simple in-memory Monty Python movie database as a table that matches
movie release date years (the keys) to movie titles in honour of Python’s namesake (the
values). You get movie names by indexing on release year strings, as coded:
m
)A
(c
Although dictionaries aren’t sequences like lists and strings, it’s simple to cycle
Notes
e
through the elements in one by calling the dictionary keys method, which returns all
stored keys, which you can traverse through with a for loop. You can index from key to
value as you go inside the for loop if necessary, as shown in this code.
in
In reality, most for loops in Python allow you to move through a dictionary’s keys
list without ever executing the keys method. Saying for key in D works the same as
nl
saying for key in D.keys for any dictionary D. (). This is simply another example of
the iterators stated above, which allow the in membership operator to function with
dictionaries as well.
O
4.2.4 Iterating a Dictionary, Reverse Lookup
As seen below, a for loop may be used to iterate over all of the keys in a dictionary.
Each time the loop body executes, a different key from the dictionary is saved in the for
ty
loop’s variable, k.
r si
This programme starts by establishing a new dictionary with three key-value pairs
ve
when it runs. The for loop then loops through the keys in the dictionary. The body of
the loop executes once the first key in the dictionary, pi, is placed in k. It generates a
coherent message that incorporates pi as well as its value of 3.14. Control then returns
to the top of the loop, where e is kept in k. The loop body runs a second time, this
ni
time displaying a message stating that e is 2.71. Finally, with k equal to root 2, the loop
executes a third time, and the final message is displayed.
U
It is also possible to use a for loop to go over the values in a dictionary (instead of
the keys). This is performed by using the values method on a dictionary to produce the
collection of values utilised by the for loop, which does not take any arguments. The
following programme for example, computes the sum of all the values in a dictionary.
ity
Constants.values() will return a collection with the values 3.14, 2.71, and 1.41 after it
runs. Each of these values is saved in v as the for loop runs, and thus allows the total to
be computed without accessing any of the dictionary’s keys.
m
)A
(c
While loops are more efficient than for loops in some dictionary issues. The
following programme for example, use a while loop to read strings from the user until 5
distinct values have been entered. The counts for all of the strings are then presented.
Amity Directorate of Distance & Online Education
180 Python Programming
Notes
e
in
nl
O
When you run this programme, it starts by constructing an empty dictionary. The
ty
while loop condition is then assessed. Using the len function, it determines how many
key-value pairs are in the dictionary. The condition evaluates to True and the loop body
executes because the number of key-value pairs is originally zero.
si
A string is read from the user each time the loop body executes. The in operator is
then used to see if the string has already been assigned to a key in the dictionary. If this
is the case, the key’s associated count is incremented by one. Otherwise, the string is
r
added to the dictionary as a new key with the value 1 and is stored in the dictionary. The
ve
loop will continue until there are 5 key-value pairs in the dictionary. When this happens, all
of the strings supplied by the user, as well as their related values, are shown.
Reverse Lookup
ni
It’s simple to find the appropriate value v = d[k] given a dictionary d and a key k. A
lookup is the term for this procedure.
But what if you already have v and are looking for k? You have two issues:
U
first, there could be several keys that correspond to the value v. Depending on the
programme, you may be able to select one or you may be required to create a list that
includes all of them. Second, a reverse lookup does not have a straightforward syntax;
ity
Here’s a function that accepts a value and returns the first key that corresponds to it:
m
)A
This function is another example of the search pattern, but it employs a new
feature, raise, that we haven’t seen previously. The raise statement throws an
exception, in this case a LookupError, which is a built-in exception that indicates a failed
lookup operation.
We raise an exception if we reach the conclusion of the loop and v does not appear
(c
Notes
e
in
Example:
Create a reverseLookup function that finds all of the keys in a dictionary that
nl
correspond to a certain value. The dictionary and the value to search for will be the sole
parameters passed to the function. It will provide a list of keys from the dictionary that
map to the specified value (which may or may not be empty).
O
As part of your solution to this exercise, include a main programme that
demonstrates the reverseLookup function. Your software should first generate a
dictionary, then demonstrate that the reverseLookup method returns multiple keys,
ty
a single key, and no keys appropriately. Make sure your primary programme only
runs when the file holding your exercise solution hasn’t been imported into another
programme.
si
Solution:
r
ve
ni
U
ity
m
)A
(c
Notes
e
in
nl
O
4.2.5 Dictionary and Lists
You can create dictionaries that are dictionaries of dictionaries. However, by
ty
combining lists and dictionaries, more sophisticated data structures can be created. You
can have a dictionary with a list of dictionaries or a dictionary with only lists as values.
A dictionary or a list can be created from any sublist or subdictionary. Although this may
appear to be a complex data structure, it can be quite useful in describing hierarchical
si
data. We’re going to depict a bunch of cars in this initial example. This information could
be about cars we possess, cars we want to buy, or cars that are waiting to be sold at a
used car dealership:
r
ve
ni
U
ity
Each entry of the list in this example is a dictionary. The keys in each dictionary are
m
the same. It would be simple to loop through all of the automobiles using this structure,
looking for all cars that meet a set of criteria. For example, if we wanted to locate all
cars with four doors and a mileage of fewer than 50,000 miles in our database, we
could use the following code:
)A
(c
Notes
e
in
nl
O
ty
r si
ve
We have a lexicon of people in this case. As keys, we use their names. Each
individual is represented as a set of key/value pairs in a dictionary. However, if you look
at the allergies key, you’ll notice that each person’s value is a list of everything they’re
allergic to. There can be any number of elements in the list, even zero. This is how we
ni
individual is allergic to. We can tell that Joe is allergic to tree pollen, carrots, and onions
in his case. Mary’s allergy list is blank, indicating that she is not allergic to anything.
We could use the following to create a printout of all people and their allergies:
(c
Notes
e
in
nl
O
ty
r si
We may create highly complicated data structures by combining lists and
ve
dictionaries. Python code can be built in a fairly simple way to acquire the specific
information you want as long as you understand the layers that make up the data
structure. As demonstrated, an appropriate sequence of indices and/or keys is used to
extract the data that is significant to you.
ni
may be called several times with the same arguments. Memoization is based on the
principle of only computing a value in a function once. Then we make a mental note
to return the value we just computed when the function is invoked with the same
arguments again. This saves you the trouble of having to recalculate the figure.
ity
The recursive Fibonacci function is a great example of this. This is how the
Fibonacci sequence is defined.
●● Fib(0) = 0
m
●● Fib(1) = 1
●● Fib(n) = Fib(n−1) + Fib(n−2)
This sequence can be computed recursively by writing a Python function as follows.
)A
(c
This function, on the other hand, should never be used for anything other than
Notes
e
a simple example of a small Fibonacci number. Even something as large as fib(100)
cannot be computed with the function. Even the best computers will take a long time to
run the function with an argument of 100. Consider what occurs when fib is computed
in
(5). To do so, you must first compute fib(4) and fib(3).
The two findings can then be combined to find fib (5). However, in order to compute
nl
fib(4), the numbers fib(3) and fib(2) must first be calculated. To compute fib(5), we must
now compute fib(3) twice. However, to compute fib(3), we must first compute fib(2) and
fib(3) (1). However, fib(2) must be computed in order to determine fib(4).
O
As you can see in Fig: Computing fib(5), computing fib requires a lot of calls to the fib
function (5). Consider how many phone calls it would take to calculate lie (6). To compute
fib(6), we must first compute fib(5), and then fib(6) (4). To compute fib(5), it took 15 calls
to fib, and we can see from the graph that it takes 9 calls to compute fib(6) (4).
ty
It will take 25 calls to fib to compute fib, including the call to fib(6) (6). It will take 15
+ 25 + 1 calls, or 41 calls, to compute fib(7). This method of computing fib(n) more than
doubles the number of calls required to compute fib(n2). Exponential growth is the term
si
for this. The fib function has an O complexity (2n). Except for relatively tiny values of n,
an exponentially complex function is useless.
r
ve
ni
U
ity
m
There is yet hope. There are more efficient techniques to calculate the Fibonacci
sequence. Avoiding all of that unneeded effort is the best approach to increase
)A
efficiency. We should not compute fib(2) again once it has been computed. That job has
already been completed. There are at least a few options for increasing efficiency. One
technique, which is probably the best, is to remove the recursion and compute fib(n)
with a loop. The recursive function, on the other hand, is closer to the original definition.
Memoization can help us improve the recursive version of the function.
(c
The memo dictionary is used in the following section to map n variables to their
fib(n) results.
e
in
nl
O
ty
r si
ve
ni
U
ity
In the previous section, the memoized fib function records any value returned by
the function in its memo. The enclosing scope is used to access the memo variable.
We don’t build the memo locally since we want it to last from one fib call to the next.
m
The answer is saved in the memo each time fib is called with a new value of n. The
memoized result is looked up and returned when fib(n) is called again for some n.
As a result, the memoized fib function now has O(n) complexity and can
)A
This is an extreme example of how memoization can help, but it can be useful in a
variety of scenarios.
Global variable
Notes
e
Global variables are variables that are utilised throughout the programme; once
defined, they can be used as a main function or any other function.
in
This type of variable can be changed anywhere in the programme, which may
appear to be a benefit, but it may also cause confusion for the programmer and anybody
else who reads the programme. Another disadvantage of global variables is that they
nl
might take up more space than common variables since they cannot be deleted at the
end of the function. On the other hand, this feature prevents the code from being reused,
which makes Python one of the most appealing programming languages.
O
Working with global variables is considered bad practise in general, yet having
comprehensive knowledge is never too much. After that, we’ll look at how to declare a
global variable.
ty
This necessitates the usage of the global command:
r si
ve
Calling or declaring a global variable is not difficult, as we saw in the previous
example. We may compare it to how we declared variables; the only difference is that the
variable “var” will now have a global character, allowing any function to access it easily.
ni
not type or size declarations. The global statement informs Python that a function
intends to change one or more global names, i.e. names that exist within the scope of
the enclosing module (namespace).
ity
●● Global names are variables assigned at the top level of the enclosing module file
●● Global names must be declared only if they are assigned within a function.
●● Global names may be referenced within a function without being declared.
To put it another way, global allows us to alter names that exist outside of a def
m
at the module file’s top level. The nonlocal statement is nearly identical to the local
statement, but it applies to names in the enclosing def’s local scope rather than names
in the enclosing module, as we’ll see later.
)A
Notes
e
in
nl
The X inside the def now refers to the X outside the def; they’re the same variable
this time, thus changing X inside the function modifies X outside it. Here’s an example
O
of global at work that’s a little more involved:
ty
Within the function all global, x, y, and z are all globals. y and z are global since
they aren’t allocated in the function; x is global because it was explicitly mapped to the
si
module’s scope in a global statement. By virtue of the assignment, x would be deemed
local without the global.
r
It’s worth noting that y and z aren’t declared global; Python’s LEGB lookup rule
automatically locates them in the module. Also, before the function starts, x does not
ve
exist in the enclosing module; in this situation, the initial assignment in the function
generates x in the module.
>>> fibonacci(50)
U
12586269025L
The L at the end denotes that the result is of type long, or a long integer. Long has
been deprecated in Python 3, and all integers, including very large ones, are now of
ity
type int.
Integer values have a fixed range; long integers can be arbitrarily large, but they
require more space and time as they grow larger.
m
The mathematical operators, as well as the math module’s functions, work with
long integers, thus any code that works with int will likewise work with long.
1000000
(c
10000000000L
The result in the first case is of type int, while the result in the second case is of
Notes
e
type long.
in
4.3 Tuple
Tuples also have two type-specific callable methods in Python 3.0, but not nearly
as many as lists:
nl
>>> T.index(4) # Tuple methods: 4 appears at offset 3
3
O
>>> T.count(4) # 4 appears once
1
The main difference between tuples and other types of data is that they can’t be
ty
modified after they’ve been generated. They are, in other words, unchanging sequences:
si
AttributeError: ‘tuple’ object has no attribute ‘append’
Tuples, like lists and dictionaries, accept mixed types and nesting, but because
they are immutable, they do not grow and shrink: r
ve
Why Tuples?
So, why have a type that is similar to a list but only allows a limited set of
operations? In fact, tuples aren’t used nearly as frequently as lists, but their immutability
ni
is the whole idea. If you pass a list of objects throughout your programme, it can be
modified anywhere; if you use a tuple, it can’t be changed. Tuples, in other words, give
an integrity constraint that is useful in programmes larger than the ones we’ll build
today. Tuples will be discussed in greater depth later in the book. But for now, let’s
U
In many aspects, a tuple is similar to a list. Tuples, like lists, hold a collection of
elements of various data kinds. A comma separates the tuple’s elements, which are
then enclosed in parentheses.
Tuples, like Lists, are perhaps the most commonly used container types in Python.
They can be found in practically any Python programme that isn’t trivial.
)A
Tuples are an immutable ordered collection of objects, which means that each
member in a tuple has a fixed place (its index), which does not change over time. It is
true that after a tuple has been generated, it is not feasible to add or delete elements.
(c
Tuples are used to create simple object groups. Tuples are similar to lists in that
they can’t be changed in place (they’re immutable), and they’re commonly represented
as a series of elements in parenthesis rather than square brackets. Tuples share most
of their attributes with lists, despite the fact that they don’t have as many methods.
Notes
e
Here’s a quick rundown of the fundamentals. The following are examples of multiples:
●● Ordered collections of arbitrary objects: Tuples, like strings and lists, are
in
positionally ordered collections of objects (i.e., their contents are in a left-to-
right order), and they can include any type of object.
●● Accessed by offset: Items in a tuple are accessible by offset (not by key),
nl
just like strings and lists, and they allow all offset-based access operations like
indexing and slicing.
●● Of the category “immutable sequence”: Tuples are sequences, much like
O
strings and lists, and they enable many of the same operations. Tuples, like
strings, are immutable, and they don’t support any of the in-place change
operations that are supported by lists.
●● Fixed-length, heterogeneous, and arbitrarily nestable: You can’t change the
ty
size of a tuple without making a copy since tuples are immutable. Tuples, on
the other hand, permit arbitrary nesting since they can hold any sort of object,
including other compound objects (e.g., lists, dictionaries, and other tuples).
si
●● Arrays of object references: Tuples are best conceived of as object
reference arrays, similar to lists; they hold access points to other objects
(references), and indexing a tuple is quite fast.
r
A tuple is a set of values in order. Tuples are similar to lists in that the values can
ve
be of any type and are indexed by integers. The most significant distinction is that
tuples are immutable.
>>> t1 = ‘a’,
ity
>>> type(t1)
<class ‘tuple’>
>>> t2 = (‘a’)
>>> type(t2)
<class ‘str’>
)A
The built-in function tuple is another way to make a tuple. It makes an empty tuple
if there is no argument:
>>> t = tuple()
(c
>>> t
()
The result is a tuple with the items of the sequence if the argument is a sequence
Notes
e
(string, list, or tuple):
>>> t = tuple(‘lupins’)
in
>>> t
(‘l’, ‘u’, ‘p’, ‘i’, ‘n’, ‘s’)
nl
You should avoid using tuple as a variable name because it is the name of a built-
in function.
Tuples are supported by the majority of list operators. The bracket operator is used
O
to index a specific element:
ty
‘a’
si
>>> t[1:3]
(‘b’, ‘c’)
r
However, if you try to change one of the tuple’s elements, you’ll get the following error:
ve
>>> t[0] = ‘A’
TypeError: object doesn’t support item assignment
You can’t change the elements of tuples because they’re immutable. However, you
ni
The relational operators work with tuples and other sequences, and Python
compares the first member in each sequence first. If they are equal, it moves on to the
next element, and so on, until it comes across elements that are different. Subsequent
elements are not taken into account (even if they are really big).
m
True
Tuple Assignment
Swapping the values of two variables is frequently useful. You must utilise a
(c
>>> temp = a
>>> a = b
Notes
e
>>> b = temp
in
>>> a, b = b, a
A tuple of variables is on the left, while a tuple of expressions is on the right. Each
nl
value is associated with its own variable. Before any of the assignments, all of the
expressions on the right side are evaluated.
The number of variables on the left must equal the number of values on the right:
O
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
ty
The right side might be any form of sequence in general (string, list or tuple). To
separate an email address into a user name and a domain for example, you could write:
si
>>> uname, domain = addr.split(‘@’)
Split returns a list with two elements, the first of which is assigned to uname and
the second to domain:
r
ve
>>> uname
‘monty’
>>> domain
‘python.org’
ni
A function can only return one value in strict terms, however if the value is a tuple,
it has the same impact as returning many values. For example, computing x/y and
then x percent y is wasteful when dividing two integers and computing the quotient and
remainder. It is preferable to do both at the same time.
ity
Divmod is a built-in function that takes two arguments and returns a tuple of two
values: the quotient and remainder. The result can be saved as a tuple:
>>> t = divmod(7, 3)
m
>>> t
(2, 1)
>>> rem
1
e
def min_max(t):
return min(t), max(t)
in
The built-in functions max and min are used to find the largest and smallest entries
in a sequence. Both are computed by min max, which gives a tuple of two values.
nl
4.3.2 Variable Length Argument Tuples
In Python, there are two types of data structures: list and tuple. The list has
O
dynamic properties, but the tuple has static ones.
In other languages, lists are declared similarly to arrays. Lists don’t have to be
homogeneous all of the time, which makes it Python’s most powerful tool. The list is
ty
a sort of container in Python’s Data Structures that is used to hold numerous pieces
of data at once. Lists are a good way to keep track of a succession of data and iterate
over it.
si
Syntax:
list_data = [‘an’, ‘example’, ‘of’, ‘a’, ‘list’]
r
Tuple is another sequence data type that can contain elements of many data types,
ve
but it is immutable. A tuple, in other terms, is a set of Python objects separated by
commas. Because of its static nature, the tuple is faster than the list.
Syntax:
ni
An asterisk (*) is placed before the variable name that contains the values of all
nonkeyword variable parameters. This tuple remains empty if no more arguments are
specified during the function call.
ity
def printall(*args):
print args
m
The gather parameter can have any name you like, but args is conventional. Here’s
how the function works:
The antonym of gather is scattered. If you have a series of values, you can use the
* operator to provide them to a function as many parameters. Divmod for example, only
takes two arguments and does not operate with a tuple:
(c
>>> t = (7, 3)
>>> divmod(t)
Amity Directorate of Distance & Online Education
194 Python Programming
e
But if you scatter the tuple, it works:
>>> divmod(*t)
in
(2, 1)
nl
●● For variable length arguments, the word ‘*args’ is not necessary. Only the
letter * is required, and the variable name can be anything, such as *numbers
or *names.
O
●● Variable length arguments can be used to pass zero or more arguments to a function.
●● The values given to *args are combined to form a tuple.
●● Before variable args, a formal argument is allowed, but not after variable args.
ty
Variable arguments come before keyword arguments.
si
Despite their resemblance to lists, tuples are frequently utilised in distinct settings
and for different purposes. Tuples are immutable and often contain a heterogeneous
sequence of components that can be retrieved using unpacking or indexing. Lists are
r
mutable, and indexing is used to access their items. In a tuple, items cannot be added,
ve
deleted, or replaced.
ni
U
ity
If you try to change “great barrier” with another item in the tuple coral reef, such as
“pickles reef,” you’ll get a TypeError since tuples can’t be edited more than 1-2 lines. By
supplying the tuple name to the list() method on the 3rd and 4th lines, you can convert a
tuple to a list. You can alter an item within a tuple if it is mutable. When a list is present
as an item in a tuple, any changes to the list are reflected in the tuple’s overall items. As
m
an example,
5. >>> german_cars
[‘porsche’, ‘audi’, ‘bmw’, ‘mercedes’]
6. >>> european_cars
(‘ferrari’, ‘volvo’, ‘renault’, [‘porsche’, ‘audi’, ‘bmw’, ‘mercedes’]) Notes
e
When the underlying list changes, the tuple “containing” the list appears to change as
in
well. Tuples have no way of knowing whether the things inside them are mutable, which
is the important insight. A method that updates an item’s data is the sole thing that makes
it changeable. There is no way to detect this in general. The tuple remained unchanged.
nl
It couldn’t alter because it lacks mutating capabilities. When the list is updated,
the tuple is not notified of the change. The list isn’t sure if it’s being referenced by a
variable, a tuple, or another list 1st through 6th. The tuple itself isn’t mutable because it
O
doesn’t have any methods for modifying its contents. Similarly, the string is immutable
since it lacks any altering methods.
ty
Sr. No. List Tuple
1. List are mutable Tuples are immutable
Implication of iterations is Time- The implication of iterations is
si
2.
consuming comparatively Faster
The list is better for performing operations, Tuple data type is appropriate for
3.
such as insertion and deletion accessing the elements
4.
List consume more memory r
Tuple consume less memory as
ve
compared to the list
Lists have several built-in methods Tuples does not have many built-in
5.
methods
The unexpected changes and errors are In tuple, it is hard to take place
6.
ni
Key: value pairs are the building blocks of dictionaries. Lists and tuples are
arranged and retrieved in Python based on their position. Keys and values are used to
structure and retrieve dictionaries in Python. It doesn’t matter where a pair of keys and
ity
Curly brackets are used to define dictionaries in Python. The key-value pairs that
make up the dictionary are separated by commas. A colon connects each key-value pair:
Let’s put two people’s ages in a dictionary. Gabby and Maelle are the two
m
individuals. Gabby is eight years old, and Maelle is five. It’s worth noting that Gabby’s
name is a string and her age is an integer.
)A
By supplying the tuple name to the dict() function, tuples can be turned to
Notes
e
dictionaries. This is accomplished by nesting tuples within tuples, with two elements in
each nested tuple item (1st and 2nd line). When a tuple is turned to a dictionary, the
first item becomes the key and the second item becomes the value (3rd line).
in
In a dictionary, the method items() returns a list of tuples, each of which
corresponds to a key:value pair in the dictionary. As an example,
nl
1. >>> founding_year={“Google”:1996, “Apple”:1976, “Sony”:1946, “ebay”:1995,
“IBM”:1911}
2. >>> founding_year.items()
O
dict_items([(‘Google’, 1996), (‘Apple’, 1976), (‘Sony’, 1946), (‘ebay’, 1995),
(‘IBM’, 1911)])
3. >>> for company, year in founding_year.items():
ty
... print(f”{company} was found in the year {year}”)
Output
si
Google was found in the year 1996
Apple was found in the year 1976
Sony was found in the year 1946
r
ebay was found in the year 1995
ve
IBM was found in the year 1911
Because the items() method returns a fresh view of the dictionary’s key and value pairs
as tuples, which sequentially iterates through each of the key:value pairs in the dictionary,
ni
the for loop in the third line contains two iteration variables—company and year.
The relational operators work with tuples and other sequences, and Python
compares the first member in each sequence first. If they are equal, it moves on to the
next element, and so on, until it comes across elements that are different. Subsequent
ity
elements are not taken into account (even if they are really big).
Thus, in Python, tuples are compared based on their order: the first item of the first
tuple is compared to the first item of the second tuple. If they are not equal, the output
can be deduced from the first comparison. Otherwise, the second item is considered,
m
followed by the third, and so on, until both tuples’ corresponding elements have
been compared.
In the same way, the sort function operates. It sorts by the first element in most
)A
cases, but if there is a tie, it sorts by the second element, and so on.
In other words, each tuple’s comparison begins with the first element. If they don’t
match =, or >, it moves on to the next element, and so on.
e
True
In the same way, the sort function operates. It sorts by the first element in most
in
cases, but if there is a tie, it sorts by the second element, and so on.
This functionality lends itself to a pattern known as DSU, which stands for Decorate
A Sequence by creating a list of tuples with one or more sort keys preceding the
nl
sequence’s items, sort the list of tuples, and Undecorate by removing the sequence’s
sorted elements.
O
Consider the following scenario: you have a list of words that you wish to sort from
longest to shortest:
def sort_by_length(words):
ty
t = []
for word in words:
t.append((len(word), word))
si
t.sort(reverse=True)
res = []
for length, word in t:
r
ve
res.append(word)
return res
The first loop generates a list of tuples, each of which consists of a word followed
ni
by its length.
Sort compares the first element, length, first, and breaks ties only with the second
element. Sort is told to go in decreasing order by the keyword parameter reverse=True.
U
The second loop iterates through the tuple list, creating a list of words in
decreasing length order.
ity
To begin with, strings are more constrained than other sequences due to the
fact that the constituents must be characters. They’re also unchangeable. Instead
of constructing a new string, you might wish to use a list of characters if you need to
update the characters in an existing one.
)A
Lists are more commonly used than tuples, owing to their mutability. However,
there are a few situations when tuples may be preferable:
●● You must use an immutable type like a tuple or string if you want to utilise a
sequence as a dictionary key.
e
decreases the chance of aliasing causing unexpected behaviour.
Because tuples are immutable, they lack operations that modify existing lists,
in
such as sort and reverse. However, Python has built-in functions such as sorted, which
returns a new list with the same members in sorted order, and reversed, which returns
an iterator that traverses the list in reverse order.
nl
Summary
●● Python also has a higher-order function called map. The specified function is applied
O
to all items in the iterable(s) passed to Map. It returns a new iterable that contains
the results of the applied function. It’s the functional counterpart of a for loop applied
to an iterable that collects the results of each iteration around the for loop.
●● The filter() function is a higher-order function that takes in a function to filter
ty
elements from a collection. The filter() function creates a new iterable with only the
elements selected by the test function.
●● The pop method is used to remove an element from a list at a specific index. As an
si
optional input to pop, the index of the element to remove is provided. Pop removes
the last element from the list if the argument is missing. The only outcome of the
pop method is the value that was removed from the list. When this value is needed
r
for a later calculation, call pop on the right side of an assignment statement to
ve
save it into a variable.
●● A list is a collection of elements separated by commas and enclosed in square
brackets. These are comparable to arrays in other programming languages,
however unlike arrays, the elements in the list can be of various data types. Lists
ni
are changeable, which means they can be changed after they’ve been created.
●● A string is a collection of characters in a specific arrangement. Alphabets, numerals,
and special characters, such as spaces, are examples of these characters. Single
U
quote marks (e.g., “hello”) or double quotation marks (e.g., “python course”) are
used to contain string values. The quotations are not part of the string; they are
utilised by the interpreter to indicate the start and end of the string.
ity
●● Slicing is the process of extracting a substring from a given string. Giving both
the starting and ending indexes of a substring is an explicit way to denote it. The
ending value is not included in the set of values represented in a slice in Python,
just as it is not included in the set of values described in the range function.
m
lists as ordered collections of objects, dictionaries are similar; the main difference
is that items in dictionaries are stored and retrieved by key rather than positional
offset.
●● An implementation is a method of carrying out a computation; some are better
than others. One advantage of the dictionary approach is that we don’t have to
(c
know which letters will appear in the string ahead of time, and we simply have to
create room for the ones that will.
e
may be called several times with the same arguments. Memoization is based on
the principle of only computing a value in a function once. Then we make a mental
note to return the value we just computed when the function is invoked with the
in
same arguments again.
●● In many aspects, a tuple is similar to a list. Tuples, like lists, hold a collection of
nl
elements of various data kinds. A comma separates the tuple’s elements, which
are then enclosed in parentheses.
●● A Tuple represents a collection of ordered and immutable objects (cannot be
O
modified). Tuples are indexed and allow duplicate members.
●● Tuples, like Lists, are perhaps the most commonly used container types in Python.
They can be found in practically any Python programme that isn’t trivial.
ty
Glossary
●● Global variable: Global variables are variables that are utilised throughout the
programme; once defined, they can be used as a main function or any other
si
function.: Converts the first character of the string to a capital (uppercase) letter.
●● Reverselookup: Doing a reverse dictionary lookup returns a list containing each
key in the dictionary that maps to a specified value.
●●
r
Python List append(): Add a single element to the end of the list
ve
●● Python List clear(): Removes all Items from the List
●● Python List copy(): returns a shallow copy of the list
●● Python List count(): returns count of the element in the list
ni
●● Python List extend(): adds iterable elements to the end of the list
●● Python List index(): returns the index of the element in the list
U
1. Python supports list slicing, which allows you to extract a portion of a list by specifying
an index range and the _ _ _ _ _ _ _ _ _operator
a. colon (:)
b. and &
(c
c. Or
d. None of the above.
e
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
in
print(List)
nl
c. [4.445, 3, 5.33, 1.054, 2.5]
d. [2.3, 4.445, 3, 2.5]
O
3. The _ _ _ _ _ _ _function is a higher-order function that takes in a function to filter
elements from a collection.
a. copy()
ty
b. move()
c. cat()
si
d. None of the above
4. The _ _ _ _ _ _ _function takes an iterable and applies a function on each element,
combining the results into a single result.
a. Filter()
r
ve
b. reduce()
c. pop()
d. None of the above
ni
a. list
b. tupple
c. Dictionary
ity
b. local
c. both a and b
d. none of the above
)A
7. The _ _ _ _ at the end denotes that the result is of type long, or a long integer.
a. L
b. M
(c
c. T
d. LI
8. A tuple is similar to a_ _ _ _ _ _.
Notes
e
a. dictionary
b. list
in
c. array
d. None of the above
nl
9. What will be the output of following program:
List = [‘Mathematics’, ‘chemistry’, 1997, 2000]
List.insert(2,100)
O
print(List)
ty
c. [‘Mathematics’, 2 ‘chemistry’, 1997, 2000]
d. [‘Mathematics’, 100, ‘chemistry’, 1997, 2000]
si
10. What will be the output of following program:
List = [4, 4, 3, 1, 4, 2, 1, 2, 3, 2, 1]
print(List.count(4))
r
ve
a. 2
b. 3
c. 4
ni
d. 1
Exercise
U
b. List Slicing
3. Explain different list methods.
4. Define map, filter and reduce.
m
8. Explain aliasing.
9. What do you mean by list arguments?
10. What do you mean by Dictionary?
(c
e
14. Define long integers.
15. What do you mean by tuples?
in
16. Define variable length argument tuples.
17. Define sequences of sequences.
nl
Learning Activities
1. Create a Python program using different string functions.
O
2. Create a Python program using different list method.
ty
1 a
2 c
3 d
si
4 b
5 c
6 a r
ve
7 a
8 b
9 a
ni
10 b
e
Learning Objectives:
in
At the end of this module, you will be able to understand:
nl
●● Accessing and Manipulating Files on the Disk
●● Accessing and Manipulating Directories on the Disk
O
●● Format Operator, Command Line Arguments
●● Filenames and Paths
●● Errors and Exceptions
ty
●● Raising and Handling Exceptions
●● Try and Finally Statement
si
●● With Statement
●● Catching Exceptions
●● Working with Database
●● Concept of Pickling and Unpickling
r
ve
●● Code Snippet Implementing the Concept of Pickling and Unpickling
●● Pipes
ni
Introduction
Python, like many other programming languages, offers file management and
allows users to read and write files, as well as perform a variety of other file-related
U
tasks. The concept of file handling has been extended to a variety of other languages,
but the implementation is either complicated or lengthy. However, like most Python
principles, this concept is simple and straightforward.
ity
Python includes a number of built-in exceptions that allow our application to execute
uninterrupted and produce the desired results. The following are the exceptions:
Common Exceptions
m
Although Python has a large variety of built-in exceptions, we will just cover the
most frequent standard exceptions here. The following is a list of common exceptions
that can be thrown by a basic Python programme.
)A
●● EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
Although Python has a more basic serialisation package known as marshal, pickle
Notes
e
should always be used to serialise Python objects. The primary purpose of marshal is to
support Python’s.pyc files.
in
The pickle module is distinct from marshal in numerous ways:
The pickle module keeps track of the objects it’s already serialised so that further
references to the same item aren’t serialised. This is something that the marshal does not do.
nl
This has ramifications for both recursive and shared items. Objects that contain
references to themselves are known as recursive objects. Recursive objects are not
handled by marshal, and attempting to marshal them will cause your Python interpreter
O
to fail. When there are several references to the same object in different points in the
serialised object hierarchy, object sharing occurs. Pickle only keeps a single copy of
such items and makes sure that all other references go to it. Shared objects are always
ty
shared, which is crucial for mutable objects.
si
importable and saved in the same module as the object.
It is not assured that the marshal serialisation format will work across Python
versions. The Python implementers reserve the right to change the serialisation format
r
in non-backwards compatible ways if the need arises, because their primary goal is
ve
to support.pyc files. If a compatible pickle protocol is used and pickling and unpickling
code handles with Python 2 to Python 3 type differences if your data crosses the
specific breaking change language border, the pickle serialisation format is guaranteed
to be backwards compatible across Python releases.
ni
which is crucial. Each line of code consists of a series of characters that together
constitute a text file. A specific character called the EOL or End of Line character, such
as the comma, or newline character, is used to end each line in a file. It signals to the
interpreter that the current line has ended and that a new one has begun. Let’s start
ity
5.1.1 Text Files and Their Formats, Reading and Writing Files
m
The term “file” is used as a catch-all in everyday life. It’s used to define things
that aren’t only written, but also items that don’t contain any words at all, such as
photographs. All programmes and data are “written” into and “read” from a file, which is
the most common storage unit in a computer.
)A
The letter or set of characters after the period that makes up a full file name is
known as a file extension, also known as a file suffix or a filename extension. Your
computer’s operating system, such as Windows, uses the file extension to decide which
programme will be associated with the file.
(c
Consider the file assignments for example. docx is a file extension that is
connected with your computer’s Microsoft Word. When you try to open this file,
Windows notices that it has a docx extension and recognises that it should be opened
Notes
e
using Microsoft Word.
File extensions frequently, but not always, reflect the file type or format of the file.
in
The extensions of any file can be renamed, but this will not convert the file to another
format or change anything about it but this component of its name.
The terms “file extensions” and “file formats” are frequently used interchangeably. The
nl
file extension, on the other hand, is whatever letters come after the period, but the file format
describes how the data in the file is organised and what type of file it is. The file extension csv
for example, indicates that the file name pop.csv is a CSV file. You might easily change the file
O
to pop.mp3, but that does not guarantee that it will play on a smartphone.
The file is still a CSV file with rows of text, not a compressed musical recording
(an MP3 file). Some file extensions are classed as executable, which means that when
ty
you click on them, they don’t only open for viewing or playing, but instead perform
something on their own, such as install a programme, start a process, or run a script.
All of the information on your hard disc is organised into files and folders. The
si
primary distinction between the two is that files contain data, whereas directories
contain files and other directories. Folders, often known as directories, are used to
manage your computer’s contents. On the hard drive, the directories themselves take
r
up almost minimal space. On the other hand, files can be anything from a few bytes to
many terabytes in size. On your computer, directories are used to arrange files.
ve
File Types
Text files and binary files are both supported by Python. Although these two file
types appear to be identical on the surface, they encode data differently. While both
ni
binary and text files store data in a series of bits (binary values of 1s and 0s), the bits
in text files represent characters, whereas the bits in binary files represent special data.
U
Supporting programmes can interpret this data, but it will appear as jumbled text in a text
editor. A.JPG picture file opened in an image viewer and a text editor are shown below.
m
)A
(c
The image reader, as you can see, detects the binary data and shows the image.
Notes
e
The binary data is transformed to unrecognisable text when the image is opened in a
text editor. You may note, though, that part of the writing is readable. This is due to
the JPG format’s inclusion of short textual data storage sections. Despite the fact that
in
the text editor was not meant to read this file format, it still displays the text when it is
opened. Many other binary file types also have readable text parts.
nl
As a result, by opening an unknown binary file type in a text editor, you may
be able to learn more about it. Headers, which are bytes of data at the beginning of
a file that identify the file’s contents, are commonly seen in binary files. The file type
and additional descriptive information are frequently included in headers. A software
O
programme may refuse to open a file if the header information is incorrect, or it may
report the file as corrupted.
Because text files may only hold textual data, they are more limited than binary
ty
files. They are, nevertheless, less prone to become corrupted than binary files. A little
fault in a binary file may render it unreadable, yet a small error in a text file may just
appear once it is opened. A typical plain text file has numerous lines of text, each of
si
which is terminated by an EOL character.
After the final character, an End-of-File (EOF) marker is put, signalling the file’s
end. A character encoding system influences how characters are interpreted and what
r
characters can be shown in text files. Many programmes are capable of reading and
ve
altering text files because they employ a basic, standard format. Microsoft Notepad and
WordPad, which come bundled with Windows, and Apple TextEdit, which comes with
Mac OS X, are two common text editors.
The file extension usually tells us whether a file is binary or text. This is because
ni
the extension, by convention, represents the file format, and the file format ultimately
determines whether the file data is binary or text.
e
Any output generated during the execution of the programme is lost when the
programme stops in all of the programmes you’ve run so far. Data was not saved
in
once the execution was completed. You can write and retrieve data files in Python that
endure after your programme has completed running, just like programmes do. Open a
file, read from a file, write to a file, and close a file are all built-in functions in Python.
nl
Creating and Opening Text Files
If you can’t get to the information in a file, it’s not very useful. Before utilising the
O
Python’s built-in open() function to read or write to a file, it must first be opened. When
the open() function is used to open a file, it returns a file object called a file handler, which
contains methods for accessing the file. The open() function’s syntax is listed below.
ty
si
For the file name, the open() function produces a file handler object. The open()
method typically takes two parameters, the first of which is a string providing the file
r
name to open, which can be absolute or relative to the current working directory. The
second argument is a string that contains a few characters that describe how the file will
ve
be utilised, as given in the table below. If the mode argument is missing, r will be used
instead. The file handler will not contain any information about the file.
ni
U
ity
m
For example,
>>>file_handler = open(“example.txt”,”x”)
)A
>>>file_handler = open(“moon.txt”,”r”)
>>>file_handler = open(“C:\langur.txt”,”r”)
>>>file_handler = open(“C:\prog\example.txt”,”r”)
>>>file_handler = open(“C:\\fauna\\bison.txt”,”r”)
(c
>>>file_handler = open(“C:\\network\computer.txt”,”r”)
>>>file_handler = open(r”C:\network\computer.txt”,”r”)
Amity Directorate of Distance & Online Education
208 Python Programming
e
directory: ‘titanic.txt’
in
>>>file_handler = open(“titanic.txt”,”w+”)
>>>file_handler = open(“titanic.txt”,”a+”)
The file handler object returned by the open() method can be used to read or edit
nl
the file. The name of the file and the kind of action you wish to perform on it are passed
to the open() function as two parameters. The mode in is “x.” If the file example.txt does
not exist, it is generated. The operation fails if the file already exists. In read mode, the
O
text file moon.txt in the current directory is opened. The absolute path is specified in
and the text langur.txt in the root directory C: is opened in read-only mode.
The text file example.txt can be located in the prog subfolder of the C: root
ty
directory and is read-only. In the absolute path, there are two backslashes. When the
identical expression is run with only a single slash, an error occurs.
r si
ve
The characters f and b in the path will be regarded as escape sequences by the
Python interpreter, not as part of the directory or text name.
As a result, you must notify Python that you truly want two characters of f and b
instead of Formfeed and Backspace, which you do by escaping the backslash with
U
another one. You must insert another backslash in to overcome the problem of the
characters n being interpreted as an escape sequence in the path.
The r character can also be used to prefix the absolute path. If that’s the case,
ity
there’s no need to use double backslashes in the path to get around the escape
sequence issue.
The r indicates that the absolute path string should be handled as a raw string,
ignoring all escape sequences. For example, ‘n’ is a new line character, but r’n’ is the
m
sequence of characters after n. If a file is not present when the software opens it for
reading, it will crash with a “no such file or directory” error. For reading and writing, the
file is opened in w+ mode.
)A
If the file titanic.txt does not already exist, it is generated. For reading, writing, and
adding, the file is opened in a+ mode. If the file already exists, the data or content is
attached to it. If the file does not already exist, it is created.
Opening files uses up system resources, and other programmes may be unable to
access them depending on the file mode. It’s critical to save the file after the processing
is finished. You can’t read or write to the file after the file handler object is closed. If you
Notes
e
try to utilise the file handler object after it has been closed, you will get an error. The
close() function has the following syntax:
in
file_handler.close()
nl
O
Close the file by calling file handler.close(). This immediately releases any system
resources that it was using. If you don’t explicitly close a file, Python’s garbage collector
will destroy the object and close the open file for you, but the file may have been open
for a long time. Another danger is that cleanup will occur at various times in different
ty
Python implementations.
The code departs without closing the file if an exception occurs while performing
some operation on it. To solve this problem, you should handle exceptions with a try-
si
exceptfinally block. As an example,
r
ve
ni
The finally block should not be used to write to the file since any exceptions
U
produced there will not be captured by the except block. If the try block – raises an
exception, the except block is executed. Regardless matter what happens, the finally
block is always executed. The finally block will not be skipped if the return statement is
ity
used in the unless block. The finally block, by its very nature, cannot be skipped; this
is why you should place your “clean-up” code (i.e., shutting files) in there –. So, even if
there is an exception -, the above code will ensure that your file is closed properly..
When the open() function in Python is used, it returns a file object known as a file
handler. You may get information about many file properties using this file handler:
)A
(c
Notes
e
in
nl
O
File Methods to Read and Write Data
When you call the open() function, it creates a file object. The following is a list of
ty
the methods that can be used on this object.
r si
ve
ni
U
ity
display the results. However, that output is only available while the application is
running, and input must be entered using the keyboard. This is due to the fact that
the variables used in a programme have a lifetime that lasts until the programme is
)A
executed. What if we wanted to save the data that was entered as well as the
generated output indefinitely so that we could utilise it again later? Typically, businesses
would wish to save information on employees, inventory, sales, and other items
indefinitely to prevent having to enter the same information over and over again. As a
result, data is permanently preserved on secondary storage devices for reusability. With
(c
a.py extension, we store Python applications written in script mode. Each software is
saved as a file on the secondary device. Similarly, the data entered and the result can
be saved to a file indefinitely.
Amity Directorate of Distance & Online Education
Python Programming 211
e
file or files and documents on a computer. Despite the fact that everyone understands
what a file is, we provide a formal definition anyway:
in
A file, often known as a computer file, is a collection of logically related data or
information that computer programmes may access. A file is often stored on a permanent
storage medium, such as a hard drive disc. Human users, as well as programmes and
nl
scripts, use a unique name and path to access a file for reading and modification.
O
Computer programmes in real-world applications deal with data from various
sources such as databases, CSV files, HTML, XML, JSON, and so on. In general, we
access files to write or read data from them. However, file operations include opening
and closing files, writing data to files, traversing files, reading data from files, and so on.
ty
The io module in Python offers many functions for dealing with files.
Opening a file
si
To open a file in Python, we use the open() function. The syntax of open() is as follows:
r
This function returns a file handle object, which is saved in the file object variable.
By invoking the functions defined in Python’s io module, we may use this variable to
ve
move data to and from the file (read and write). If the file does not already exist, the
above command creates a new empty file with the name specified in the statement.
Certain characteristics of the file object provide basic information about the file,
ni
such as:
The access mode parameter is an optional argument that specifies how the
programme should access the file. It’s also known as the processing mode. The
operation for which the file must be opened, such as r> for reading, w> for writing, +>
for both reading and writing, and a> for adding to the end of an existing file, is referred
m
to as mode. The read mode is the default. We can also specify whether the file should
be processed in binary (b>) or text mode. By default, files are opened in text mode,
which allows you to read and write strings. Non-text files are opened in binary mode,
)A
When a file is opened in a specific mode, the file offset position in the table refers
to the position of the file object.
(c
e
File Mode Description File Offset position
<r> Opens the file in read-only mode Beginning of the file
in
<rb> Opens the file in binary and read-only mode Beginning of the file
<r+> or <+r> Opens the file in both read and write mode Beginning of the file
nl
<w> Opens the file in write mode. If the file already Beginning of the file
exists, all the contents will be overwritten. If the
file doesn’t exist, then a new file will be created.
O
<wb+> or Opens the file in read, write and binary mode. Beginning of the file
<+wb> If the file already exists, the contents will be
overwritten. If the file doesn’t exist, then a new
file will be created.
ty
<a> Opens the file in append mode. If the file doesn’t End of the file
exist, then a new file will be created.
<a+> or <+a> Opens the file in append and read mode. If the file End of the file
si
doesn’t exist, then it will create a new file.
r
myObject=open(“myfile.txt”, “a+”)
ve
The file myfile.txt is opened in append and read modes in the preceding sentence.
At the conclusion of the file, there will be a file object. That means we may use the file
object named myObject to write data at the end of the file and read data from it at the
same time.
ni
Closing a file
It is a good habit to shut a file once we have completed the read/write operations
U
on it. To do so, Python provides the close() method. The system frees the RAM
assigned to a file when it is closed. close() has the following syntax:
file_object.close()
ity
The object returned while opening the file is file object in this case.
Before the file is closed, Python ensures that any unwritten or unsaved data
is flushed off (written) to it. As a result, whenever our job is through, we should
always close the file. The previous file is also automatically closed if the file object is
m
In Python, we can also open a file using with clause. The syntax of with clause is:
The benefit of employing the with clause is that any file opened with this clause is
(c
automatically closed once the control leaves the with clause. The file is automatically
closed if the user forgets to explicitly close it or if an exception occurs. It also has a
more straightforward syntax.
e
content = myObject.read()
We don’t need to use the close() statement to explicitly close the file in this case.
in
The file will be automatically closed by Python.
nl
The functions we’ve learned so far are used to access data from a file in a
sequential order. However, if we wish to retrieve data in a random order, we can use
Python’s seek() and tell() functions.
O
The tell() method
This function returns a number indicating the file object’s current location in the file.
ty
The byte position from the beginning of the file to the present position of the file object
is supplied in this way. The syntax for using tell() is as follows:
file_object.tell()
si
The seek() method
This method is used to position the file object at a particular position in a file. The
syntax of seek() is: r
ve
file_object.seek(offset [, reference_point])
The offset in the above syntax refers to the number of bytes that the file object will
be relocated by. The starting position of the file object is indicated by reference point.
That is, the offset must be counted in relation to which position. Any of the following
ni
2 - end of file
The value of reference point is 0 by default, which means the offset is calculated
ity
from the beginning of the file. The statement fileObject.seek(5,0) for example, will place
the file object at the 5th byte position from the file’s start.
print(str)
print(“Initially, the position of the file object is: “,fileobject.
tell())
(c
fileobject.seek(0)
print(“Now the file object is at the beginning of the file:
“,fileobject.tell())
Notes
e
fileobject.seek(5)
print(“We are moving to 10th byte position from the beginning of
in
file”)
print(“The position of the file object is at”, fileobject.tell())
nl
str=fileobject.read()
print(str)
O
Output of Program
>>>
RESTART: Path_to_file\Program2-2.py
ty
Learning to move the file object
roll_numbers = [1, 2, 3, 4, 5, 6]
Initially, the position of the file object is: 33
si
Now the file object is at the beginning of the file: 0
We are moving to 10th byte position from the beginning of file
r
The position of the file object is at 10
ve
numbers = [1, 2, 3, 4, 5, 6]
>>>
Let us now do some fundamental operations on a text file, having learned several
methods that allow us open and shut a file, read and write data in a text file, discover
the position of the file object, and move the file object to a desired location. Let’s
U
We use the open() method to create a text file, passing in the filename and mode.
If a file with the same name already exists, the open() function will behave differently
depending on the mode selected (write or add). If it is set to write mode (w), all of the
contents of the file will be erased, and a new file with the same name will be created.
The new data will be written after the current data if the file is created in append mode
m
(a). If the file does not exist in either case, a new empty file will be created. In Program
below, a file named practice.txt is opened in write (w) mode and three sentences are
written to it, as seen in the output screen.
)A
while True:
data= input(“Enter data to save in the text file: “)
fileobject.write(data)
Notes
e
ans=input(“Do you wish to enter more data?(y/n): “)
if ans==’n’: break
in
fileobject.close()
Output of Program
nl
>>>
RESTART: Path_to_file\Program2-3.py
O
Enter data to save in the text file: I am interested to learn about
Computer Science
Do you wish to enter more data?(y/n): y
ty
Enter data to save in the text file: Python is easy to learn
Do you wish to enter more data?(y/n): n
>>>
si
Traversing a file and displaying data
We’ll use the previous example, where we created the file practice.txt, to read
r
and show data saved in a text file. The file will be opened in read mode, with reading
ve
beginning at the beginning.
str = fileobject.readline()
while str:
U
print(str)
str=fileobject.readline()
fileobject.close()
ity
The readline() function is used in the while loop to read data from the text file line
by line. The lines are shown using the print command (). When the readline() function
reaches the end of the file, it returns an empty string. Finally, using the close command,
the file is closed ().
m
Output of Program
>>>
)A
module but accessing file system functionality (such as handling directories) must.
The os module must first be loaded. os is a Python module that is part of the Python
ecosystem’s core. It’s done with an import statement like this:
import os
Notes
e
Most of the methods we’ll require throughout this essay are in the os module.
However, as you’ll see later, the tempfile module is required if you want to do something
in
more complicated, such as create a temporary file for storing data.
nl
Detecting the current working directory using the getcwd method is an example of
directory operations (). This method returns a string containing your working directory’s path.
O
import os
# detect the current working directory and print it
path = os.getcwd()
ty
print (“The current working directory is %s” % path)
si
$ python3 cwd.py
/home/frank/ is the current working directory.
r
Additionally, the os module includes the getcwdb() method. This method is similar
ve
to getcwd(), but instead returns the path as a binary string.
Creating a Directory
The mkdir() method is used to create a single directory. Mkdir() requires the path
ni
name for the directory as an input before it can be created. Consider the following code
as an example:
import os
U
try:
os.mkdir(path)
except OSError:
print (“Creation of the directory %s failed” % path)
m
else:
print (“Successfully created the directory %s “ % path)
)A
Keep in mind that the mkdir() method can only construct one level of subdirectories
in a single call. You must call mkdir() once each directory level to generate an entire
path. Make use of the makedirs() method instead if you wish to create numerous
directories at once.
(c
Within the mkdir() call, you can define the directory’s access restrictions as an
optional parameter. The default setting is 777, which indicates that the owner, group
members, and all other users can read and write to it. If you need a more restrictive
setting, such as 755, (visible and accessible by all users, but only the owner has write
Notes
e
access), you can call it:
import os
in
# define the name of the directory to be created
path = “/tmp/year”
nl
# define the access rights
access_rights = 0o755
try:
O
os.mkdir(path, access_rights)
except OSError:
print (“Creation of the directory %s failed” % path)
ty
else:
print (“Successfully created the directory %s” % path)
si
One thing to keep in mind about this code: the access permissions (755 in this
case) are supplied with the octal prefix (0o), which eliminates the need to convert the
number to decimal beforehand. Because the access permissions are represented as
octal by the OS, we’ll do the same here. r
ve
Creating a Directory with Subdirectories
As previously stated, the mkdir() technique only allows us to create a single
directory. The makedirs() method is used to build multi-level subdirectories. Actually,
ni
makedirs() is written in such a way that it uses mkdir() to create each new directory.
import os
# define the name of the directory to be created
path = “/tmp/year/month/week/day”
ity
try:
os.makedirs(path)
except OSError:
m
have a temporary directory for a variety of purposes, such as temporarily parking data.
The tempfile module has techniques for dealing with such situations in a secure and
consistent manner.
e
in this example. Because both the directory and its contents were completely erased
after the with line, the temporary directory no longer exists.
in
import tempfile
# create a temporary directory
with tempfile.TemporaryDirectory() as directory:
nl
print(‘The created temporary directory is %s’ % directory)
# directory and its contents have been removed by this point
O
the Python script’s output from Listing 5 On UNIX/Linux systems, the three
directories /tmp, /var/tmp, and /usr/tmp are checked for temporary files, and the first
match is used. In this instance, the /tmp directory is being used.
ty
$ python3 mkdir-temporary.py
The created temporary directory is /tmp/tmpf6o0hy3c
si
Deleting a Directory
The opposite of creating a directory is deleting it. You can do this with the os
module’s rmdir() method. rmdir() takes a path string including the directory name and
r
only deletes the path string’s deepest entry. It’s worth noting that this only works if the
ve
directory is completely empty. An OSError is raised if it is not empty.
import os
path = “/tmp/year”
try:
U
os.rmdir(path)
except OSError:
else:
to remove an entire directory tree the rmtree() method from the shutil module will
m
Format Operator
Python allows you to format text strings in a variety of ways. percent -formatting and
str.format are two examples (). Each of these strategies has advantages, but they also
have drawbacks that make them difficult to utilise in practise. The Python community is
(c
embracing a new string formatting method known as “f-strings,” which is derived from the
leading letter used to designate such strings and stands for “formatted strings.”
The f-strings provide a simple syntax for embedding expressions inside strings
Notes
e
literals. In the source code of a Python programme, a string literal is what we see,
including the quotation marks. It’s important to remember that an f-string is a run-time
expression, not a constant value. An f-string in Python source code is a literal string
in
beginning with ‘f’ that comprises expressions enclosed by curly brackets “ and “.
The desire to have an easier approach to format strings in Python led to the
nl
creation of f-strings formatting. Existing formatting methods are either error-prone, rigid,
or inconvenient. The types that percent -formatting supports are limited. Formatting is
only possible with int, str, and doubles. All other types are either ignored or transformed
to one of these before being formatted. Furthermore, when a single value is supplied,
O
there is a well-known trap. As an example,
ty
When only one value is supplied, 1-2 works fine. The identical code would fail if the
variable almanack was ever changed to a tuple. As an example,
r si
ve
Passing 1-2 Percent-formatting does not handle multiple values.
To address some of the issues with percent -formatting, the str.format() formatting
ni
was added. It also accepts multiple parameters because it uses standard function call
syntax. Str.format(), on the other hand, is not without flaws. The most notable of these
is its verbosity. The text value is repeated for example, in the following code.
U
ity
Even in its most basic form, there is considerable boilerplate, and the value entered
into the placeholder is sometimes a long way from where the placeholder is located.
m
You cannot use backslashes because they may not occur inside the expression
parts of f-strings. Backslash escapes can appear inside an f-string string’s segments. To
escape quotations inside f-strings for example:
(c
When using f-strings, backslashes are not supported within the curly brackets.
Notes
e
Inside the expression, you can use a different sort of quote:
in
Within and outside the curly braces, use a variety of quotes.
nl
Format Specifiers
Evaluated expressions can also be seen in format specifiers. The f-string
O
formatting operation has the following syntax:
ty
is a string that is made up of a series of characters. You specify the variable_ name
whose value will be shown within curly brackets. The width and precision settings can
be specified if desired. Both width and precision should be included in curly braces if
they are given.
si
Also, a colon should be used to separate variable name from either width or
precision values. The width value can be used to pad or create space around the
r
variable name value element. Strings are left-justified by default, while numbers are
right-justified. The total number of digits that will be presented in a number is referred to
ve
as precision. This contains the decimal point as well as all digits, both before and after
it. As an example,
ni
U
ity
via the console is referred to as command line arguments. To access command line
arguments, you must first import the sys module. Using sys.argv, all command line
arguments in Python can be output as a list of strings.
Notes
e
in
nl
O
Output
ty
r si
ve
You must travel to the directory where your command line argument application
is saved before you can run it. Then type python file name argument 1 argument 2
argument 3...... argument n on the command prompt. Any argument can be used in
ni
For an individual file, all operating systems use the same general naming
conventions: a base file name and an optional extension separated by a period. A
directory is simply a file with a special property indicating that it is a directory, but it
must otherwise adhere to all of the same naming requirements as a regular file. To use
m
files, you must first give a file path, which is essentially a path that tells the user or
programme where the file is located.
file name, and possibly a volume name or drive name in Windows or root in Linux,
separated by a special character (a backslash for Windows and a forward slash
for Linux), with each component being a directory name or file name, and possibly a
volume name or drive name in Windows or root in Linux. If a file name is a component
of a path, it must be the last component. The appearance of the path’s beginning, or
(c
prefix, is typically essential to the system’s perception of the path. The maximum path
length in the Windows Operating System is 260 characters, while the maximum path
length in the Linux Operating System is 4096 characters.
e
create and process valid names for files and directories in both Windows and Linux
operating systems:
in
●● To separate the base file name from the extension in the file name, use a period.
●● To separate the components of a path, use the backslash () in Windows and
the forward slash (/) in Linux. The backslash (or forward slash) is used to
nl
separate one directory name from another in a path, as well as the file name
from the path that leads to it. The characters backslash () and forward slash (/)
are reserved and cannot be used in the name of a file or directory.
O
●● Don’t make the mistake of assuming case sensitivity. In Windows, file and
directory names are not case sensitive, however in Linux, they are. For
example, on Windows, the directory names ORANGE, Orange, and orange
are the same, but under Linux, they are different.
ty
●● Volume designators (drive letters) in Windows are case-insensitive. “D:” and
“d:” refer to the same drive for example.
●● (less than), > (greater than),: (colon), “ (double quote), / (forward slash),
si
(backslash), | (vertical bar or pipe),? (question mark), and * are reserved
characters that should not be used in file and directory names (asterisk).
●● Reserved terms like CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4,
r
COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6,
ve
LPT7, LPT8, and LPT9 should not be used to name files and folders in the
Windows Operating System.
A file path can be either a fully qualified or relative path name. An Absolute path is
also known as a fully qualified path name. If a path links to a file location that always
contains the root and the complete directory list, it is said to be a fully qualified path.
U
The current directory is the one in which a user is now working. Every user works in a
directory at all times.
Note that depending on what the current directory was set to during the most
recent “change directory” action on that drive, it may or may not be the root directory.
ity
The root directory, sometimes known as root, is the “highest” directory in the directory
structure. It can also be thought of as the start or start of a directory hierarchy in
general. All other directories on the drive are contained in the root directory, which can
likewise contain files. For example, on a Windows system, the root directory of the
m
primary partition is C:, while on a Linux system, the root directory is /. (forward slash).
components in a path, it is said to be a relative path. The directory above the current
directory, often known as the “parent directory,” is indicated by these two consecutive
periods. To denote the current directory, use a single period as a directory component in
Notes
e
a route.
in
●● “..\langur.txt” specifies a file named “langur.txt” located in the parent of the
current directory fauna.
●● “.\bison.txt” specifies a file named “bison.txt” located in a current directory
nl
named fauna.
●● “..\..\langur.txt” specifies a file that is two directories above the current
directory india
O
5.2 Exception Handling
A program’s exception can be characterised as an unexpected condition that
ty
causes the program’s flow to be disrupted.
When an exception occurs, the program’s execution is halted, and the remaining
code is not executed. As a result, run-time failures that are unable to manage the Python
si
script are an exception. A Python object that describes an error is called an exception.
Python provides a mechanism for handling exceptions so that the code can
r
continue to run uninterrupted. The interpreter does not execute all of the code that
exists after the exception if we do not manage it.
ve
5.2.1 Errors and Exceptions
When running a Python programme, it is possible that it will either not run at all
ni
or will run but produce unexpected output or act erratically. When there are syntax
problems, runtime faults, or logical errors in the code, these errors occur. Exceptions
are errors that occur automatically in Python. Exceptions, on the other hand, can be
U
When writing a programme, syntax mistakes are identified when we do not follow
the rules of the programming language. Parsing mistakes are another name for these
errors. When a syntax error occurs, the interpreter refuses to run the programme until
ity
the errors are corrected, saved, and repeated. When Python encounters a syntax
problem when working in shell mode, it shows the error’s name as well as a brief
description.
Example:
m
Output:
Notes
e
File “/home/ac35380186f4ca7978956ff46697139b.py”, line 4
if(amount>2999
in
^
SyntaxError: invalid syntax
nl
The parser repeats the offending line and shows a small ‘arrow’ pointing to the
line’s earliest point where the error was found. The error is created (or at least detected)
by the token preceding the arrow: in this case, the error is identified at the function
O
print() because a colon (‘:’) is absent before it. If the input came via a script, the file
name and line number are given so you know where to look.
Exceptions
ty
Even though a statement or expression is syntactically accurate, it is possible that
an error will occur during execution. For instance, opening a file that does not exist,
dividing by zero, and so on. Exceptions are errors that may cause the program’s usual
si
execution to be disrupted.
Example:
ni
Output:
m
to divide a number by 0.
if(a<3):
print(“gfg”)
(c
Output:
Notes
e
in
nl
The error message’s last line explains what went wrong. The types of exceptions
are printed as part of the message: in the example, the types are ZeroDivisionError,
NameError, and TypeError. The name of the built-in exception that occurred is shown
as the exception type. This is true for all built-in exceptions, but not all user-defined
O
exceptions must be true (although it is a useful convention). Built-in identifiers are
standard exception names (not reserved keywords).
The rest of the line delves into the specifics of the exception and what triggered it.
ty
In the form of a stack traceback, the preceding part of the error message shows the
context in which the exception occurred. It has a stack traceback that lists source lines
in general; however, it does not show lines read from standard input.
si
Built-in Exceptions
In Python, all exceptions must be instances of a BaseException-derived class.
r
The except clause in a try statement that mentions a specific class also handles any
ve
exception classes inherited from that class (but not exception classes from which
it is derived). Even if they have the same name, two exception classes that are not
connected via subclassing are never equal.
The interpreter or built-in functions can generate the built-in exceptions described
ni
below. They have a “associated value” giving the exact source of the error, unless
otherwise stated. This could be a string or a tuple comprising multiple items of data
(e.g., an error code and a string explaining the code). The associated value is normally
U
supplied as an argument to the function Object() { [native code] } of the exception class.
Built-in exceptions can be triggered by user code. This can be used to test an
exception handler or to report an error condition that is “equivalent” to when the
ity
interpreter raises the same exception; however, be aware that user code can raise an
improper error.
Exception Description
IndexError When the wrong index of a list is retrieved.
AssertionError It occurs when the assert statement fails.
AttributeError It occurs when an attribute assignment is failed.
(c
e
MemoryError It occurs when a program runs out of memory.
TypeError It occurs when a function and operation are applied in an incorrect type.
in
5.2.2. Raising and Handling Exceptions
nl
Until now, we’ve relied on Python to raise exceptions for us by making mistakes (on
purpose! ), but our scripts can also raise exceptions—that is, exceptions can be raised
by Python or by your programme, and they can be caught or not. Simply run a raise
O
statement to manually trigger an exception. User-initiated exceptions are handled in the
same way as Python-initiated exceptions are. The following Python code isn’t the most
useful ever written, but it gets the job done—it raises the built-in IndexError exception:
ty
si
User-triggered exceptions are propagated up to the toplevel default exception handler
r
if they aren’t handled, and the application is terminated with a standard error message:
ve
ni
User-Defined Exceptions
The previous section’s raise statement raises a built-in exception specified in
Python’s built-in scope. You can also define new exceptions that are exclusive to your
U
programmes, as you’ll see later in this section of the book. User-defined exceptions are
created using classes that inherit from a built-in exception class, commonly the Exception:
class.
ity
m
)A
Scripts can use class-based exceptions to create exception categories that can
inherit behaviour and have state information and methods attached. They can also
(c
change the text of the error message that appears if they aren’t caught:
Notes
e
in
nl
An exception is an error that occurs while a programme is being executed. Non-
programmers see exceptions as examples that do not follow a general rule. In computer
O
science, the term “exception” has the same meaning: It suggests that the problem
(the exception) is a “exception to the norm.” Exception handling is a construct in
several programming languages that allows you to automatically handle or deal with
errors. Exception handling is built-in to many programming languages, including C++,
ty
Objective-C, PHP, Java, Ruby, Python, and many others.
Errors are often handled by preserving the state of execution at the time the error
occurred and stopping the program’s normal flow to run a specific function or piece
si
of code known as the exception handler. The error handler can “correct” the problem
depending on the type of error (“division by zero,” “file open error,” and so on) that
occurred, and the programme can then be continued using the previously saved data.
r
ve
ni
U
ity
m
)A
To avoid taking the square root of a negative value and creating an error at
runtime, the quadratic programme above use decision structures. Using decisions to
defend against infrequent but likely errors is a typical trend in many programmes.
(c
We validated the data before calling the sqrt function in the instance of the
quadratic solver. When a function checks for potential errors, it may return a special
value to indicate that the operation failed. A other square root operation for example, might
Notes
e
yield a negative integer (for example, -1) to signal an error. This value could be used to
indicate an error because the square root function should always return the non-negative
root. The programme would evaluate the operation’s outcome and make a decision:
in
nl
O
Occasionally, programmes become so cluttered with decisions to check for
exceptional instances that the main mechanism for dealing with common cases
appears to be lost. Designers of programming languages have devised ways for
handling exceptions that aid in the resolution of this design issue. The idea behind
ty
an exception-handling system is that the programmer can write code that detects
and handles mistakes that occur during the execution of the programme. Rather than
confirming that each step of the algorithm was successful, an exception-handling
programme can essentially say, “Do these steps, and if any problems arise, handle
si
them this manner.”
Exception handling in Python is accomplished via a unique control structure that resembles
r
a decision. Let’s start with a specific example before moving on to the overall strategy.
ve
Here’s a version of the quadratic programme that makes advantage of Python’s
exception system to catch any potential arithmetic problems. sqrt (square root):
ni
U
ity
m
)A
It’s worth noting that this is essentially the initial version of the quadratic
programme with the inclusion of a try... except in the program’s heart. The general form
of a try statement is:
(c
Python tries to execute the statements inside the body when it meets a try
Notes
e
statement. After the try... except, control goes to the following statement if these
statements run without errors. Python looks for an except clause with a matching error
type if an error occurs somewhere in the body. The handler code is performed if an
in
appropriate except is found.
The following error was caused by the original programme, which did not handle
nl
exceptions:
O
ty
The error message’s last line identifies the sort of error that occurred, namely a
ValueError. The programme has been changed to include an except clause that will
capture the ValueError. This is how it appears in action:
si
The real solutions to a quadratic are found with this programme:
r
ve
Rather than crashing, the exception handler captures the problem and prints a
message stating that the equation has no true roots.
ni
Our new application, interestingly, also detects mistakes caused by the user
entering erroneous input values. Let’s rerun the programme with “x” as the first input
this time. This is how it appears:
U
Enter coefficient a: x
ity
No real roots
Do you see what’s going on here? When calling float (“x”), Python returned a
ValueError because “x” is not a float. As a result, the programme exited the try clause
and went straight to the except clause for that error. Of course, the final message
m
appears to be odd. Here’s a final version of the programme that determines what type
of error occurred:
# quadratic6.py
)A
import math
def main():
print(“This program finds the real solutions to a quadratic\n”)
try:
(c
e
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
in
print(“\nThe solutions are:”, root1, root2 )
except ValueError as excObj:
if str(excObj) == “math domain error”:
nl
print(“Invalid coefficient given”)
except:
print(“\nSomething went wrong, sorry!”)
O
main()
El ifs are similar to multiple excepts. If an error occurs, Python will check every
option except tum to find one that matches the error type. In this example, the bare
ty
except at the bottom functions as an else and is used as the default if no prior except
error type matches. The application crashes and Python reports the problem if there is
no default at the bottom and none of the except types match the error.
si
Exceptions are objects in their own right. If you use an as in an except clause after
the error type, Python will assign the actual exception object to that variable. In this
case, I converted the exception to a string and examined the message to determine the
r
reason of the ValueError. Notice that if the error is not caught (e.g., ValueError: math d
ve
oma in error), Python prints the following text. This software simply prints an apology
if the exception isn’t a ValueError. As a challenge, see if you can identify an incorrect
input that results in the apology.
You can see how the try...except statement helps us to design programmes that
ni
are bulletproof. Observe the error messages that Python prints and create except
clauses to catch and manage them using the same manner. The type of application
you’re building will determine whether you need to go to this much difficulty. You
U
might not be concerned about improper input in your early programmes; nonetheless,
professional-quality software should do everything possible to protect users from
unexpected outcomes.
ity
out” of the try statement if a finally clause is included in the try statement. It takes the
following general form:
)A
Python starts by running the statement block associated with the try header line as
(c
usual in this variant. Whether or not an exception occurs during the try block determines
what happens next:
●● If no exception occurs while the try block is active, Python moves on to the
Notes
e
finally block and then to the next statement after the try statement.
●● If an exception occurs while the try block is being executed, Python returns
in
and executes the finally block, but the exception is propagated up to a
previously entered try or the top-level default handler; the programme does
not resume execution below the finally clause’s try statement. That is, even
if an exception is raised, the finally block is executed, but unlike an except,
nl
the finally does not terminate the exception; it continues to be raised after the
finally block is completed.
When you want to be absolutely certain that an action will happen after some code
O
executes, regardless of the program’s exception behaviour, the try/finally form is useful.
In fact, it lets you specify cleanup activities that must be performed on a regular basis,
such as file closures and server disconnects as necessary.
ty
In Python 2.4 and earlier, the finally clause cannot be combined with the except
and otherwise clauses in the same try statement, hence the try/finally is better thought
of as a separate statement type. Finally can appear in the same statement as except
si
and else in Python 2.5 and later, therefore there is now only one try statement with
numerous optional clauses (more about this shortly). Regardless of the version you
use, the finally clause has the same goal: to describe “cleanup” activities that must
always be performed, regardless of any exceptions.
r
ve
Example: Using try/finally to code termination actions
The control flow hops back and runs the finally block to close the file when the
m
reached. If the function did not throw an exception, the programme would still terminate
the file with the finally block, but it would continue below the try statement.
contents of the file’s output buffer have been flushed from memory to disc. A code
structure similar to this can ensure that server connections are closed, and so on.
In standard Python (CPython), file objects are automatically closed when trash
Notes
e
collection occurs; this is especially beneficial for temporary files that aren’t assigned to
variables. However, it’s not always straightforward to estimate when garbage collection
will take place, particularly in larger systems or Python implementations with different
in
garbage collection policies (e.g., Jython, PyPy). The try statement specifies a specified
block of code and makes file closures more explicit and predictable. Regardless of
whether an exception happens or not, it ensures that the file is closed on block exit.
nl
Although the function in this example isn’t really useful (it simply raises an
exception), encapsulating calls in try/finally statements is an excellent method to ensure
that your closing-time termination operations always execute. Whether or not an error
O
occurs in the try block, Python always executes the code in your finally blocks.
Unified try/except/finally
ty
Prior to Python 2.5 (roughly 15 years ago), the try statement came in two flavours
and was actually two separate statements: we could use a finally to ensure that cleanup
code was always run, or we could write except blocks to catch and recover from specific
si
exceptions and optionally specify an else clause to be run if no exceptions occurred.
That is, the finally clause could not be used in conjunction with the except and
else clauses. This was partially due to implementation challenges, and partly due to
r
the ambiguous idea of combining the two—catching and recovering from exceptions
ve
seemed to be a separate concept from performing cleanup activities.
However, in Python 2.5 and later, the two statements have been combined.
Because of the Java language’s equivalent utility, we may now blend finally, except, and
else clauses in the same expression. That is, we may now write the following statement:
ni
U
ity
As is customary, the code in the main-action block of this statement is run first. If
m
that code throws an exception, all of the except blocks are examined one by one for
a match to the exception. If the raised exception is Exception1, the handler1 block is
executed; if it is Exception2, the handler2 block is invoked, and so on. The else-block is
)A
The finally-block is executed once the main action block is complete and all raised
exceptions have been handled, regardless of what has transpired earlier. In reality,
even if there is an error in an exception handler or the else-block, the code in the finally-
(c
block will be executed and a new exception will be raised, the code in the finally-block
will be executed.
The finally clause, as always, does not end the exception—if an exception is active
Notes
e
when the finally-block is executed, it will continue to propagate after the finallyblock is
completed, and control will jump to another location in the programme (to another try,
or to the default top-level handler). Control continues after the full try statement if no
in
exception is active when the finally is run.
nl
●● In the main action, an exception occurred, which was handled.
●● There was an exception in the main action that was not handled.
●● In the main action, there were no exceptions.
O
●● In one of the handlers, a new exception was thrown.
Finally, regardless of what exceptions have been raised or handled, the finally
specifies cleanup actions that must always be performed on the way out of the attempt.
ty
Unified try Statement Syntax
The try statement must have either an except or a finally when coupled in this way,
si
and the order of its elements must be as follows:
r
where else and finally are optional, and there can be zero or more excepts, but if
ve
an else appears, there must be at least one except. The try statement is actually made
up of two parts: excepts with an optional else and/or finally.
Because of these restrictions, the else can only exist if there is at least one except,
thus mixing except and finally is always conceivable, regardless of whether or not an
else appears. Finally and else can also be mixed, but only if an except appears (though
the except can omit an exception name to catch everything and run a raise statement,
described later, to reraise the current exception). Python will throw a syntax error
(c
exception before your code starts if you break any of these ordering restrictions.
e
In Python, the with statement is used to manage resources and handle exceptions.
It makes it easier to manage common resources such as file streams. Take a look at the
in
following code to see how the use of the with statement makes the code cleaner.
For example, the statement assures that if an exception is raised, the file stream
process does not block other processes and instead terminates properly.
nl
# file handling
(1) without using with statement
O
file = open(‘file_path’, ‘w’)
file.write(‘hello world !’)
file.close()
ty
(2) without using with statement
file = open(‘file_path’, ‘w’)
try:
si
file.write(‘hello world’)
finally:
r
file.close()
ve
# using with statement
with open(‘file_path’, ‘w’) as file:
ni
When utilising the with statement, unlike the first two implementations, there is no
need to call file.close(). The with statement guarantees that resources are acquired and
U
The second approach in the above example handles all exceptions, but the use
of the with statement makes the code more compact and clear. As a result, the with
statement aids in the prevention of defects and leaks by ensuring that a resource is
correctly relinquished when the code that uses it is fully performed. The with statement
m
is commonly used with file streams, as demonstrated above, as well as Locks, sockets,
subprocesses, and telnets, among other things.
There’s nothing particular about open() that makes it suitable for use with the with
statement; the same capability can be found in user-defined objects. Supporting with
statements in your objects ensures that no resource is ever left open.
You only need to add the methods __enter__() and __exit__() to the object
(c
methods to use the with statement in user defined objects. Consider the following
scenario for more information.
e
class MessageWriter(object):
def __init__(self, file_name):
in
self.file_name = file_name
def __enter__(self):
nl
self.file = open(self.file_name, ‘w’)
return self.file
def __exit__(self):
O
self.file.close()
# using with statement with MessageWriter
with MessageWriter(‘my_file.txt’) as xfile:
ty
xfile.write(‘hello world’)
The function Object() { [native code] } of MessageWriter follows the with keyword, as
si
you can see. A MessageWriter object is generated as soon as the execution enters the
context of the with statement, and Python then runs the __enter__() method. Initialize the
resource you want to use in the object with this __enter__() method. The descriptor of the
r
obtained resource should always be returned by the __enter__() method.
ve
resource descriptors
The operating system provides these handles to access the needed resources. File
is a descriptor of the file stream resource in the following code block.
ni
file = open(‘hello.txt’)
The __enter__() method in the MessageWriter example above creates and returns
a file descriptor. The file descriptor returned by the __enter__() method is referred to
U
as xfile here. Inside the block of the with statement is the block of code that uses the
acquired resource. The __exit__() method is called as soon as the code inside the with
block is executed. The __exit__() method releases all of the resources that have been
acquired. With user created objects, we utilise the with statement in this way.
ity
Context Manager is the interface of the __enter__() and __exit__() methods that
supports the with statement in user defined objects.
contextlib module, we can modify the context manager for the MessageWriter object.
@contextmanager
Notes
e
def open_file(self):
try:
in
file = open(self.file_name, ‘w’)
yield file
nl
finally:
file.close()
# usage
O
message_writer = MessageWriter(‘hello.txt’)
with message_writer.open_file() as my_file:
my_file.write(‘hello world’)
ty
Because of the yield statement in its definition, the function open file() is a
generator function in this code sample.
si
This open file() function creates a resource descriptor named file when it is called.
The caller receives this resource descriptor, which is represented here by the variable
my file. The programme control returns to the open file() method after the code inside
r
the with block has been run. The code after the yield statement is executed by the
open file() method, which resumes its execution. This section of code, which follows
ve
following the yield statement, releases the resources that have been acquired. The @
contextmanager is a decorator in this case.
However, this isn’t always what you want. Server applications for example, must
often remain operational despite internal problems. Wrap the call in a try statement to
U
When an exception is thrown while the try block is executing, Python immediately
moves to your handler—the block behind the except clause that names the exception
raised. The end result is that a nested block of code is wrapped in an error handler that
)A
We return to the Python prompt after the unless clause runs while working
interactively like this. Try statements in a more realistic programme not only catch but
also recover from exceptions:
(c
Notes
e
in
nl
O
This time, after the exception has been caught and handled, the programme resumes
execution after the full try statement that caught it—hence the “continuing” message. The
regular error notice is not displayed, and the programme proceeds normally.
ty
It’s worth noting that there’s no way to return to the function that caused the error
in Python (short of rerunning the code that reached that point all over again, of course).
Control continues after the full try that caught the exception, not after the statement that
launched it off, once you’ve caught the exception. In fact, Python clears the memory of
si
any functions that departed due to the exception, such as fetcher in our case; they can’t
be resumed. The try is where the programme restarts after catching exceptions.
5.3 Pickling
r
ve
For serialising and de-serialising a Python object structure, the Python pickle
package is utilised. Pickling an object in Python allows it to be saved on disc. Pickle
works by first “serialising” the item before writing it to file. Pickling is a Python function
ni
that converts a list, dict, or other Python object into a character stream. The assumption
is that this character stream provides all of the data required to recreate the object in
another Python function.
U
Although Python has a more basic serialisation package known as marshal, pickle
should always be used to serialise Python objects. The primary purpose of marshal is to
support Python’s.pyc files.
ity
that the database is stored on disc (or other permanent storage) and so survives the
program’s termination.
The dbm module gives you a way to create and update database files. I’ll make a
)A
If the database does not already exist, the mode ‘c’ indicates that it should be created.
Notes
e
The output is a database object that may be used like a dictionary (for most operations).
Dbm changes the database file when you create a new item:
in
>>>db[‘cleese.png’] = ‘Photo of John Cleese.’
When you access one of the items, dbm reads the file:
nl
>>>db[‘cleese.png’]
b’Photo of John Cleese.’
Because the result is a bytes object, it starts with b. In many aspects, a bytes
O
object is comparable to a string. The distinction becomes significant as you progress
through Python, but for now, we can disregard it.
If you change the value of an existing key, dbm overwrites the old value:
ty
>>>db[‘cleese.png’] = ‘Photo of John Cleese doing a silly walk.’
>>>db[‘cleese.png’]
si
b’Photo of John Cleese doing a silly walk.’
Certain dictionary methods, such as keys and items, are incompatible with
database objects. Iteration with a for loop, on the other hand, works:
Wherever possible, the DB API provides a minimal standard for working with
databases using Python structures and syntax. The following are included in this API:
U
returns strings, which must be supplied to a function like int(), which accepts a string
like ‘123’ and returns the numeric value 123. Things get a lot more challenging when
you want to save more complex data types like lists, dictionaries, or class instances.
)A
Python has a standard module called pickle that allows users to save complex
data types without having to continually write and debug code. This is a fantastic
module that can transform practically any Python object to a string representation, a
process known as pickling. Unpickling is the process of reconstructing an object from
its string representation. The string describing the item may have been saved in a file
(c
The simplest way to pickle an object x and a file object f that has been opened for
Notes
e
writing is to do the following:
pickle.dump(x, f)
in
The dump() method saves a pickled representation of object x to open file f.
If f is a file object that has been opened for reading, then simplest way to unpickle it.
nl
x =pickle.load(f)
The load() method reads a pickled object representation from the open file object f
and returns the reconstructed object hierarchy inside.
O
Pickling is the typical method for creating Python objects that may be saved and reused
by other programmes or by a future execution of the same programme; the technical word for
this is “permanent object.” Because pickle is so widely used, many Python extension writers
ty
must make sure that all data types are pickled and unpickled correctly.
For serialising and de-serialising a Python object structure, the Python pickle
package is utilised. Pickling an object in Python allows it to be saved on disc. Pickle
si
works by first “serialising” the item before writing it to file. Pickling is a Python function
that converts a list, dict, or other Python object into a character stream.
r
The assumption is that this character stream provides all of the data required to
recreate the object in another Python function.
ve
Pickling without a file
# initializing data to be stored in db
ni
db[‘Siddharth’] = Siddharth
db[‘Ravi’] = Ravi
# For storing
m
print(myEntry)
accesses to the same item aren’t serialised again. (This causes the marshal
module to crash.)
●● Pickle saves the item once and ensures that all other references link to the
Notes
e
master copy.
●● Object sharing (references to the same object in different places): This is
in
similar to self-referencing objects; pickle stores the object once and ensures
that all other references point to the master copy. Shared objects are always
shared, which is crucial for mutable objects.
nl
●● Classes and instances defined by the user: Pickle can save and restore class
instances transparently, but Marshal doesn’t support them at all. The class
definition must be able to be imported and saved in the same module as
the object.
O
Unpickling is the process of converting a byte stream back into a class object. It is
the opposite of pickling. De-serialization is another name for this procedure.
Because binary files provide byte stream, pickling and unpickling should be done
ty
with them. We’ll use the pickle module’s load() function to read a pickled object from a
binary file and return it as an object.
Example:
si
...
...
r
with open(‘employee.dat’, mode=’rb’) as f:
ve
obj = pickle.load(f)
print(‘Unpickling Done!’)
obj.disp()
ni
Example:
import pickle
)A
class Employee:
def __init__(self, name, salary, address):
self.name = name
self.salary = salary
(c
self.address = address
def disp(self):
Amity Directorate of Distance & Online Education
Python Programming 241
e
with open(‘employee.dat’, mode=’wb’) as f:
emp1 = Employee(‘Dipak’, 50000, ‘Sutrapada’)
in
pickle.dump(emp1, f)
print(‘Pickling Done!’)
nl
with open(‘employee.dat’, mode=’rb’) as f:
obj = pickle.load(f)
print(‘Unpickling Done!’)
O
obj.disp()
Output:
ty
C:UsersAdminDesktopPython_tutotial>python pickling_unpickling_python.py
Pickling Done!
Unpickling Done!
si
Name: Dipak Salary: 50000 Address: Sutrapada
Output:
Unpickling {‘cooper’: ‘sheldon’}
m
The dictionary key:value pair is saved as a Python pickle in this programme. Pickling
is done with the dump() function, which takes the dictionary name and file object as
arguments, and unpickling is done with the load() method, which takes the file object as
an argument.
(c
Another snippet:
Example:
Notes
e
Using the pickle module in Python 3, create a programme to demonstrate how to
store data efficiently. Module converts an in-memory Python object to a serialised byte
in
stream, which may be written to any file-like object as a string of bytes.
import pickle
nl
def storeData():
# initializing data to be stored in db
O
Omkar = {‘key’ : ‘Siddharth’, ‘name’ : ‘Siddharth Pathak’,
‘age’ : 21, ‘pay’ : 40000}
Jagdish = {‘key’ : ‘Ravi’, ‘name’ : ‘Ravi Pathak’,
ty
‘age’ : 50, ‘pay’ : 50000}
# database
db = {}
si
db[‘Siddharth’] = Siddharth
db[‘Ravi’] = Ravi
r
# Its important to use binary mode
ve
dbfile = open(‘examplePickle’, ‘ab’)
# source, destination
pickle.dump(db, dbfile)
ni
dbfile.close()
def loadData():
# for reading also binary mode is important
U
storeData()
loadData()
)A
Output:
Siddharthpathak-Inspiron-3542:~/Documents/Python-Programs$ python
P60_PickleModule.py
Ravi => {‘age’: 50, ‘name’: ‘Ravi Pathak’, ‘key’: ‘Ravi’, ‘pay’: 50000}
5.3.4 Pipes
Notes
e
A command-line interface, commonly known as a shell, is available on most
operating systems. Shells typically include commands for navigating the file system and
in
launching programmes. For example, in Unix, you can use cd to move directories, ls to
view the contents of a directory, and Firefox to run a web browser.
Invalid or inaccessible file names and paths, or other arguments that have the
nl
correct type but are not accepted by the operating system, all functions in the os
module throw OSError.
In Python, the os.pipe() method is used to create a pipe. A pipe is a mechanism for
O
passing data from one process to another. It only allows for one-way communication,
and the system stores the data until it is read by the receiving process.
A pipe object, which represents a running programme, can be used to launch any
ty
application that can be launched from the shell.
The Unix command ls -l for example, is used to display the contents of the current
directory in long format. os.popen1:ls can be used to start ls.
si
>>>cmd = ‘ls -l’
>>>fp = os.popen(cmd)
r
The parameter is a shell command in the form of a string. An object that functions
ve
as an open file is returned as the return value. With readline, you can read one line at a
time from the ls output, or read the entire output with read:
>>> print(stat)
The ls process’s ultimate status is represented by the return value; none indicates
that it completed successfully (with no errors).
ity
Most Unix systems for example, have a command named md5sum that reads a
file’s contents and computes a “checksum.”
This command is useful for determining whether two files have the same contents.
It’s quite rare that various contents will produce the same checksum (that is, unlikely to
m
You can execute md5sum from Python using a pipe and obtain the following result:
)A
1e0033f0ed0656636de0d75144ba32e0 book.tex
Notes
e
>>> print stat
None
in
Summary
●● The term “file” is used as a catch-all in everyday life. It’s used to define things
nl
that aren’t only written, but also items that don’t contain any words at all, such
as photographs. All programmes and data are “written” into and “read” from a file,
which is the most common storage unit in a computer.
O
●● User-defined classes and their instances cannot be serialised using marshal.
Pickle can save and restore class instances invisibly, but the class definition must
be importable and saved in the same module as the object.
ty
●● The terms “file extensions” and “file formats” are frequently used interchangeably. The
file extension, on the other hand, is whatever letters come after the period, but the file
format describes how the data in the file is organised and what type of file it is.
si
●● Text files and binary files are both supported by Python. Although these two file
types appear to be identical on the surface, they encode data differently. While
both binary and text files store data in a series of bits (binary values of 1s and 0s),
r
the bits in text files represent characters, whereas the bits in binary files represent
special data.
ve
●● A file, often known as a computer file, is a collection of logically related data or
information that computer programmes may access. A file is often stored on a
permanent storage medium, such as a hard drive disc. Human users, as well as
ni
programmes and scripts, use a unique name and path to access a file for reading
and modification.
●● To open a file in Python, we use the open() function. This function returns a file
U
handle object, which is saved in the file object variable. By invoking the functions
defined in Python’s io module, we may use this variable to move data to and from
the file (read and write).
●● The access mode parameter is an optional argument that specifies how the
ity
programme should access the file. It’s also known as the processing mode. The
operation for which the file must be opened, such as r> for reading, w> for writing,
+> for both reading and writing, and a> for adding to the end of an existing file, is
referred to as mode.
m
●● We use the open() method to create a text file, passing in the filename and
mode. If a file with the same name already exists, the open() function will behave
differently depending on the mode selected (write or add). If it is set to write mode
)A
(w), all of the contents of the file will be erased, and a new file with the same name
will be created.
●● The command line can be used to pass any number of parameters to a Python
application. The usage of command line arguments to provide input to a
programme via the console is referred to as command line arguments.
(c
●● Syntax errors or parsing errors are detected when we have not followed the rules
of the particular programming language while writing a program.
Amity Directorate of Distance & Online Education
Python Programming 245
●● When syntax error is encountered, Python displays the name of the error and a
Notes
e
small description about the error.
●● The execution of the program will start only after the syntax error is rectified.
in
●● An exception is a Python object that represents an error.
●● When an exception occurs during execution of a program and there is a built-in
exception defined for that, the error message written in that exception is displayed.
nl
The programmer then has to take appropriate action and handle it.
●● Some of the commonly occurring built-in exceptions are SyntaxError, ValueError,
O
IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError,
NameError, IndentationError, TypeError,and OverFlowerror.
●● The process of exception handling involves writing additional code to give proper
messages or instructions to the user. This prevents the program from crashing
ty
abruptly. The additional code is known as an exception handler
●● Raising an exception involves interrupting the normal flow of the program
execution and jumping to the exception handler.
si
●● The statements inside the finally block are always executed regardless of whether
an exception occurred in the try block or not.
Glossary r
ve
●● EOL: End of Line
●● EOF: End-of-File
●● Common extensions for text file formats:
ni
document. If the file does not exist, an I/O error is raised. This is also the default
mode for opening files.
●● Read and Write (‘r+’): To read and write in the file, double-click it. The handle is at
the beginning of the document. If the file does not exist, an I/O error is thrown.
m
●● Write Only (‘w’): To begin writing, open the file. The data in an existing file is
truncated and overwritten. The handle is at the beginning of the document. If the
)A
created. The file’s handle is located at the very end. After the existing data, the
data that is being written will be added at the end.
●● Append and Read (‘a+’): To read and write in the file, double-click it. If the file
Notes
e
does not exist, it is created. The file’s handle is located at the very end. After the
existing data, the data that is being written will be added at the end.
in
●● CSV: Comma-Separated Values
●● HTML: Hyper Text Markup Language
●● XML: Extensible Markup Language
nl
●● JSON: JavaScript Object Notation
O
1. How many except statements can a try-except block have?
a. zero
ty
b. one
c. more than one
d. more than zero
si
2. When will the else part of try-except-else be executed?
a. always
b. r
when an exception occurs
ve
c. when no exception occurs
d. when an exception occurs in to except block
3. Is the following Python code valid?
ni
try:
# Do something
U
except:
# Do something
finally:
ity
# Do something
e
a. when there is no exception
b. when there is an exception
in
c. only if some condition that has been specified is satisfied
d. always
nl
6. What will be the output of the following Python code?
def foo():
O
try:
return 1
finally:
ty
return 2
k = foo()
print(k)
si
a. 1
b. 2
c. 3 r
ve
d. error, there is more than one return statement in a single try-finally block
7. What will be the output of the following Python code?
try:
ni
if ‘1’ != 1:
raise “someError”
U
else:
print(“someError has not occurred”)
except “someError”:
ity
c. invalid code
d. none of the mentioned
8. What happens when ‘1’ == 1 is executed?
)A
a. we get a True
b. we get a False
c. an TypeError occurs
(c
d. a ValueError occurs
9. The _ _ _strings provide a simple syntax for embedding expressions inside strings
Notes
e
literals.
a. f
in
b. s
c. a
nl
d. t
10. _______ method is used to position the file object at a particular position in a file.
a. Seek()
O
b. Tell()
c. Open()
ty
d. Close()
11. The maximum path length in the Windows Operating System is _ _ _ _ characters.
a. 250
si
b. 260
c. 270
d. 280 r
ve
12. The maximum path length in the Linux Operating System is _ _ _ _characters.
a. 4096
b. 8192
ni
c. 1024
d. 2048
U
Exercise
1. Define text files and their formats.
2. How to access and manipulate files on the disk?
ity
e
13. Define pipes.
in
Learning Activities
1. Create a Python program implementing the concept of pickling and unpickling.
2. “Every syntax error is an exception but every exception cannot be a syntax error.”
nl
Justify the statement.
3. What is the use of a raise statement? Write a code to accept two numbers and
display the quotient. Appropriate exception should be raised if the user enters the
O
second number (denominator) as zero (0).
4. When are the following built-in exceptions raised? Give examples to support your
answers.
ty
a) ImportError
b) IOError
si
c) NameError
d) ZeroDivisionError
4 a
5 d
6 b
U
7 c
8 b
ity
9 a
10 a
11 b
m
12 a
e
5. Python Cookbook: Recipes for Mastering Python 3, Brian K. Jones and David
M. Beazley
in
6. Python for Everybody: Exploring Data Using Python 3, Charles Severance
7. Think Python: An Introduction to Software Design, Allen B. Downey
nl
8. Programming Python, Mark Lutz
9. Dive into Python, Mark Pilgrim
O
ty
r si
ve
ni
U
ity
m
)A
(c