0% found this document useful (0 votes)
194 views124 pages

Python Programming 19-06-2023

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
194 views124 pages

Python Programming 19-06-2023

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 124

Python Programming

Python Programming

Dr. Richa Malhotra


Dr. Nitika
Dr. Shipra Varshney
Ms. Varsha Gupta
Dr. Shimpy Goyal
Published by

Namya Press

India: 213, Vardan House, 7/28 Ansari Road Darya Ganj - Delhi India 110002
USA: 10685-B Hazelhurst Dr. # 31013 Houston, Texas USA - 77043
Email: namyapress@gmail.com
Website: https://namyapress.com

Edition : First Published in 2023 (Namya Press)


Title : Python Programming
Authors : Dr. Richa Malhotra, Dr. Nitika, Dr. Shipra Varshney,
Ms. Varsha Gupta and Dr. Shimpy Goyal
ISBN : 978-93-5545-216-0
Copyright : © Dr. Richa Malhotra, Dr. Nitika, Dr. Shipra Varshney,
Ms. Varsha Gupta and Dr. Shimpy Goyal
2023 All Rights Reserved

This book is being sold on the condition that it cannot be used commercially or in
any other form without the prior written permission of the publisher. This book
cannot be republished or sold or rented. And it cannot be operated among readers
in book-binding or any other form. All these conditions will also apply to the buyer
of the book. All rights of copyright are reserved in this context.

This book has been published with all efforts taken in making the material error-
free after the consent of the author. However, the author and the publisher do not
assume and hereby disclaim any liability of any part for loss, damage, or disruption
caused by error or omissions.
Preface

Matter Required
vi | Python Programming
Contents

Preface
xi
1. Python Basics 1

1.1 Entering Expressions into the Interactive Shell 2

1.2 The Integer Data Type 3

1.3 Floating-Point Data Type 4

1.4 The String Data Type 4

1.5 String Concatenation and Replication 5

1.6 Storing Values in Variables 5

1.7 First Program 6

1.8 Dissecting Your Program 6
Exercise 7
2. Flow Control 11

2.1 Boolean Values 11

2.2 Comparison Operators 14

2.3 Boolean Operators 17

2.4 Combining Boolean and Comparison Operators 19

2.5 Elements of Flow Control 21

2.6 Program Execution 22

2.7 Flow Control Statements 23

2.8 Importing Modules 27

2.9 Ending a Program Early with sys.exit() 29
Exercise 30
viii | Python Programming

3. Functions 33

3.1 def Statements with Parameters 35

3.2 Return Values and return Statements 36

3.3 Keyword Arguments and print() 37

3.4 Local and Global Scope 38

3.5 The global Statement 39

3.6 Exception Handling 40
Exercise 41
4. Lists 46

4.1 The List Data Type 46

4.2 Working with Lists 47

4.3 Augmented Assignment Operators 49

4.4 Methods 49
Exercise 53
5. Dictionaries and Structuring Data 58

5.1 The Dictionary Data Type 58

5.2 Pretty Printing 60

5.3 Using Data Structures to Model Real-World Things 61
Exercise 64
6. Strings 68

6.1 Creating Strings 68

6.2 Useful String Methods 70
Exercise 73
7. Reading and Writing Files 78

7.1 Files and File Paths 78

7.2 The os.path Module 79

7.3 The File Reading/Writing Process 80

7.4 Saving Variables with the shelve Module 83

7.5 Saving Variables with the pprint.pformat() Function 84
Exercise 86
Contents | ix

8. Organizing Files 91

8.1 The shutil Module 91

8.2 Walking a Directory Tree 93

8.3 Compressing Files with the zipfile Module 94
Exercise 95
9. Web Scraping 100

9.1 Project: MAPIT.PY with the web browser Module 100

9.2 Introduction to the Web Browser Module 101

9.3 Building MAPIT.PY 104

9.4 Running MAPIT.PY 105
Exercise 110
1
Python Basics

In the vast landscape of programming languages, Python stands


out as a versatile and powerful tool that has gained immense
popularity in recent years. With its clean syntax, ease of use,
and extensive libraries, Python has become the go-to choice for
beginners and experienced developers alike. This chapter serves
as a comprehensive introduction to the fundamental concepts and
building blocks of Python programming.
Whether you are an aspiring programmer taking your first
steps into the world of coding or an experienced developer looking
to expand your skillset, this chapter will provide you with a solid
foundation in Python. We will explore the key concepts that underpin
the language and equip you with the essential knowledge needed to
tackle a wide range of programming tasks.
We will start by understanding the basic structure of a Python
program and how to write and execute your first “Hello, World!”
program. From there, we will delve into variables, data types, and
operators, which form the backbone of any programming language.
You will learn how to manipulate and store data effectively, enabling
you to solve real-world problems with elegance and efficiency.
Throughout this chapter, we will provide practical examples,
exercises, and tips to reinforce your understanding of Python
basics. By the end, you will have a solid grasp of the language’s
2 | Python Programming

syntax, core concepts, and best practices, setting you on a path to


becoming a proficient Python programmer.
So, whether you aspire to develop web applications, dive into
data science, or automate mundane tasks, this chapter will be your
launchpad into the world of Python, where possibilities are limited
only by your imagination. Let’s embark on this exciting journey and
unlock the magic of Python programming together!

1.1 ENTERING EXPRESSIONS INTO THE INTERACTIVE SHELL


Python has an interactive shell that allows you to enter expressions
and see their results immediately. To start the interactive shell,
open a terminal window and type “python” (without the quotes).
You should see the Python prompt (>>>) appear.

1.1.1 Data Types

In Python programming, data types are used to categorize and


represent different kinds of data. Each data type has its own set
of operations and methods that can be performed on it. Python
provides several built-in data types, and you can also create your
own custom data types using classes.

1.1.2 Some of the Commonly Used Data Types in Python

Numeric Types:
•• int: Represents integer numbers, e.g., 5, -10, 100.
•• float: Represents floating-point numbers (decimals), e.g.,
3.14, -2.5, 0.75.
•• complex: Represents complex numbers with real and
imaginary parts, e.g., 2 + 3j, -1.5 - 2j.
Sequence Types:
•• str: Represents a string of characters, e.g., “Hello, World!”,
‘Python’.
•• list: Represents an ordered collection of items, enclosed in
square brackets [], e.g., [1, 2, 3], [‘apple’, ‘banana’, ‘orange’].
•• tuple: Represents an ordered collection of items (immutable),
enclosed in parentheses (), e.g., (1, 2, 3), (‘a’, ‘b’, ‘c’).
Python Basics | 3

Mapping Type:
•• dict: Represents a collection of key-value pairs, enclosed in
curly braces {}, e.g., {‘name’: ‘John’, ‘age’: 25}.
Set Types:
•• set: Represents an unordered collection of unique elements,
enclosed in curly braces {}, e.g., {1, 2, 3}, {‘apple’, ‘banana’,
‘orange’}.
•• frozenset: Represents an immutable version of a set.
Boolean Type:
•• bool: Represents a Boolean value, either True or False.
None Type:
•• None: Represents the absence of a value or null.
These data types can be used to store and manipulate different
kinds of data in Python. It’s important to understand the data type
of a variable or value, as it affects the operations you can perform
on it and how it behaves in your program.

1.2 THE INTEGER DATA TYPE


An integer is a whole number that does not have a fractional
component. In Python, you can create an integer by simply typing
a number, such as:
>>> 42
42
In this example, we entered the integer value 42 and the shell
returned the same value. You can perform basic arithmetic operations
on integers, such as addition, subtraction, multiplication, and division.
>>> 40 + 2 42
>>> 50 - 8 42
>>> 21 * 2 42
>>> 84 / 2 42.0
Note that the result of the division operation is a floating-point
value because one of the operands is a floating-point value (in this
case, 84.0 divided by 2).
4 | Python Programming

1.3 FLOATING-POINT DATA TYPE


A floating-point number, or float for short, is a number that
has a fractional component. In Python, you can create a float by
appending a decimal point and at least one digit to an integer, or by
using scientific notation:
>>> 3.14
3.14
>>> 42.0
42.0
In the first example, we created a float with the value 3.14.
In the second example, we created a float with the value 42.0 by
appending a decimal point and a zero to the integer 42.
You can perform the same arithmetic operations on floats as you
can on integers:
>>> 4.2 + 37.8
42.0
>>> 50.0 - 8.0
42.0
>>> 10.5 * 4.0
42.0
>>> 84.0 / 2.0
42.0

1.4 THE STRING DATA TYPE


A string is a sequence of characters. In Python, you can create
a string by enclosing characters in single quotes or double quotes:
>>> ‘Hello, world!’
‘Hello, world!’
>>> “Hello, world!”
‘Hello, world!’
In both examples, we created a string with the value “Hello,
world!”.
Python Basics | 5

1.5 STRING CONCATENATION AND REPLICATION


You can perform concatenation and replication on strings:
>>> ‘Hello,’ + ‘ world!’
‘Hello, world!’
>>> ‘Spam’ * 3
‘SpamSpamSpam’
In the first example, we concatenated two strings using the +
operator to create the string “Hello, world!”. In the second example,
we replicated the string “Spam” three times using the * operator to
create the string “SpamSpamSpam”.

1.6 STORING VALUES IN VARIABLES


A variable is a named location in memory that stores a value. In
Python, you can create a variable by assigning a value to a name
using the = operator:
>>> message = ‘Hello, world!’
>>> print(message)
Hello, world!
In this example, we created a variable named message and
assigned it the string “Hello, world!”. We then used the print ()
function to display the value of the variable in the interactive shell.
You can also perform operations on variables:
>>> x = 10
>>> y = 20
>>> z = x + y
>>> print(z)
30
In this example, we created three variables x, y, and z, and
assigned them the integer values 10, 20, and the sum of x and y
(30), respectively. We then used the print () function to display the
value of z.
6 | Python Programming

1.7 FIRST PROGRAM


Now that we have covered the basic concepts of Python
programming, let’s walk through an example program to demonstrate
these concepts.
# This is a comment
print (‘Hello, world!’)
In this program, we have a comment on the first line that starts
with the # symbol. Comments are ignored by the Python interpreter
and are used to add notes or explanations to your code.
The second line of the program uses the print () function to
display the string “Hello, world!” in the interactive shell.
To run this program, save the code to a file with a .py extension
(e.g., helloworld.py) and run it from the terminal by typing “python
helloworld.py” (without the quotes).

1.8 DISSECTING YOUR PROGRAM


Let’s take a closer look at the different parts of the program.
# This is a comment
As mentioned earlier, this is a comment that is ignored by the
Python interpreter.
print(‘Hello, world!’)
This line uses the print() function to display the string “Hello,
world!” in the interactive shell.
Overall, this program is a simple example of how to use Python
to display text in the console. As you learn more about Python
programming, you will be able to write more complex programs that
perform a wide range of tasks.
Python Basics | 7

EXERCISE

Short Questions (2 Marks Each)

1. What is the purpose of the interactive shell in Python?


2. What are the three basic data types in Python?
3. How do you concatenate two strings in Python?
4. How do you store a value in a variable in Python?
5. What is the output of a Python program called?
6. What are Boolean values in Python?
7. Name two comparison operators in Python.
8. What are boolean operators used for in Python?
9. How can you end a program early in Python?
10. What is the purpose of importing modules in Python?

Long Questions (5 Marks Each)

1. Describe the concept of storing values in variables in Python.


Provide an example.
2. Explain the process of executing a Python program step by
step.
3. Discuss the different types of flow control statements
available in Python.
4. How can you combine boolean and comparison operators in
Python? Provide examples.
5. Explain the purpose of importing modules in Python and
provide an example of how to import a module.
6. What are the different data types used for storing numbers
in Python? Describe each type with an example.
7. Describe the process of concatenating and replicating strings
in Python. Provide examples.
8. Explain the role of boolean values in programming and how
they are used in flow control.
8 | Python Programming

9. Discuss the concept of comparison operators in Python and


provide examples of each operator.
10. What are the key features of the interactive shell in Python?
How does it facilitate experimentation and learning?

Multiple-choice Questions with Answers

1. Which of the following statements is true about Python?


a) It is a markup language.
b) It is an interpreted language.
c) It is a compiled language.
d) It is a database management system.
Answer: b) It is an interpreted language.
2. What is the purpose of the Python interactive shell?
a) To write and execute Python programs.
b) To perform mathematical calculations.
c) To debug code.
d) To experiment and evaluate Python expressions.
Answer: d) To experiment and evaluate Python expressions.
3. Which data type would you use to store a person’s age?
a) Integer
b) Floating-point
c) String
d) Boolean
Answer: a) Integer
4. Which symbol is used for variable assignment in Python?
a) =
b) ==
c) +
d) :
Answer: a) =
Python Basics | 9

5. What is the standard convention for the first program in any


programming language?
a) Display “Hello, World!”
b) Perform a mathematical calculation.
c) Import a module.
d) Declare a function.
Answer: a) Display “Hello, World!”
6. Which operator is used to check if two values are equal in
Python?
a) ==
b) =
c) !=
d) <=>
Answer: a) ==
7. What is the standard convention for the first program in any
programming language?
a) Display “Hello, World!”
b) Perform a mathematical calculation.
c) Import a module.
d) Declare a function.
Answer: a) Display “Hello, World!”
8. What are boolean values in Python?
a) Numbers with decimal points.
b) Strings enclosed in double quotes.
c) True and False
d) Variables assigned with the value “boolean”.
Answer: c) True and False
9. What is the result of the expression “Hello” + “World”?
a) “Hello World”
b) “HelloWorld”
10 | Python Programming

c) “Hello World!”
d) Error Answer:
Answer: c) “Hello World!”
10. Which statement is used to execute a block of code repeatedly
as long as a certain condition is met?
a) if statement
b) for loop
c) while loop
d) else statement
Answer: c) while loop
2
Flow Control

Flow control refers to the ability to control the execution of code


based on certain conditions. It is a crucial aspect of programming
and is used to create programs that are flexible and efficient. In this
chapter, we will explore the different aspects of flow control using
Python programming. We will start by discussing Boolean values
and comparison operators, which are the building blocks of flow
control. Then we will move on to Boolean operators, mixing Boolean
and comparison operators, and the elements of flow control. We will
also cover program execution, flow control statements, importing
modules, and ending a program early with sys.exit().

2.1 BOOLEAN VALUES


Boolean values are an essential part of programming in Python.
They represent two states: True and False. Understanding how
to work with boolean values is crucial for making decisions and
controlling the flow of your program.

2.1.1 Boolean Data Type

In Python, the boolean data type is denoted by the built-in bool


class. It has two possible values: True and False. Let’s see how to
assign boolean values to variables:
12 | Python Programming

x = True
y = False
In this example, x is assigned the boolean value True, and y is
assigned the boolean value False.

2.1.2 Boolean Operations

Python provides three primary boolean operations: and, or,


and not. These operators allow you to combine boolean values and
perform logical operations.
The and operator returns True if both operands are True, and
False otherwise. Here’s an example:
x = True
y = False
result = x and y
print(result) # Output: False
In this case, the and operator evaluates both x and y and returns
False because y is False.
The or operator returns True if at least one of the operands is
True, and False otherwise. Let’s take a look:
x = True
y = False
result = x or y
print(result) # Output: True
In this example, the or operator evaluates both x and y and
returns True because x is True.
The not operator is a unary operator that negates a boolean
value. It returns True if the operand is False, and False if the
operand is True. Here’s an example:
x = True
result = not x print(result) # Output: False
In this case, the not operator negates the value of x, resulting
in False.
Flow Control | 13

2.1.3 Boolean Expressions

Boolean expressions are comparisons or conditions that


evaluate to either True or False. We’ll explore comparison operators
in the next section, but for now, let’s see an example of a boolean
expression:
x=5
y = 10
result = x < y
print(result) # Output: True
In this example, the expression x < y compares the values of x
and y using the less-than operator <. Since 5 is less than 10, the
expression evaluates to True.

2.1.4 Boolean Values in Control Structures

Boolean values are commonly used in control structures, such


as if statements and loops, to determine the flow of execution.
In the following example, an if statement checks if a condition is
True and executes the code block inside if it is:
x=5
if x > 0:
print (“Positive number”)
In this case, the code block inside the if statement is executed
because the condition x > 0 evaluates to True.
Boolean values can also be used in loops, such as the while
loop, to control the repetition of code. Here’s an example:
x=0
while x < 5:
print(x) x += 1
This while loop will keep executing the code block inside as
long as the condition x < 5 is True. It prints the value of x and
increments it by 1 until x reaches 5.
14 | Python Programming

2.1.5 Example: User Authentication

Boolean values are often used in real-life scenarios. Let’s consider


a common example of user authentication.
username = input (“Enter your username: “)
password = input (“Enter your password: “)
if username == “admin” and password == “password123”:
print (“Login successful”)
else:
print(“Invalid username or password”)
In this code, the user is prompted to enter their username and
password. The if statement checks if the entered username is
“admin” and the password is “password123”. If both conditions are
True, the program prints “Login successful.” Otherwise, it prints
“Invalid username or password.”

2.2 COMPARISON OPERATORS


Comparison operators are used to compare values and return
boolean results based on the comparison. They are fundamental in
making decisions and controlling the flow of your program.

2.2.1 Comparison Operators List

Python provides several comparison operators to compare values.


Here is a list of the most commonly used comparison operators:
==: Equal to
!=: Not equal to
<: Less than
>: Greater than
<=: Less than or equal to
>=: Greater than or equal to

2.2.2 Using Comparison Operators

Let’s explore each comparison operator and see how they work
with different data types.
Flow Control | 15

Equal to (==)
The equal to operator == checks if the values on both sides are
equal. Here’s an example:
x=5
y=5
result = x == y
print(result) # Output: True
In this case, x == y evaluates to True because both x and y have
the same value, which is 5.
Not equal to (!=)
The not equal to operator != checks if the values on both sides
are not equal. Let’s see an example:
x=5
y = 10
result = x != y
print(result) # Output: True
In this example, x != y evaluates to True because x is 5 and y is
10, which are not equal.
Less than (<) and Greater than (>)
The less than operator < checks if the value on the left side is
less than the value on the right side. Similarly, the greater than
operator > checks if the value on the left side is greater than the
value on the right side. Let’s look at some examples:
x=5
y = 10
result1 = x < y
result2 = x > y
print(result1) # Output: True
print(result2) # Output: False
In this case, x < y evaluates to True because 5 is indeed less
than 10. On the other hand, x > y evaluates to False since 5 is not
greater than 10.
16 | Python Programming

Less than or equal to (<=) and Greater than or equal to (>=)


The less than or equal to operator <= checks if the value on
the left side is less than or equal to the value on the right side.
Similarly, the greater than or equal to operator >= checks if the
value on the left side is greater than or equal to the value on the
right side. Here’s an example:
x=5
y=5
result1 = x <= y
result2 = x >= y
print(result1) # Output: True
print(result2) # Output: True
In this example, x <= y and x >= y both evaluate to True because
x is equal to y, making the expressions true for both operators.

2.2.3 Chaining Comparison Operators

You can also chain multiple comparison operators together to


form complex conditions. Python evaluates these conditions from
left to right. Here’s an example:
x=5
y = 10
z=7
result = x < y < z
print(result) # Output: True
In this case, x < y < z evaluates to True because both x < y
and y < z are true. It’s important to note that this chaining works
because the comparison operators have left-to-right associativity.

2.2.4 Example: Temperature Conversion

Let’s consider a practical example of temperature conversion


from Celsius to Fahrenheit.
celsius = float(input(“Enter the temperature in Celsius: “))
Flow Control | 17

fahrenheit = (celsius * 9/5) + 32

if fahrenheit > 90:


print(“It’s hot!”)
elif fahrenheit < 30:
print(“It’s cold!”)
else:
print(“It’s moderate.”)

In this code, the user enters the temperature in Celsius. The


program converts it to Fahrenheit using the formula (C * 9/5) + 32.
Then, using comparison operators, it determines the temperature
category: hot, cold, or moderate.

2.3 BOOLEAN OPERATORS


Boolean operators allow you to combine boolean values and
expressions to create more complex conditions. Python provides
three boolean operators: and, or, and not.

2.3.1 The and Operator

The and operator returns True if both operands are True, and
False otherwise. It can be used with boolean values or expressions.
Let’s see some examples:
Using Boolean Values
x = True
y = False
result = x and y
print(result) # Output: False
In this case, x and y evaluates to False because y is False.
Using Boolean Expressions
x=5
18 | Python Programming

y = 10
result = x > 0 and y < 20
print(result) # Output: True
In this example, x > 0 and y < 20 evaluates to True because
both conditions are true.

2.3.2 The or Operator

The or operator returns True if at least one of the operands is


True, and False otherwise. It can also be used with boolean values
or expressions. Let’s see some examples:
Using Boolean Values
x = True
y = False
result = x or y
print(result) # Output: True
In this case, x or y evaluates to True because x is True.
Using Boolean Expressions
x=5
y = 10
result = x > 0 or y < 0
print(result) # Output: True
In this example, x > 0 or y < 0 evaluates to True because at
least one of the conditions is true.

2.3.3 The not Operator

The not operator is a unary operator that negates a boolean


value. It returns True if the operand is False, and False if the
operand is True. Let’s see some examples:
Using Boolean Values
x = True
result = not x
print(result) # Output: False
Flow Control | 19

In this case, not x evaluates to False because x is True.


Using Boolean Expressions
x = 5 y = 10
result = not (x > y)
print(result) # Output: True
In this example, not (x > y) evaluates to True because x > y is
False, and the not operator negates it.

2.3.4 Example: Voting Eligibility

Boolean operators are commonly used to check multiple


conditions in real-life scenarios. Let’s consider an example of voting
eligibility.
age = int(input(“Enter your age: “))
citizen = input(“Are you a citizen? (yes/no): “)
if age >= 18 and citizen == “yes”:
print(“You are eligible to vote.”)
else: print(“You are not eligible to vote.”)
In this code, the user is prompted to enter their age and
citizenship status. The if statement checks if the person is 18 years
or older and a citizen. If both conditions are True, it prints “You are
eligible to vote.” Otherwise, it prints “You are not eligible to vote.”

2.4 COMBINING BOOLEAN AND COMPARISON OPERATORS


Combining boolean and comparison operators allows you
to create more complex conditions for decision-making in your
programs.

2.4.1 Combining with and Operator

By using the and operator, you can combine multiple conditions


that all need to be True for the overall expression to evaluate to
True. Let’s see an example:
x=5
y = 10
20 | Python Programming

z=7
result = x < y and y > z
print(result) # Output: True
In this case, x < y and y > z are both true, so x < y and y > z
evaluates to True.

2.4.2 Combining with or Operator

Using the or operator, you can combine multiple conditions


where at least one condition needs to be True for the overall
expression to evaluate to True. Here’s an example:
x=5
y = 10
z=7
result = x < y or y < z
print(result) # Output: True
In this example, x < y is true, so x < y or y < z evaluates to True.

2.4.3 Combining with not Operator

The not operator can be used to negate a complex condition. It


can be useful when you want to check if a condition is False. Let’s
see an example:
x=5
y = 10
result = not (x > y)
print(result) # Output: True
In this case, x > y is False, and not (x > y) evaluates to True.

2.4.4 Example: Ticket Purchase Eligibility

Let’s consider a real-life example of ticket purchase eligibility


based on age and available seats.
age = int(input(“Enter your age: “))
seats_available = 100
if age >= 18 and seats_available > 0:
Flow Control | 21

print(“Ticket purchase is eligible.”)


else:
print(“Ticket purchase is not eligible.”)
In this code, the user is asked to enter their age, and the program
checks if the person is 18 years or older and if there are seats
available. If both conditions are True, it prints “Ticket purchase is
eligible.” Otherwise, it prints “Ticket purchase is not eligible.”

2.5 ELEMENTS OF FLOW CONTROL


The elements of flow control in programming refer to the tools
and constructs that allow you to manage the flow or execution path
of your code. These elements help you make decisions, repeat code
blocks, and handle different scenarios based on specific conditions.
The key elements of flow control in most programming languages,
including Python, include:
Conditional Statements:
•• if statement: Executes a block of code if a certain condition
is true.
•• if-else statement: Executes one block of code if a condition is
true and another block if the condition is false.
•• if-elif-else statement: Executes different blocks of code
based on multiple conditions.
Looping Statements:
•• for loop: Repeats a block of code for a specific number of
iterations or over a sequence of elements.
•• while loop: Repeats a block of code as long as a certain
condition remains true.
•• break statement: Terminates the execution of a loop
prematurely.
•• continue statement: Skips the current iteration of a loop
and continues to the next iteration.
Exception Handling:
•• try-except statement: Allows you to handle and recover from
exceptions that occur during the execution of your code.
22 | Python Programming

•• finally statement: Specifies a block of code that is always


executed, regardless of whether an exception occurs or not.
Control Flow Modifiers:
•• return statement: Terminates the execution of a function
and returns a value (optional).
•• yield statement: Pauses the execution of a generator function
and returns a value (generally used in iteration contexts).
•• pass statement: Represents a null operation or a placeholder
to be filled in later.
These elements of flow control provide the necessary tools to
navigate through different branches of code, repeat actions, handle
errors, and control the overall execution of your program. By
effectively utilizing these elements, you can create programs that
are flexible, adaptive, and capable of making decisions based on
various conditions.Top of Form

2.6 PROGRAM EXECUTION


Program execution refers to the order in which statements are
executed in a program. By default, Python executes statements
sequentially, from top to bottom. However, with flow control, you
can alter the program’s execution path based on certain conditions.
This ability to make decisions and perform different actions based
on specific conditions is what makes programming powerful.
Let’s look at an example to understand program execution
better. Suppose we want to create a program that checks whether a
given number is even or odd. Here’s how we can achieve that using
an if statement:
number = int(input(“Enter a number: “))
if number % 2 == 0:
print(“The number is even.”)
else:
print(“The number is odd.”)
In this code snippet, we first prompt the user to enter a number
using the input() function and convert it to an integer using int().
Flow Control | 23

Then, we use an if statement to check if the number is divisible


by 2 (number % 2 == 0). If it is, we print “The number is even.”
Otherwise, we print “The number is odd.” The execution flow of the
program depends on the condition being true or false.

2.7 FLOW CONTROL STATEMENTS


Flow control statements are constructs in programming that
allow you to control the flow or execution path of your code. In
Python, flow control statements include conditional statements (if,
if-else, if-elif-else), looping statements (for loop, while loop), and
exception handling statements (try-except, finally). Let’s explore
each of these statements in detail, including their syntax and
examples.
Conditional Statements:
if statement:
Syntax:
if condition:
# Code block executed if condition is true
Example:
x = 5 if x > 0: print(“x is positive”)
In this example, the if statement checks if the condition x > 0 is
true. If it is true, the code block print(“x is positive”) is executed,
and the output will be “x is positive”.
if-else statement:
Syntax:
if condition:
# Code block executed if condition is true
else:
# Code block executed if condition is false
Example:
x=5
if x > 0:
print(“x is positive”)
24 | Python Programming

else:
print(“x is non-positive”)
In this example, the if-else statement checks if the condition
x > 0 is true. If it is true, the code block print(“x is positive”) is
executed. Otherwise, the code block print(“x is non-positive”) is
executed. The output will be “x is positive”.
if-elif-else statement:
Syntax:
if condition1:
# Code block executed if condition1 is true
elif condition2:
# Code block executed if condition1 is false and condition2 is
true
else:
# Code block executed if all conditions are false
Example:
x=5
if x > 0:
print(“x is positive”)
elif x < 0:
print(“x is negative”)
else:
print(“x is zero”)
In this example, the if-elif-else statement checks multiple
conditions. If x > 0 is true, the code block print(“x is positive”) is
executed. If it is false and x < 0 is true, the code block print(“x is
negative”) is executed. If both conditions are false, the code block
print(“x is zero”) is executed. The output will be “x is positive”.
Looping Statements:
for loop:
Syntax:
for item in iterable:
Flow Control | 25

# Code block executed for each item in the iterable


Example:
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
In this example, the for loop iterates over each item in the list
fruits. The code block print(fruit) is executed for each fruit, and
the output will be:
Copy code
apple banana cherry
while loop:
Syntax:
while condition:
# Code block executed as long as the condition is true
Example:
count = 0
while count < 5:
print(count) count += 1
In this example, the while loop executes the code block
print(count) as long as the condition count < 5 is true. The output
will be:
01234
Exception Handling Statements:
try-except statement:
Syntax:
try:
# Code block where exceptions might occur except
ExceptionType:
# Code block executed if an exception of type ExceptionType
occurs
26 | Python Programming

Example:
try: x = 10 / 0
except ZeroDivisionError:
print(“Division by zero is not allowed”)
In this example, the try block attempts to perform a division
by zero operation, which raises a ZeroDivisionError exception.
The except block catches the exception and executes the code
block print(“Division by zero is not allowed”). The output will be
“Division by zero is not allowed”.
finally statement:
Syntax:
try:
# Code block where exceptions might occur except
ExceptionType
: # Code block executed if an exception of type ExceptionType
occurs
finally:
# Code block always executed, regardless of whether an exception
occurred or not
Example:
try: x = 10 / 0
except ZeroDivisionError:
print(“Division by zero is not allowed”)
finally:
print(“Finally block executed”)
In this example, similar to the previous example, the try block
raises a ZeroDivisionError exception. The except block catches
the exception and executes the code block print(“Division by zero
is not allowed”). Finally, the finally block is always executed,
regardless of whether an exception occurred or not. The output will
be:
•• Division by zero is not allowed
•• Finally block executed
Flow Control | 27

2.8 IMPORTING MODULES


Importing modules in Python allows you to access pre-existing
code and functionality from external files or libraries. It enables you
to extend the capabilities of your program by utilizing functions,
classes, and variables defined in other modules. In this explanation,
we’ll cover the syntax and provide examples for different ways of
importing modules in Python.
Python provides several ways to import modules:
Importing the Entire Module: The simplest way to import a
module is by using the import keyword followed by the module
name.
Syntax:
import module_name
Example:
import math result = math.sqrt(25)
print(result) # Output: 5.0
In this example, the math module is imported, and the sqrt()
function from the module is used to calculate the square root of 25.
The output will be 5.0.
Importing Specific Items from a Module: Instead of importing
the entire module, you can import specific functions, classes, or
variables from a module using the from keyword.
Syntax:
from module_name import item_name1, item_name2, ...
Example:
from math import sqrt, pow
result1 = sqrt(25)
result2 = pow(2, 3)
print(result1, result2) # Output: 5.0 8.0
In this example, only the sqrt() and pow() functions from the
math module are imported. The code then uses these functions
directly without referencing the module name. The output will be
5.0 and 8.0.
28 | Python Programming

Importing a Module with an Alias: You can import a module


with an alias or a different name using the as keyword. This can be
useful to provide shorter or more descriptive names for modules.
Syntax:
import module_name as alias_name
Example:
import math as m result = m.sqrt(25)
print(result) # Output: 5.0
In this example, the math module is imported with the alias m.
The sqrt() function is then accessed using the alias. The output will
be 5.0.
Importing All Items from a Module: If you want to import all
functions, classes, and variables from a module, you can use the *
wildcard character.
Syntax:
from module_name import *
Example:
from math import * result = sqrt(25)
print(result) # Output: 5.0
In this example, all items from the math module are imported
using the * wildcard character. The sqrt() function is then used
directly. The output will be 5.0.
It’s important to note that importing modules only needs to
be done once in a program, typically at the beginning. Once a
module is imported, you can use its functions, classes, or variables
throughout the program.
Additionally, Python provides a vast standard library with
many modules available for use. You can also install and import
third-party modules created by other developers to enhance your
programs.
By leveraging the power of importing modules, you can tap into
a wide range of functionality and build upon the existing Python
ecosystem to create more sophisticated and efficient programs.Top
of Form
Flow Control | 29

2.9 ENDING A PROGRAM EARLY WITH SYS.EXIT()


In some situations, you may need to terminate a program before
it reaches its natural end. Python provides the sys.exit() function
from the sys module, which allows you to exit a program at any point.
It’s commonly used when a critical error occurs, or when a certain
condition is met and you want to stop the program immediately.
To use sys.exit(), you need to import the sys module first:
import sys
# Code execution sys.exit()
In the example above, we import the sys module and use sys.
exit() to terminate the program.
It’s worth mentioning that sys.exit() raises the SystemExit
exception, so if the function call is caught by an exception handler,
the program can continue execution from the exception block.

2.9.1 Example: Weather Report Application

Let’s put our knowledge of flow control to use by creating a simple


weather report application. The application will prompt the user to
enter the current temperature, and based on that temperature, it
will display a corresponding weather description.
temperature = float(input(“Enter the current temperature: “))
if temperature < 10: print(“It’s very cold outside.”)
elif temperature >= 10 and temperature < 20:
print(“It’s a bit chilly.”)
elif temperature >= 20 and temperature < 30:
print(“The weather is pleasant.”)
else:
print(“It’s quite hot today.”)
In this example, we prompt the user to enter the current
temperature. Based on the temperature entered, the program
uses an if-elif-else statement to determine the appropriate weather
description. The execution flow of the program depends on the
temperature value entered by the user.
30 | Python Programming

EXERCISE

Short Questions (2 Marks)

1. What are boolean values?


2. How many comparison operators are there in Python?
3. Can boolean operators be used with non-boolean values?
4. Explain the order of evaluation when mixing boolean and
comparison operators.
5. How does a loop contribute to flow control?

Long Questions (5 Marks)

1. Provide examples of conditional statements and their usage


in practical scenarios.
2. Explain the order of evaluation and precedence rules when
mixing boolean and comparison operators.
3. Discuss the concept of short-circuit evaluation in relation to
boolean operators.
4. Describe the behavior of comparison operators when used
with strings and other non-numeric data types.
5. Discuss common mistakes or pitfalls to avoid when working
with comparison operators.

Multiple Choice Questions

1. Which of the following is a boolean value in Python?


a) 10
b) “Hello”
c) True
d) 3.14
Answer: c
2. What does the comparison operator “==” do?
a) Checks if two values are equal
b) Checks if two values are not equal
Flow Control | 31

c) Checks if one value is greater than another


d) Checks if one value is less than another
Answer: a
3. Which boolean operator is used for logical AND?
a) &&
b) ||
c) !
d) and
Answer: d
4. Which of the following is an example of mixing boolean and
comparison operators?
a) 5 < 10 and 20 > 15
b) 5 < 10 or 20 > 15
c) 5 < 10 not 20 > 15
d) 5 < 10 + 20 > 15
Answer: a
5. What is the result of the expression 3 > 2 and 4 < 6?
a) True
b) False
c) None
d) Error
Answer: a
6. What does the “if” statement do in Python?
a) Repeats a block of code a certain number of times
b) Executes a block of code only if a certain condition is true
c) Imports a module into the program
d) Terminates the program execution
Answer: b
7. How can you end a program early in Python?
a) Using the “stop” keyword
b) Calling the function “exit()”
32 | Python Programming

c) Using the “quit()” function


d) None of the above
Answer: b
8. What does the “import” statement do in Python?
a) Imports a module into the program
b) Exports a module from the program
c) Declares a variable
d) Assigns a value to a variable
Answer: a
9. Which module is commonly used for handling command line
arguments in Python?
a) sys
b) os
c) math
d) time
Answer: a
10. What is the correct way to import the “random” module in
Python?
a) import random
b) from random import random
c) import random as rnd
d) All of the above
Answer: a
3
Functions

In the world of programming, functions play a pivotal role in


breaking down complex tasks into smaller, more manageable pieces
of code. They serve as building blocks that allow us to organize
our code, make it reusable, and improve overall efficiency. The
chapter begins by introducing the concept of defining functions
with parameters. Parameters act as placeholders for the values
that are passed into a function when it is called. By understanding
the syntax and usage of parameterized functions, you will gain
the ability to create versatile and adaptable code that can handle
different inputs and scenarios.
Next, the chapter explores the concept of return values and
return statements. Functions not only perform specific operations
but can also provide values back to the caller. You will learn how to
effectively use the return statement to retrieve data from a function
and utilize it further in your code, enabling you to build more
sophisticated and interconnected programs.
Occasionally, functions may not explicitly return any value. In
such cases, they automatically return a special value called “None.”
This chapter dedicates a section to exploring the concept of the None
value and its usage within functions. You will gain insights into
handling situations where a function doesn’t need to return a specific
result, allowing you to handle various scenarios more effectively.
34 | Python Programming

Python offers the flexibility of passing arguments to functions using


keywords rather than relying solely on their positional order. The
chapter then delves into keyword arguments and their application,
with a particular focus on the built-in print() function. You will
discover how to enhance the clarity and readability of your code
by leveraging keyword arguments, enabling you to write more
expressive and self-documenting programs.
Understanding the scope of variables within functions is crucial
for writing robust and maintainable code. This chapter introduces
the concept of variable scope, distinguishing between local and
global variables. By exploring the intricacies of local and global
scope, you will gain valuable insights into how variables are accessed
and modified within functions and how they relate to the broader
program structure. While local variables are typically confined to
the scope of a function, there may be situations when you need
to modify a global variable from within a function. The chapter
discusses the global statement, which enables you to explicitly
indicate that a variable belongs to the global scope. You will discover
how to leverage this statement to modify global variables, ensuring
your functions can interact with variables in the broader context of
your program.
Finally, the chapter explores the concept of exception handling.
Errors and exceptions are inevitable in programming, and this
section equips you with the knowledge and techniques to gracefully
handle and recover from them. By learning how to use try-except
blocks to catch and handle exceptions, you will ensure that your
programs can handle unforeseen circumstances and continue
execution in a controlled manner.
By the end of Chapter , you will have gained a solid understanding
of functions and their various aspects. Armed with this knowledge,
you will be able to write modular, efficient, and error-resistant
code, paving the way for building complex and robust applications.
Whether you’re a beginner or an experienced programmer, the
insights and skills acquired from this chapter will significantly
enhance your programming repertoire.Top of Form
Functions | 35

3.1 def STATEMENTS WITH PARAMETERS


In this section, we will explore the concept of defining functions
with parameters in Python. A function parameter is a variable that
is used to pass information into a function when it is called. This
allows us to make our functions more flexible and reusable.
To define a function with parameters, we use the def statement
followed by the function name and a list of parameter names
enclosed in parentheses. Let’s look at an example:
def greet(name):
print(“Hello, “ + name + “!”)
greet(“Alice”)
Output:
Hello, Alice!
In the above code, we defined a function called greet that takes
one parameter called name. When we call the greet function with the
argument “Alice”, the function prints out a personalized greeting.
Parameters act as placeholders for the values that will be passed
into the function. They can be used within the function body just
like any other variable. Let’s modify our greet function to use the
parameter in a different way:
def greet(name):
message = “Hello, “ + name + “!”
return message
result = greet(“Bob”)
print(result)
Output:
Hello, Bob!
In this updated version of the greet function, we store the
personalized greeting in a variable called message. Then, we use
the return statement to send the value of message back to the
caller. The returned value is assigned to the result variable, which
we then print.
36 | Python Programming

3.2 RETURN VALUES AND RETURN STATEMENTS


In Python, functions can return values using the return
statement. The return statement allows a function to send a value
back to the caller. This is useful when we want to compute a result
inside a function and use it in the rest of our program.
Let’s consider a practical example where we calculate the area
of a circle:
import math
def calculate_area(radius):
area = math.pi * radius ** 2
return area
circle_radius = 5
circle_area = calculate_area(circle_radius)
print(“The area of the circle is:”, circle_area)
Output:
The area of the circle is: 78.53981633974483
In the above code, we define a function called calculate_area
that takes the radius as a parameter. Inside the function, we use the
formula for the area of a circle (math.pi * radius ** 2) to calculate
the area. We then use the return statement to send the calculated
area back to the caller.
The returned value is assigned to the variable circle_area, which
we print to display the result.
Section 3.3: The None Value
In Python, None is a special value that represents the absence of
a value. It is often used to indicate that a function does not return
anything or that a variable has no assigned value.
Consider the following example:
def perform_task():
# Code to perform a task...
result = perform_task()
print(result)
Functions | 37

Output:
None
In this code, we define a function called perform_task that
does not have a return statement. When we call this function and
assign its result to the variable result, we get the value None. This
indicates that the function does not return anything.
We can also explicitly return None from a function:
def greet(name):
if name:
return “Hello, “ + name + “!”
else:
return None
result = greet(“”)
print(result)
Output:
None
In this example, if the name parameter is an empty string, the
function returns None to indicate that no greeting can be formed.

3.3 KEYWORD ARGUMENTS AND print()


Python allows us to pass arguments to a function using keyword
arguments. Keyword arguments are passed in the form parameter_
name=value, allowing us to specify which parameter each value
corresponds to.
The print() function in Python accepts several optional keyword
arguments that modify its behavior. Let’s explore some of them:
print(“Hello”, “World”, sep=”, “, end=”!\n”)
print(“Python”, “Programming”, sep=”-”, end=”!\n”)
Output:
Hello, World!
Python-Programming!
38 | Python Programming

In the first print() statement, we use the sep keyword argument


to specify the separator between the values. By default, the separator
is a space character, but we override it to be “, “.
In the second print() statement, we use both the sep and end
keyword arguments. The sep argument sets the separator to a
hyphen (-), and the end argument sets the ending character to
“!\n”, which adds an exclamation mark and a newline character
at the end.
Using keyword arguments can make our code more readable
and self-explanatory, especially when dealing with functions that
have many parameters.

3.4 LOCAL AND GLOBAL SCOPE


Here,we will explore the concepts of local and global scope in
programming languages. Scope refers to the visibility or accessibility
of variables, functions, and objects within a program. Understanding
scope is crucial for writing clean and maintainable code. We will
discuss how variables are defined within different scopes and how
they can be accessed.

3.4.1 Local Scope

Variables that are defined within a function have a local scope.


This means that they can only be accessed within the function where
they are defined. Once the function finishes executing, the local
variables are destroyed and their values are no longer accessible.
Let’s consider an example to better understand local scope:
def calculate_sum(a, b):
result = a + b
return result
sum_result = calculate_sum(3, 5)
print(sum_result) # Output: 8
print(result) # Error: NameError: name ‘result’ is not defined
In the example above, the variable result is defined within the
calculate_sum function. It is accessible only within the function.
Functions | 39

When we try to access result outside of the function, we get a


NameError because the variable is not defined in the global scope.

3.4.2 Global Scope


Variables that are defined outside of any function or block have
a global scope. They can be accessed from anywhere in the program,
including inside functions. To access a global variable within a
function, we need to use the global keyword. Let’s see an example:
global_var = 10
def multiply_by_global(num):
global global_var
return num * global_var
result = multiply_by_global(5)
print(result) # Output: 50
In the example above, we have a global variable global_var that
is defined outside of any function. Inside the multiply_by_global
function, we use the global keyword to indicate that we want to
use the global global_var rather than creating a new local variable
with the same name. We can then perform operations on the global
variable within the function.

3.5 THE GLOBAL STATEMENT


In addition to using the global keyword to access global variables
within functions, Python provides the global statement. The global
statement allows us to modify the value of a global variable from
within a function. Let’s consider an example to illustrate the usage
of the global statement:
global_var = 10
def modify_global():
global global_var
global_var = 20
print(global_var) # Output: 10
modify_global()
40 | Python Programming

print(global_var) # Output: 20
In the above example, we define a global variable global_var with
an initial value of 10. Inside the modify_global function, we use
the global statement to indicate that we want to modify the global
variable global_var. After calling the modify_global function, we
can see that the value of global_var has changed to 20.

3.6 EXCEPTION HANDLING


Exception handling is a mechanism that allows us to catch
and handle errors or exceptional conditions that may occur during
the execution of a program. By using exception handling, we can
gracefully handle errors without crashing the program. In Python,
exceptions are raised when an error occurs, and they can be caught
using the try and except statements.
try:
num = int(input(“Enter a number: “))
result = 100 / num
print(“Result:”, result)
except ZeroDivisionError:
print(“Error: Cannot divide by zero.”)
except ValueError:
print(“Error: Invalid input. Please enter a valid number.”)
In the example above, we ask the user to enter a number. If
the user enters zero, a ZeroDivisionError will be raised, and
the corresponding except block will execute, displaying an error
message. If the user enters a non-numeric value, a ValueError will
be raised, and the corresponding except block will execute.
Exception handling allows us to handle errors gracefully, provide
meaningful error messages to users, and take appropriate actions
based on the encountered exceptions.
Functions | 41

EXERCISE

Short Questions (2 Marks)

1. What is a function in programming?


2. What is the purpose of using parameters in a function?
3. What is the role of the return statement in a function?
4. What is the significance of the None value in Python?
5. How can keyword arguments be used in function calls?

Long Questions (5 Marks)

1. Explain the concept of local and global scope in Python


functions. Provide examples to illustrate the difference
between local and global variables.
2. How are functions defined with parameters? Describe the
process of passing arguments to functions and how they are
used within the function body.
3. What is the role of the return statement in a function?
Discuss its importance in returning values from a function
and how it affects the flow of execution.
4. Explain the concept of the None value in Python. Discuss its
purpose and when it is commonly used in functions.
5. Discuss the usage of the global statement in Python. How
does it allow modification of global variables from within a
function? Provide an example to illustrate its usage.

Multiple Choice Questions

1. Which of the following is true about functions in programming?


a) Functions cannot have parameters
b) Functions cannot have a return statement
c) Functions are reusable blocks of code
d) Functions can only be defined inside a loop
Answer: c) Functions are reusable blocks of code
42 | Python Programming

2. What is the purpose of using parameters in a function?


a) Parameters define the name of a function
b) Parameters specify the return value of a function
c) Parameters allow the function to receive input values
d) Parameters determine the number of times a function
can be called
Answer: c) Parameters allow the function to receive input
values
3. What is the role of the return statement in a function?
a) It terminates the function execution
b) It defines the name of the function
c) It specifies the output of the function
d) It determines the number of parameters in the function
Answer: c) It specifies the output of the function
4. What does the None value represent in Python?
a) An error in the code
b) A placeholder for an empty value
c) A reserved keyword in Python
d) A function that does not return anything
Answer: b) A placeholder for an empty value
5. How can keyword arguments be used in function calls?
a) By passing arguments in a specific order
b) By specifying the argument values using their parameter
names
c) By using special characters in the argument values
d) By using a separate function for keyword arguments
Answer: b) By specifying the argument values using their
parameter names
Functions | 43

6. What is local scope in Python?


a) Variables defined within a function
b) Variables defined outside any function
c) Variables accessible from any part of the program
d) Variables that cannot be modified
Answer: a) Variables defined within a function
7. Which of the following is true about global scope in Python?
a) Global variables can only be accessed from within a
function
b) Global variables can be accessed from any part of the
program
c) Global variables are defined inside a function
d) Global variables cannot be modified
Answer: b) Global variables can be accessed from any part of
the program
8. How is the global statement used in Python?
a) It defines a new global variable
b) It modifies the value of a global variable from within a
function
c) It restricts the visibility of a variable to the local scope
d) It enables exception handling in Python
Answer: b) It modifies the value of a global variable from
within a function
9. What is exception handling used for in programming?
a) To catch and handle errors or exceptional conditions
b) To define global variables
c) To pass arguments to a function
d) To print values on the console
Answer: a) To catch and handle errors or exceptional
conditions
44 | Python Programming

10. Which keyword is used to catch exceptions in Python?


a) try
b) except
c) catch
d) finally
Answer: b) except
11. In Python, can a function return multiple values?
a) Yes
b) No
Answer: a) Yes
12. What happens if a function does not have a return statement?
a) It returns None implicitly
b) It raises an error
c) It returns the value of the last expression executed
d) It does not return anything
Answer: a) It returns None implicitly
13. Which statement is used to raise an exception manually in
Python?
a) raise
b) try
c) except
d) finally
Answer: a) raise
14. What is the purpose of the finally block in exception handling?
a) It is used to handle exceptions
b) It is executed when an exception is raised
c) It is executed regardless of whether an exception occurs or
not
d) It is used to define global variables
Answer: c) It is executed regardless of whether an exception
occurs or not
Functions | 45

15. Which exception is raised when dividing by zero in Python?


a) ZeroDivisionError
b) TypeError
c) ValueError
d) SyntaxError
Answer: a) ZeroDivisionError
4
Lists

In this chapter, we will explore one of the most versatile and


commonly used data types in programming: lists. A list is an
ordered collection of elements, which can be of any data type such
as numbers, strings, or even other lists.
Lists are mutable, meaning that you can modify their elements
after they have been created. This section will provide a detailed
explanation of the list data type and how to work with lists
effectively.

4.1 THE LIST DATA TYPE


Lists are defined by enclosing a comma-separated sequence of
elements within square brackets ([]). Let’s start by creating a simple
list:
fruits = [‘apple’, ‘banana’, ‘orange’]
In this example, we have defined a list called fruits containing
three elements: ‘apple’, ‘banana’, and ‘orange’. Each element in the
list has an index associated with it, starting from 0. Thus, ‘apple’
has an index of 0, ‘banana’ has an index of 1, and ‘orange’ has an
index of 2.
Lists | 47

4.1.1 Accessing List Elements

To access elements of a list, we use their indices. We can retrieve


a single element by specifying its index within square brackets ([]):
print(fruits[0])
Output: ‘apple’
We can also access a range of elements using slicing. Slicing
allows us to extract a portion of the list based on a specified start
and end index. For example:
print(fruits[1:3])
Output: [‘banana’, ‘orange’]
Here, the slicing operation fruits[1:3] retrieves elements starting
from index 1 up to, but not including, index 3.

4.1.2 Modifying List Elements

Lists are mutable, so we can change their elements directly. We


can assign a new value to an element using its index:
fruits [0] = ‘grape’
print(fruits)
Output: [‘grape’, ‘banana’, ‘orange’]
In this example, we have changed the first element of the fruits
list from ‘apple’ to ‘grape’.

4.2 WORKING WITH LISTS


In this section, we will explore various operations and techniques
for manipulating lists efficiently.

4.2.1 List Concatenation and Repetition

Lists can be concatenated using the + operator, which combines


two or more lists into a single list:
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
48 | Python Programming

combined = numbers1 + numbers2


print(combined)
Output: [1, 2, 3, 4, 5, 6]
We can also repeat a list multiple times using the * operator:
repeated = numbers1 * 3 print(repeated)
Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

4.2.2 List Length

To determine the number of elements in a list, we can use the


len() function:
print(len(numbers1))
Output: 3
The len() function returns the length of the list, which in this
case is 3.

4.2.3 List Iteration

Lists can be iterated using loops. We can use a for loop to iterate
over each element in a list:
for fruit in fruits:
print(fruit)
This will output each fruit on a new line:
grape
banana
orange

4.2.4 List Membership


To check if an element is present in a list, we can use the in
keyword:
if ‘apple’ in fruits:
print(‘Apple is in the list.’)
If ‘apple’ is present in the fruits list, the above code will print
“Apple is in the list.”
Lists | 49

4.3 AUGMENTED ASSIGNMENT OPERATORS


In this section, we will explore augmented assignment operators,
which provide a shorthand notation for performing operations on
list elements.

4.3.1 The += Operator


The += operator is used to add new elements to a list. It appends
the right-hand side (RHS) element(s) to the list:
animals = [‘cat’, ‘dog’]
animals += [‘elephant’]
print(animals)
Output: [‘cat’, ‘dog’, ‘elephant’]
Here, the += operator adds the element ‘elephant’ to the animals
list.

4.3.2 Other Augmented Assignment Operators


Augmented assignment operators can also be used with other
arithmetic operators, such as -, *, /, and %. These operators perform
the corresponding operation on the list elements and assign the
result back to the list. For example:
numbers = [1, 2, 3]
numbers *= 2 print(numbers)
Output: [1, 2, 3, 1, 2, 3]
In this case, the *= operator multiplies the numbers list by 2,
resulting in a repeated list.

4.4 METHODS
In this section, we will explore various methods available for
lists. Methods are built-in functions that can be applied directly to
list objects.

4.4.1 Adding Elements to a List

The append() method allows us to add a single element to the


end of a list:
50 | Python Programming

fruits.append(‘pear’)
print(fruits)
Output: [‘grape’, ‘banana’, ‘orange’, ‘pear’]
The extend() method is used to append multiple elements from
an iterable (e.g., another list) to the end of the original list:
fruits.extend([‘kiwi’, ‘mango’])
print(fruits)
Output: [‘grape’, ‘banana’, ‘orange’, ‘pear’, ‘kiwi’, ‘mango’]

4.4.2 Removing Elements from a List

The remove() method is used to remove the first occurrence of a


specified element from a list:
fruits.remove(‘banana’)
print(fruits)
Output: [‘grape’, ‘orange’, ‘pear’, ‘kiwi’, ‘mango’]
The pop() method removes and returns the element at a specified
index. If no index is provided, it removes and returns the last
element:
removed_fruit = fruits.pop(1)
print(removed_fruit)
Output: ‘orange’
print(fruits)
Output: [‘grape’, ‘pear’, ‘kiwi’, ‘mango’]

4.4.3 Other List Methods

There are several other useful list methods, such as insert(),


index(), sort(), and reverse(), among others. These methods provide
flexibility and enable various operations on lists.
1. The insert() Method:
The insert() method is used to insert an element at a specified
position within a list. It takes two arguments: the index where
the element should be inserted and the value of the element to be
inserted.
Lists | 51

Syntax:
list_name.insert(index, value)
Example:
fruits = [‘apple’, ‘banana’, ‘orange’]
fruits.insert(1, ‘grape’)
print(fruits)
Output: [‘apple’, ‘grape’, ‘banana’, ‘orange’]
In this example, the insert() method is used to insert the element
‘grape’ at index 1 in the fruits list. As a result, the list is modified to
[‘apple’, ‘grape’, ‘banana’, ‘orange’].
2. The index() Method:
The index() method is used to find the index of the first occurrence
of a specified element within a list. It takes one argument: the value
of the element to be searched.
Syntax:
list_name.index(value)
Example:
fruits = [‘apple’, ‘banana’, ‘orange’]
index = fruits.index(‘banana’)
print(index)
Output: 1
In this example, the index() method is used to find the index
of the element ‘banana’ in the fruits list. The returned value, 1,
represents the index position of ‘banana’ within the list.
3. The sort() Method:
The sort() method is used to sort the elements of a list in
ascending order. This method modifies the original list and does
not return a new sorted list.
Syntax:
list_name.sort()
Example:
numbers = [5, 2, 8, 1, 3]
52 | Python Programming

numbers.sort()
print(numbers)
Output: [1, 2, 3, 5, 8]
In this example, the sort() method is applied to the numbers list,
which contains unsorted integers. After calling the sort() method,
the list is sorted in ascending order: [1, 2, 3, 5, 8].
4. The reverse() Method:
The reverse() method is used to reverse the order of elements in
a list. This method modifies the original list and does not return a
new reversed list.
Syntax:
list_name.reverse()
Example:
fruits = [‘apple’, ‘banana’, ‘orange’]
fruits.reverse()
print(fruits)
Output: [‘orange’, ‘banana’, ‘apple’]
In this example, the reverse() method is applied to the fruits
list. After calling the reverse() method, the order of elements in the
list is reversed: [‘orange’, ‘banana’, ‘apple’].Top of Form
Lists | 53

EXERCISE

Short Questions Answers (2 Marks)

1. What is the list data type in Python?


2. How do you access elements in a list?
3. What is the difference between append() and extend() methods
for lists?
4. How can you determine the length of a list?
5. What does it mean for a list to be mutable?

Long Answer Questions (5 Marks)

1. Explain the concept of indexing in lists with examples.


2. Discuss the various ways to modify elements in a list.
3. Describe the process of concatenating and repeating lists.
4. What are augmented assignment operators for lists? Provide
examples.
5. Elaborate on the different methods available for lists and
their applications.

Multiple Choice Questions

1. Which symbol is used to define a list in Python?


a) ()
b) []
c) {}
d) //
Answer: b) []
2. How do you access the first element of a list?
a) list[0]
b) list[1]
c) list[-1]
d) list[-2]
Answer: a) list[0]
54 | Python Programming

3. What is the result of the following code?


numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4, 3, 2, 1]
d) [4, 2, 3]
Answer: b) [1, 2, 3, 4]
4. How do you find the number of elements in a list?
a) count()
b) size()
c) length()
d) len()
Answer: d) len()
5. Which list method is used to remove an element from a list
by its value?
a) remove()
b) delete()
c) discard()
d) pop()
Answer: a) remove()
6. Which list method is used to sort the elements in ascending
order?
a) sort()
b) order()
c) arrange()
d) organize()
Answer: a) sort()
Lists | 55

7. What does the reverse() method do to a list?


a) Reverses the order of elements in the list.
b) Removes the last element from the list.
c) Repeats the list multiple times.
d) Checks if a specific element is present in the list.
Answer: a) Reverses the order of elements in the list.
8. What is the output of the following code?
fruits = [‘apple’, ‘banana’, ‘orange’]
fruits.insert(1, ‘grape’)
print(fruits)
a) [‘grape’, ‘banana’, ‘orange’]
b) [‘apple’, ‘grape’, ‘banana’, ‘orange’]
c) [‘apple’, ‘banana’, ‘grape’, ‘orange’]
d) [‘apple’, ‘banana’, ‘orange’, ‘grape’]
Answer: c) [‘apple’, ‘banana’, ‘grape’, ‘orange’]
9. Which operator is used for list concatenation?
a) +
b) -
c) *
d) /
Answer: a) +
10. Which method is used to find the index of a specific element
in a list?
a) find()
b) locate()
c) search()
d) index()
Answer: d) index()
56 | Python Programming

11. What is the output of the following code?


numbers = [1, 2, 3]
numbers *= 2
print(numbers)
a) [1, 2, 3]
b) [1, 2, 3, 1, 2, 3]
c) [2, 4, 6]
d) [3, 6, 9]
Answer: b) [1, 2, 3, 1, 2, 3]
12. Which list method is used to remove and return the last
element of a list?
a) remove()
b) pop()
c) delete()
d) extract()
Answer: b) pop()
13. What happens when you use the extend() method to add
elements to a list?
a) It adds a single element to the end of the list.
b) It inserts multiple elements at a specific index in the list.
c) It appends multiple elements to the end of the list.
d) It replaces the existing elements with new elements.
Answer: c) It appends multiple elements to the end of the list.
14. Which method is used to count the number of occurrences of
a specific element in a list?
a) count()
b) occurrences()
c) frequency()
d) total()
Answer: a) count()
Lists | 57

15. What does it mean for a list to be mutable?


a) It can be converted to a different data type.
b) It cannot be modified after creation.
c) It can only contain elements of the same data type.
d) It can be changed or modified after creation.
Answer: d) It can be changed or modified after creation.
5
Dictionaries and Structuring Data

Dictionaries are an essential tool in Python for organizing and


manipulating data effectively. Understanding their concepts and
capabilities will greatly enhance your ability to work with complex
data structures and solve real-world problems. This chapter covers
the basics of dictionaries, including their creation, accessing values
using keys, modifying values, and adding new key-value pairs.
We also explore the ‘pprint’ module for pretty printing dictionaries
and learn how to use dictionaries to model real-world objects and
relationships. By utilizing dictionaries, you can create sophisticated
data structures that accurately represent real-world scenarios.
Dictionaries are particularly powerful when combined with other
data types and structures, such as lists, tuples, or even nested
dictionaries.

5.1 THE DICTIONARY DATA TYPE


In Python, dictionaries are a versatile data type used to store
key-value pairs. Unlike lists or tuples, which use numerical indexes
to access elements, dictionaries use keys as the means of retrieval.
To create a dictionary, you use curly braces ({}) and separate the
key-value pairs with colons (:). Let’s create a dictionary representing
a person’s information:
person = {
Dictionaries and Structuring Data | 59

‘name’: ‘John’,
‘age’: 30,
‘city’: ‘New York’
}
In this example, the dictionary ‘person’ has three key-value
pairs: ‘name’: ‘John’, ‘age’: 30, and ‘city’: ‘New York’. You can access
the values using the respective keys:

print(person[‘name’])
Output: John
print(person[‘age’])
Output: 30
print(person[‘city’])
Output: New York

Dictionaries are mutable, meaning you can modify their values.


To change the value associated with a specific key, simply assign a
new value to it:

person[‘age’] = 35 #Changing the age to 35


print(person[‘age’])
Output: 35

You can also add new key-value pairs to a dictionary by assigning


a value to a previously unused key:

person[‘occupation’] = ‘Engineer’ # Adding a new key-value pair


print(person)
Output: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’, ‘occupation’:
‘Engineer’}
60 | Python Programming

If you try to access a key that doesn’t exist in the dictionary,


Python raises a KeyError. To avoid this, you can use the ‘get()’
method, which allows you to provide a default value if the key is
not found:
print(person.get(‘gender’, ‘Unknown’))
Output: Unknown

5.2 PRETTY PRINTING


When dictionaries contain a large number of key-value pairs,
printing them in a simple format may result in a messy output.
To achieve more readable results, you can use the ‘pprint’
module, which stands for “pretty print.” The ‘pprint’ module provides
a ‘pprint()’ function that formats the output more elegantly.
To use ‘pprint’, you need to import it first:
import pprint
Let’s create a dictionary with several key-value pairs:
fruits = {
‘apple’: 3,
‘banana’: 2,
‘orange’: 5,
‘grape’: 1,
‘watermelon’: 2
}

To print the ‘fruits’ dictionary using ‘pprint’, call the ‘pprint()’


function:
pprint.pprint(fruits)
The output will be neatly formatted and easy to read, even for
larger dictionaries. Here’s an example output:
{‘apple’: 3,
‘banana’: 2,
Dictionaries and Structuring Data | 61

‘grape’: 1,
‘orange’: 5,
‘watermelon’: 2}
The ‘pprint’ module also provides other functions, such as
‘pformat()’ that returns the formatted string instead of printing it
directly.

5.3 USING DATA STRUCTURES TO MODEL REAL-WORLD


THINGS
Dictionaries are excellent for modelling real-world objects and
their properties. For instance, let’s consider a simple inventory
management system for a grocery store. We can represent each
item’s details using a dictionary:
item1 = {
‘name’: ‘apple’,
‘price’: 0.5,
‘quantity’: 10
}
item2 = {
‘name’: ‘banana’,
‘price’: 0.25,
‘quantity’: 15
}
item3 = {
‘name’: ‘orange’,
‘price’: 0.35,
‘quantity’: 5
}
In this example, each item is represented by a dictionary
containing the ‘name’, ‘price’, and ‘quantity’ as key-value pairs.
We can organize these item dictionaries into a list to represent
the entire inventory:
62 | Python Programming

inventory = [item1, item2, item3]


Now, we have an ‘inventory’ list that contains the dictionaries
representing individual items. To access specific details of an item
in the inventory, you can use indexing and key access together:
print(inventory[0][‘name’])
Output: apple
print(inventory[1][‘price’])
Output: 0.25
print(inventory[2][‘quantity’])
Output: 5
This allows us to retrieve and manipulate data in a structured
manner.
Dictionaries also allow you to model complex relationships
between objects by using nested dictionaries or lists.
For example, let’s consider a scenario where we want to represent
a student database. Each student has multiple subjects, and each
subject has its own details, such as the teacher’s name and the
student’s grade:

student1 = {
‘name’: ‘John’,
‘subjects’: {
‘Maths’: {
‘teacher’: ‘Mr. Smith’,
‘grade’: ‘A’
},
‘English’: {
‘teacher’: ‘Ms. Johnson’,
‘grade’: ‘B’
}
}
}
Dictionaries and Structuring Data | 63

student2 = {
‘name’: ‘Alice’,
‘subjects’: {
‘Maths’: {
‘teacher’: ‘Mr. Johnson’,
‘grade’: ‘B’
},
‘Science’: {
‘teacher’: ‘Mrs. Adams’,
‘grade’: ‘A’
}
}
}
In this example, each student is represented by a dictionary
containing the ‘name’ and ‘subjects’ as key-value pairs. The
‘subjects’ key further maps to another dictionary, representing the
student’s subjects and their respective details.

To access specific information, you can use nested key access:


print(student1[‘name’])
Output: John
print(student2[‘subjects’][‘Maths’][‘teacher’])
Output: Mr. Johnson
print(student2[‘subjects’][‘Science’][‘grade’])
Output: A
This demonstrates how dictionaries allow us to model real-world
relationships and organize data effectively.
64 | Python Programming

EXERCISE

Short Answer Questions (2 Marks)

1. What is the dictionary data type in Python?


2. How can dictionaries be used to store and retrieve data?
3. What is the purpose of pretty printing in Python?
4. How does pretty printing help in displaying dictionary data?
5. How can dictionaries be used to model real-world things in
Python?

Long Answer Questions (5 Marks)

1. Explain the dictionary data type in Python and provide an


example of its usage.
2. Discuss the importance of dictionaries in storing and retrieving
data, highlighting their advantages over other data structures.
3. Describe the concept of pretty printing in Python and explain
how it can be applied to dictionaries.
4. Give an example of using pretty printing to display a complex
dictionary with nested structures. Explain the benefits of
this approach.
5. Elaborate on the role of data structures, specifically
dictionaries, in modeling real-world things. Provide examples
of how dictionaries can be used to represent various entities
and their attributes.

Multiple Choice Questions

1. Which of the following data types in Python is used to store


key-value pairs?
a. List
b. Tuple
c. Dictionary
d. Set
Answer: c
Dictionaries and Structuring Data | 65

2. What is the key requirement for keys in a dictionary?


a. They must be integers.
b. They must be strings.
c. They must be unique.
d. They must be sorted.
Answer: c
3. How are values accessed in a dictionary?
a. Using indexes
b. Using keys
c. Using values
d. Using attributes
Answer: b
4. Which Python module provides the “pprint” function for
pretty printing dictionaries?
a. math
b. random
c. pprint
d. os
Answer: c
5. What is the purpose of pretty printing a dictionary?
a. To improve its performance
b. To make it more readable
c. To reduce memory usage
d. To sort the keys alphabetically
Answer: b
6. Which symbol is used to access a value in a dictionary using
its key?
a. .
b. :
c. [
d. (
Answer: b
66 | Python Programming

7. In Python, can dictionaries have duplicate values?


a. Yes
b. No
Answer: a
8. Which of the following is true about dictionary keys in
Python?
a. Keys can be mutable.
b. Keys cannot be modified once assigned.
c. Keys can be of any data type.
d. Keys are automatically sorted in ascending order.
Answer: b
9. How can you check if a key exists in a dictionary?
a. Using the “in” keyword
b. Using the “exists()” function
c. Using the “has_key()” method
d. Using the “contains()” method
Answer: a
10. What happens if you try to access a key that does not exist
in a dictionary?
a. An exception is raised.
b. The dictionary is automatically resized.
c. The value None is returned.
d. The dictionary is sorted.
Answer: a
11. Which of the following is true about dictionaries in Python?
a. They preserve the order of elements.
b. They are implemented as a linked list.
c. They have a fixed size once created.
d. They are not iterable.
Answer: a
Dictionaries and Structuring Data | 67

12. What is the time complexity of accessing a value in a


dictionary using its key?
a. O(1)
b. O(log n)
c. O(n)
d. O(n log n)
Answer: a
13. Can a dictionary in Python contain multiple values for the
same key?
a. Yes
b. No
Answer: b
14. Which of the following operations can be performed on a
dictionary in Python?
a. Sorting
b. Appending
c. Concatenation
d. Indexing
Answer: a
15. What is the difference between a dictionary and a set in
Python?
a. Dictionaries store unordered data, while sets store ordered
data.
b. Dictionaries store key-value pairs, while sets store only
unique values.
c. Dictionaries can be modified after creation, while sets are
immutable.
d. Dictionaries have a fixed size, while sets can dynamically
resize.
Answer: b
6
Strings

Strings are an essential data type in Python that allow us to work


with textual data. In this chapter, we will explore various techniques
to manipulate strings, including string concatenation, slicing, and
formatting. Understanding these operations will enable you to
efficiently process and transform strings in your Python programs.
By mastering these techniques, you’ll have a solid foundation for
working with strings in Python.

6.1 CREATING STRINGS


In most programming languages, strings can be created by
enclosing characters within quotation marks. Here’s an example in
Python:
name = “John Doe”
In this case, the variable name holds a string value “John Doe”.
Similarly, strings can be created using double quotes, as in “John
Doe”, or triple quotes for multi-line strings, as in “””This is a
multi-line string.”””

6.1.1 String Concatenation

String concatenation is the process of combining two or more


strings into a single string. In Python, concatenation is achieved
using the “+” operator. Let’s take a look at an example:
Strings | 69

first_name = “John”
last_name = “Doe”
full_name = first_name + “ “ + last_name
print(full_name)
Output: John Doe
In this example, we concatenate the first name, a space character,
and the last name to create a full name string. The resulting string
is then printed.

6.1.2 String Slicing

String slicing allows us to extract a portion of a string by


specifying a range of indices.
The syntax for string slicing is
string[start:end:step],
where start is the index to start slicing from, end is the index
to stop slicing at (exclusive), and step is an optional parameter
indicating the step size. Consider the following example:
text = “Hello, World!”
substring = text[7:12]
print(substring)
Output: World
In this example, we slice the string text to extract the substring
“World” by specifying the start index as 7 and the end index as 12.
The resulting substring is then printed.

6.1.3 String Formatting

String formatting allows us to create dynamic strings by inserting


values into predefined placeholders. Python provides multiple
approaches for string formatting, including the “%” operator and
the format() method. Let’s explore both methods:
Using the “%” Operator:
The “%” operator allows us to format strings using placeholders.
70 | Python Programming

The “%” operator is followed by a format specifier, such as “%s”


for strings, “%d” for integers, and “%f” for floating-point numbers.
Here’s an example:
name = “Alice”
age = 25
message = “My name is %s and I am %d years old.” % (name,
age)
print(message)
Output: My name is Alice and I am 25 years old.
In this example, we use the “%” operator to format the string
message. The “%s” and “%d” placeholders are replaced by the
values of name and age, respectively.
Using the format() Method:
The format() method provides a more flexible approach to string
formatting.
It allows us to specify placeholders inside curly braces and pass
the corresponding values as arguments to the format() method.
Here’s an example:
name = “Bob”
age = 30
message = “My name is {} and I am {} years old.”.format(name,
age)
print(message)
Output: My name is Bob and I am 30 years old.
In this example, we use the format() method to format the string
message. The curly braces “{}” act as placeholders, and the values
of name and age are passed as arguments to the format() method.

6.2 USEFUL STRING METHODS


6.2.1 Changing Case

Python provides several methods to change the case of strings.


These methods include lower(), upper(), and capitalize(). Let’s see
how they work:
Strings | 71

lower():
text = “Hello, World!”
lowercase_text = text.lower()
print(lowercase_text)
Output: hello, world!
upper():
The upper() method converts all characters in a string to
uppercase. Here’s an example:
text = “Hello, World!”
uppercase_text = text.upper()
print(uppercase_text)
Output: HELLO, WORLD!
capitalize():
The capitalize() method converts the first character of a string
to uppercase and the rest to lowercase. Here’s an example:
text = “hello, world!”
capitalized_text = text.capitalize()
print(capitalized_text)
Output: Hello, world!

6.2.2 Finding Substrings

Python provides methods to find the position of substrings


within a string. These methods include find(), index(), and count().
Let’s explore them:
a) find():
The find() method returns the index of the first occurrence of a
substring within a string. If the substring is not found, it returns
-1. Here’s an example:
text = “Hello, World!”
index = text.find(“World”)
print(index)
Output: 7
72 | Python Programming

index():
The index() method works similarly to find(), but if the substring
is not found, it raises a ValueError instead of returning -1. Here’s
an example:
text = “Hello, World!”
index = text.index(“World”)
print(index)
Output: 7
count():
The count() method returns the number of occurrences of a
substring within a string. Here’s an example:
text = “Hello, World!”
occurrences = text.count(“l”)
print(occurrences)
Output: 3

6.2.3 Replacing Substrings

Python provides the replace() method to replace occurrences of


a substring with a new substring. Here’s an example:
text = “Hello, World!”
new_text = text.replace(“World”, “Python”)
print(new_text)
Output: Hello, Python!
In this example, the replace() method replaces the substring
“World” with “Python” in the original string.
Strings | 73

EXERCISE

Short Answer Questions (2 Marks)

1. How can you determine the length of a string in Python?


2. What is string concatenation, and how can it be achieved in
Python?
3. How do you check if a specific substring exists within a string
in Python?
4. What is the difference between the upper() and lower() string
methods in Python?
5. How can you remove leading and trailing whitespace from a
string in Python?

Long Answer Questions (5 Marks)

1. Discuss the concept of indexing in Python strings and


explain how it can be used to access individual characters or
subsequences within a string. Provide examples to support
your explanation.
2. Explore the various string methods available in Python, such
as split(), join(), replace(), and find(). Explain each method’s
functionality, syntax, and common use cases, providing code
examples where applicable.
3. Explain the process of string formatting in Python, discussing
both the traditional % operator approach and the newer
f-strings. Compare and contrast their usage, highlighting
any advantages or disadvantages of each method.
4. Describe the functionality and significance of the startswith()
and endswith() methods in Python string manipulation.
Provide examples to demonstrate how these methods can be
used to check the beginning or ending of a string for specific
patterns.
5. Discuss the usefulness and applications of regular
expressions (regex) in Python string manipulation. Explain
the basic syntax and demonstrate how regex can be used to
74 | Python Programming

search for and manipulate specific patterns within strings,


providing relevant code examples.

Multiple Choice Questions


1. Which of the following is true about strings in Python?
a. Strings are mutable
b. Strings can contain only numeric values
c. Strings are enclosed in double quotation marks
d. Strings cannot be concatenated
Answer: c. Strings are enclosed in double quotation marks
2. What does the len() function return when applied to a string?
a. Number of characters in the string
b. Index of the last character in the string
c. Number of words in the string
d. Position of the first occurrence of a character in the string
Answer: a. Number of characters in the string
3. Which operator is used for string concatenation in Python?
a. +
b. -
c. /
d. *
Answer: a. +
4. How can you convert a string to uppercase in Python?
a. upper()
b. capitalize()
c. swapcase()
d. title()
Answer: a. upper()
Strings | 75

5. Which method can be used to split a string into a list of


substrings based on a specified separator?
a. split()
b. join()
c. replace()
d. find()
Answer: a. split()
6. What does the find() method return if the specified substring
is not found in the string?
a. -1
b. 0
c. None
d. ValueError
Answer: a. -1
7. Which method can be used to replace occurrences of a
substring in a string with another substring?
a. replace()
b. find()
c. split()
d. upper()
Answer: a. replace()
8. What is the purpose of the strip() method in Python?
a. Converts a string to uppercase
b. Removes leading and trailing whitespace from a string
c. Splits a string into a list of substrings
d. Reverses the characters in a string
Answer: b. Removes leading and trailing whitespace from a
string
76 | Python Programming

9. Which method can be used to check if a string starts with a


specific substring?
a. startswith()
b. endswith()
c. find()
d. replace()
Answer: a. startswith()
10. How can you join a list of strings into a single string using a
specified separator?
a. join()
b. split()
c. replace()
d. append()
Answer: a. join()
11. What does the isdigit() method return if a string consists only
of numeric digits?
a. True
b. False
c. None
d. Error
Answer: a. True
12. Which method can be used to count the occurrences of a
specific substring in a string?
a. count()
b. find()
c. replace()
d. upper()
Answer: a. count()
Strings | 77

13. Which method can be used to check if all characters in a


string are alphabetic?
a. isalpha()
b. isnumeric()
c. isdigit()
d. islower()
Answer: a. isalpha()
14. What is the purpose of the title() method in Python?
a. Converts the first character of each word to uppercase
b. Converts all characters to uppercase
c. Removes leading and trailing whitespace from a string
d. Reverses the characters in a string
Answer: a. Converts the first character of each word to
uppercase
15. Which method can be used to determine the index of the first
occurrence of a specific substring in a string?
a. find()
b. replace()
c. split()
d. upper()
Answer: a. find()
7
Reading and Writing Files

In this chapter, we will explore the fundamental concepts


and techniques involved in reading and writing files in Python.
Working with files is essential for processing and storing data,
and understanding how to manipulate files is a crucial skill for
any programmer. We will cover various aspects, including file
paths, the os.path module, the file reading/writing process, saving
variables with the shelve module, and using the pprint.pformat()
function. By the end of this chapter, you will have a comprehensive
understanding of file operations in Python.

7.1 FILES AND FILE PATHS


Files are a way to store and organize data on a computer. In
Python, file objects are used to interact with external files. Before
working with a file, you must open it using the open() function,
which requires the file path as a parameter. A file path is the address
or location of a file on the file system. It can be represented as an
absolute path or a relative path.
An absolute file path provides the complete location of a file from
the root directory. For example:
file_path = ‘/Users/username/Documents/example.txt’
Reading and Writing Files | 79

A relative file path is relative to the current working directory of


the script or program. For example:
file_path = ‘data/example.txt’
Python provides several functions to manipulate and extract
information from file paths. The os.path module is particularly
useful for these tasks.

7.2 THE os.path MODULE


The os.path module in Python provides functions for working
with file paths. Let’s explore some of the commonly used functions:
os.path.join(path, *paths):
This function joins one or more path components intelligently,
using the correct path separator for the operating system. It is
useful for constructing file paths dynamically.
import os
path = os.path.join(‘data’, ‘file.txt’)
print(path)
Output: data/file.txt
os.path.exists(path):
This function checks if a file or directory exists at the specified
path and returns a boolean value.
import os
file_path = ‘data/file.txt’
if os.path.exists(file_path):
print(“File exists.”)
else:
print(“File does not exist.”)
os.path.isdir(path):
This function checks if the path corresponds to a directory.
import os
directory_path = ‘data’
if os.path.isdir(directory_path):
80 | Python Programming

print(“Path is a directory.”)
else:
print(“Path is not a directory.”)
os.path.isfile(path):
This function checks if the path corresponds to a regular file.
import os
file_path = ‘data/file.txt’
if os.path.isfile(file_path):
print(“Path is a file.”)
else:
print(“Path is not a file.”)

7.3 THE FILE READING/WRITING PROCESS


To read or write data to a file, you need to follow a standard
process. Let’s understand this process step by step:

7.3.1 Opening a file

To open a file, you use the open() function, which takes the file
path and a mode parameter as arguments. The mode determines
whether the file should be opened for reading, writing, or both. The
most commonly used modes are:
‘r’: Read mode (default). Opens the file for reading.
‘w’: Write mode. Opens the file for writing. Creates a new file if it
doesn’t exist, and truncates (empties) the file if it exists.
‘a’: Append mode. Opens the file for writing, but appends data to
the end instead of truncating it.
‘x’: Exclusive creation mode. Creates a new file but raises an
error if it already exists.
file_path = ‘data/file.txt’
# Open the file in write mode
file = open(file_path, ‘w’)
Reading and Writing Files | 81

7.3.2 Reading from a file

Once the file is open for reading, you can read its contents. The
read() method is used to read the entire contents of the file, while
readline() reads one line at a time, and readlines() reads all lines
and returns them as a list.
file_path = ‘data/file.txt’

# Open the file in read mode


file = open(file_path, ‘r’)

# Read the entire contents of the file


content = file.read()
print(content)

# Read one line at a time


line = file.readline()
print(line)

# Read all lines and store them in a list


lines = file.readlines()
print(lines)

# Close the file


file.close()

7.3.3 Writing to a file

To write data to a file, you need to open it in write mode or


append mode. Use the write() method to write data to the file. If
the file already exists, opening it in write mode will overwrite the
existing content. Opening it in append mode will add data to the
end of the file.
82 | Python Programming

file_path = ‘data/file.txt’

# Open the file in write mode


file = open(file_path, ‘w’)

# Write data to the file


file.write(‘Hello, world!\n’)
file.write(‘This is a new line.’)

# Close the file


file.close()

7.3.4 Closing a file

After you finish reading or writing a file, it is important to close


it using the close() method. Closing the file ensures that all data is
written and resources are freed.
file_path = ‘data/file.txt’

# Open the file in read mode


file = open(file_path, ‘r’)

# Read the contents of the file


content = file.read()
print(content)

# Close the file


file.close()
Reading and Writing Files | 83

7.4 SAVING VARIABLES WITH THE SHELVE MODULE


The shelve module provides a convenient way to save and
retrieve Python variables in a file. It allows you to store complex
data structures, such as lists and dictionaries, without worrying
about serialization and deserialization. The shelve module uses the
same basic operations as a dictionary.

Let’s explore how to use the shelve module:


import shelve
# Open a shelve file
shelf_file = shelve.open(‘data/variables’)

# Store variables in the shelf


shelf_file[‘name’] = ‘John Doe’
shelf_file[‘age’] = 30
shelf_file[‘favorite_fruits’] = [‘apple’, ‘banana’, ‘orange’]

# Close the shelf file


shelf_file.close()
The above code creates a shelve file named ‘variables’ and stores
various variables in it. You can access the stored variables just like
you would access dictionary values.
import shelve
# Open the shelve file
shelf_file = shelve.open(‘data/variables’)

# Retrieve variables from the shelf


name = shelf_file[‘name’]
age = shelf_file[‘age’]
favorite_fruits = shelf_file[‘favorite_fruits’]
84 | Python Programming

# Close the shelf file


shelf_file.close()

print(name)
Output: John Doe
print(age)
Output: 30
print(favorite_fruits)
Output: [‘apple’, ‘banana’, ‘orange’]

7.5 SAVING VARIABLES WITH THE pprint.pformat() FUNCTION


The pprint.pformat() function from the pprint module allows
you to save variables in a more human-readable format. It converts
variables into formatted string representations, making them easier
to read and understand.

Let’s see an example of using pprint.pformat():


import pprint
# Variable to save
person = {
‘name’: ‘John Doe’,
‘age’: 30,
‘favorite_fruits’: [‘apple’, ‘banana’, ‘orange’]
}

# Save the variable using pprint.pformat()


formatted_person = pprint.pformat(person)

# Write the formatted variable to a file


file_path = ‘data/person.txt’
Reading and Writing Files | 85

file = open(file_path, ‘w’)


file.write(formatted_person)
file.close()
In the above example, the pprint.pformat() function is used to
convert the person variable into a formatted string representation.
The formatted variable is then written to a file named ‘person.txt’.
86 | Python Programming

EXERCISE

Short Answer Questions (2 Marks)

1. What is the purpose of file paths in Python file operations?


2. How can you determine if a path corresponds to a directory
using the os.path module?
3. What is the difference between opening a file in write mode
and append mode?
4. Why is it important to close a file after reading or writing
operations?
5. What does the shelve module provide in terms of saving
variables in Python?

Long Answer Questions (5 Marks)

1. Explain the process of reading and writing files in Python,


including the necessary steps and functions involved.
2. How can the os.path module be utilized to manipulate file
paths and perform operations such as joining paths, checking
existence, and determining if a path corresponds to a file or
directory?
3. Discuss the advantages and use cases of using the shelve
module for saving variables in Python. Provide examples of
storing and retrieving variables using the shelve module.
4. Explore the functionality and benefits of the pprint.pformat()
function in the context of saving variables. How does it
contribute to creating a more human-readable format?
Provide an example demonstrating the usage of pprint.
pformat() to save variables.
5. Compare and contrast the shelve module and the pprint.
pformat() function in terms of their approaches to saving
variables. Discuss their strengths, limitations, and suitable
scenarios for their application in Python file operations.
Reading and Writing Files | 87

Multiple Choice Questions

1. Which function is used to open a file in Python?


a. open_file()
b. read_file()
c. write_file()
d. open()
Answer: d. open()
2. What is the purpose of the os.path module in Python?
a. It provides functions for file input/output operations.
b. It handles file compression and decompression.
c. It manipulates and extracts information from file paths.
d. It serializes and deserializes Python variables.
Answer: c. It manipulates and extracts information from file
paths.
3. Which mode should be used to open a file for reading in
Python?
a. ‘r’
b. ‘w’
c. ‘a’
d. ‘x’
Answer: a. ‘r’
4. What does the read() method do when called on a file object?
a. Reads the entire contents of the file.
b. Reads one line at a time from the file.
c. Reads all lines and returns them as a list.
d. Reads the specified number of characters from the file.
Answer: a. Reads the entire contents of the file.
88 | Python Programming

5. Which method is used to write data to a file in Python?


a. write()
b. read()
c. append()
d. save()
Answer: a. write()
6. What is the purpose of the shelve module in Python?
a. It provides functions for file compression and
decompression.
b. It handles binary file operations.
c. It facilitates saving and retrieving Python variables in a
file.
d. It formats variables into a more human-readable
representation.
Answer: c. It facilitates saving and retrieving Python variables
in a file.
7. How can you open a shelve file in Python?
a. Using the open_file() function
b. Using the open_shelf() function
c. Using the shelve.open() function
d. Using the shelve_file() function
Answer: c. Using the shelve.open() function
8. Which function is used to convert variables into a more
human-readable format in Python?
a. pprint.pprint()
b. pprint.format()
c. pprint.pformat()
d. pprint.readable()
Answer: c. pprint.pformat()
Reading and Writing Files | 89

9. What is the purpose of the pprint module in Python?


a. It provides functions for file input/output operations.
b. It handles file compression and decompression.
c. It manipulates and extracts information from file paths.
d. It formats variables into a more human-readable
representation.
Answer: d. It formats variables into a more human-readable
representation.
10. Which module should be imported to use file path
manipulation functions in Python?
a. os
b. shelve
c. pprint
d. pathlib
Answer: a. os
11. What does the os.path.join() function do?
a. Joins two strings together.
b. Joins two file paths together.
c. Joins two lists together.
d. Joins two dictionaries together.
Answer: b. Joins two file paths together.
12. Which function can be used to check if a file or directory
exists at a given path?
a. os.path.exists()
b. os.path.isfile()
c. os.path.isdir()
d. os.path.validate()
Answer: a. os.path.exists()
90 | Python Programming

13. Which mode should be used to open a file for writing in


Python and truncate the existing content?
a. ‘r’
b. ‘w’
c. ‘a’
d. ‘x’
Answer: b. ‘w’
14. What is the purpose of the readlines() method in Python?
a. Reads the entire contents of the file.
b. Reads one line at a time from the file.
c. Reads all lines and returns them as a list.
d. Reads the specified number of characters from the file.
Answer: c. Reads all lines and returns them as a list.
15. Which method should be used to close a file after reading or
writing operations in Python?
a. close()
b. end()
c. finish()
d. terminate()
Answer: a. close()
8
Organizing Files

In this chapter, we will explore different techniques and


modules available in Python for organizing files. We will cover the
shutil module, which provides a high-level interface for file and
directory operations, as well as the zipfile module, which allows
us to compress and extract files. Additionally, we will learn about
walking through directory trees and performing operations on
multiple files.By leveraging these modules and techniques, you can
efficiently organize and manipulate files and directories in your
Python projects, automate file management tasks, and package
files for distribution or backup purposes.

8.1 THE SHUTIL MODULE


The shutil (short for shell utility) module in Python provides a set
of high-level file operations that simplify the process of working with
files and directories. It offers functions to copy, move, rename, and
delete files and directories. These operations are especially useful
when you need to automate file management tasks or organize data
within your applications.

8.1.1 Copying Files

To copy a file using the shutil module, we can use the copy()
function. This function takes two arguments: the source file path
92 | Python Programming

and the destination folder path. It creates a new copy of the file in
the destination folder, while preserving the original file.
import shutil

source_file = ‘/path/to/source/file.txt’
destination_folder = ‘/path/to/destination/’

shutil.copy(source_file, destination_folder)
By utilizing the copy() function, you can easily duplicate files for
backup purposes or to process them separately without modifying
the original source.

8.1.2 Moving and Renaming Files

The shutil module also provides a function called move() that


allows us to move files from one location to another. We can also
use this function to rename files.
The move() function takes two arguments: the source file path
and the destination file path. If the destination path is a folder,
the file will be moved to that folder with the same name. If the
destination path includes a new filename, the file will be moved and
renamed accordingly.
import shutil
source_file = ‘/path/to/source/file.txt’
destination_folder = ‘/path/to/destination/new_file.txt’
shutil.move(source_file, destination_folder)
This functionality is particularly useful when reorganizing files
or when renaming files based on specific criteria.

8.1.3 Deleting Files and Directories

To delete files and directories, we can use the os.remove() and


os.rmdir() functions from the built-in os module. However, the
shutil module provides an easier way to delete files and directories
using the shutil.rmtree() function.
Organizing Files | 93

The rmtree() function recursively deletes a directory and all


its contents, including subdirectories and files. It saves you from
writing repetitive code to handle file deletion manually.
import shutil
folder_to_delete = ‘/path/to/folder’
shutil.rmtree(folder_to_delete)
With the rmtree() function, you can swiftly remove unnecessary
files or directories, freeing up storage space and keeping your file
system organized.

8.2 WALKING A DIRECTORY TREE


Walking through a directory tree means traversing all the
directories and subdirectories within a given path and performing
specific operations on files.
The os module in Python provides the os.walk() function, which
allows us to iterate over all the directories, subdirectories, and files
within a given root folder.
By leveraging the os.walk() function, you can easily perform
batch operations on multiple files, such as searching for specific
file types, analyzing file contents, or performing modifications. Let’s
look at an example:
import os
root_folder = ‘/path/to/root/folder’
for root, directories, files in os.walk(root_folder):
for file in files:
file_path = os.path.join(root, file)
# Perform operations on file_path
In this example, os.walk() returns a generator object that
produces a tuple for each directory it traverses.
The tuple contains three elements: the current directory path
(root), a list of subdirectories (directories), and a list of files (files).
By iterating over these values, you can access and process each
file individually.
94 | Python Programming

8.3 COMPRESSING FILES WITH THE ZIPFILE MODULE


The zipfile module in Python allows us to create, read, and extract
files from ZIP archives. It provides a simple interface to compress
files and directories, making it easier to store and transfer data
efficiently.
This module is particularly useful when dealing with large sets
of files or when you need to package files for distribution.
To compress files using the zipfile module, follow these steps:
•• Specify the folder or file you want to compress.
•• Create a new ZIP archive using the ZipFile() function.
•• Iterate over the files within the specified folder and add them
to the archive using the write () method.
Here’s an example of compressing files using the zipfile module:
import zipfile
folder_to_compress = ‘/path/to/folder’
output_zip = ‘/path/to/output/archive.zip’
with zipfile.ZipFile(output_zip, ‘w’) as zipf:
for root, directories, files in os.walk(folder_to_compress):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, arcname=os.path.relpath(file_path,
folder_to_compress))
In this example, we create a new ZIP archive using the ZipFile()
function and open it in write mode (‘w’). Then, using the write()
method, we iterate over the files in the specified folder and add
them to the archive. The arcname parameter specifies the name
of the file or directory within the ZIP archive. By using os.path.
relpath(), we ensure that the paths stored in the archive are relative
to the original folder.
Organizing Files | 95

EXERCISE

Short Answer Questions (2 Marks)

1. What does the shutil module in Python provide?


2. How can you use the shutil module to copy a file?
3. What is the purpose of walking through a directory tree?
4. How can you delete a file or directory using the shutil module?
5. What does the zipfile module in Python allow you to do?

Long Answer Questions (5 Marks)

1. Explain the main functionalities of the shutil module in


Python and provide examples of how it can be used for file
and directory operations.
2. Describe the process of walking through a directory tree
using the os module in Python. Explain the significance
of the root, directories, and files variables returned by the
os.walk() function.
3. Discuss the steps involved in compressing files and directories
using the zipfile module in Python. Provide a detailed example
illustrating how to create a ZIP archive and add files to it.
4. Compare and contrast the shutil.rmtree() function with the
os.remove() and os.rmdir() functions for deleting files and
directories. Highlight the advantages of using shutil.rmtree()
in certain scenarios.
5. Explore the potential use cases and benefits of organizing
files and directories within a Python project. Discuss how the
techniques covered in this chapter, such as using the shutil
module and walking through directory trees, can contribute
to better file management and code organization.

Multiple Choice Questions

1. Which module in Python provides high-level file and directory


operations?
a. os module
b. sys module
96 | Python Programming

c. shutil module
d. zipfile module
Answer: c
2. What operation can be performed using the shutil module?
a. Copying files
b. Deleting files and directories
c. Moving files and directories
d. All of the above
Answer: d
3. What function from the shutil module is used to copy a file?
a. shutil.copy()
b. shutil.move()
c. shutil.delete()
d. shutil.compress()
Answer: a
4. What does walking through a directory tree mean?
a. Traversing all the directories and files within a directory
b. Renaming all the files in a directory
c. Compressing all the files in a directory
d. Deleting all the directories in a directory tree
Answer: a
5. Which module in Python provides the os.walk() function?
a. os module
b. shutil module
c. zipfile module
d. sys module
Answer: a
6. What does the os.walk() function return?
a. List of files in a directory
b. List of subdirectories in a directory
Organizing Files | 97

c. Tuple of (root, directories, files)


d. None of the above
Answer: c
7. Which module in Python allows us to compress and extract
files from ZIP archives?
a. os module
b. shutil module
c. zipfile module
d. sys module
Answer: c
8. What is the purpose of the arcname parameter in the zipfile.
write() function?
a. Specifies the name of the ZIP archive
b. Specifies the name of the file or directory within the ZIP
archive
c. Specifies the compression level for the file
d. Specifies the file permissions for the file
Answer: b
9. How can you delete a file or directory using the shutil module?
a. shutil.delete(file_path)
b. shutil.move(file_path, trash_bin)
c. shutil.rmtree(folder_path)
d. shutil.compress(file_path)
Answer: c
10. Which function from the shutil module can be used to move
and rename files?
a. shutil.copy()
b. shutil.move()
c. shutil.rename()
d. shutil.delete()
Answer: b
98 | Python Programming

11. What is the advantage of using shutil.rmtree() over os.rmdir()


for deleting directories?
a. shutil.rmtree() can delete directories with contents, while
os.rmdir() can only delete empty directories.
b. shutil.rmtree() is faster than os.rmdir() for deleting
directories.
c. shutil.rmtree() provides an undo option, while os.rmdir()
does not.
d. shutil.rmtree() supports wildcard deletion, while os.rmdir()
does not.
Answer: a
12. Which module is used for file compression and extraction in
Python?
a. os module
b. shutil module
c. compress module
d. zipfile module
Answer: d
13. Which function from the zipfile module is used to create a
new ZIP archive?
a. zipfile.create()
b. zipfile.open()
c. zipfile.write()
d. zipfile.ZipFile()
Answer: d
14. What is the purpose of the arcname parameter in the zipfile.
write() function?
a. It specifies the destination folder for the file.
b. It specifies the name of the file within the ZIP archive.
c. It specifies the compression level for the file.
d. It specifies the password for the ZIP archive.
Answer: b
Organizing Files | 99

15. Which module provides a high-level interface for file and


directory operations, including copying, moving, and deleting?
a. os module
b. sys module
c. shutil module
d. zipfile module
Answer: c
9
Web Scraping

9.1 PROJECT: MAPIT.PY WITH THE WEB BROWSER MODULE


In today’s digital age, the web is an abundant source of information,
offering vast amounts of data on various topics. As a programmer
or data enthusiast, being able to extract and analyse this data
efficiently is a valuable skill. This is where web scraping comes into
play, empowering us to extract data from websites and transform it
into a structured format for further analysis and processing.
Web scraping is a powerful technique that allows us to extract
data from websites and automate repetitive tasks. In this chapter,
we will explore the web browser module in Python and build a
project called MAPIT.PY, which utilizes web scraping to retrieve
map coordinates based on user input. We will dive into the details
of web scraping, learn about the web browser module, and develop
a practical application that showcases its capabilities.
By the end of this chapter, you will have gained the necessary
skills and knowledge to embark on web scraping projects with
confidence. You will be equipped with the tools to interact with web
pages using the web browser module, download files from the web
using the requests module, manage downloaded files efficiently,
and extract relevant data from HTML documents.
Web Scraping | 101

So, let’s dive into the world of web scraping and unleash the
power of extracting valuable information from the vast expanse of
the internet!

9.1.1 What is Web Scraping?


Web scraping is the process of automatically extracting data from
websites using scripts or programs. It involves accessing web pages,
parsing the HTML content, and extracting the desired information.
Web scraping can be used for various purposes, including data
analysis, research, and automation.

9.1.2 Legality and Ethics of Web Scraping

Before diving into web scraping, it’s essential to understand the


legal and ethical aspects. While web scraping itself is not illegal, the
legality may vary depending on the website’s terms of service and
the data being scraped. It’s crucial to respect the website’s policies,
be mindful of the frequency of requests, and not overload the server
with excessive traffic.

9.2 INTRODUCTION TO THE WEB BROWSER MODULE


The web browser module in Python provides a powerful and
convenient way to automate web interactions and perform tasks
such as web scraping, web testing, and web automation. With this
module, developers can control a web browser programmatically,
interact with web elements, and extract data from websites. In this
introduction, we will explore the basic features and usage of the
web browser module in Python.
Installation: To use the web browser module in Python, you
need to install a package called Selenium. Selenium is a popular
open-source library that provides a Python interface to control web
browsers. You can install Selenium using the pip package manager
by running the following command:
pip install selenium
Additionally, you need to download the appropriate web driver
executable for the browser you intend to automate. Selenium
requires a web driver to interface with the chosen browser. The
102 | Python Programming

web driver acts as a bridge between your Python code and the
browser. The supported web drivers can be downloaded from the
Selenium website (https://www.selenium.dev/documentation/en/
webdriver/driver_requirements/).
Basic Usage: Once you have installed Selenium and downloaded
the web driver, you can start using the web browser module in
Python. The following code snippet demonstrates how to open a web
page using the web browser module:
from selenium import webdriver
# Create an instance of the web driver
driver = webdriver.Chrome(‘/path/to/chromedriver’)
# Open a web page driver.get(‘https://www.example.com’)
# Close the browser driver.quit()
In this example, we import the webdriver module from Selenium
and create an instance of the web driver for the Chrome browser. We
specify the path to the downloaded Chrome web driver executable.
Then, we use the get() method to open the specified web page (in this
case, ‘https://www.example.com’). Finally, we close the browser
using the quit() method.
Interacting with Web Elements: The web browser module allows
you to interact with various web elements such as buttons, forms,
input fields, and links. You can locate elements on a web page using
different methods such as by ID, by class name, by tag name, by
CSS selector, or by XPath. Once you have located an element, you
can perform actions like clicking, typing text, submitting forms, or
extracting information.
# Locate and interact with a button
button = driver.find_element_by_id(‘button-id’) button.click()
# Locate and interact with an input field
input_field = driver.find_element_by_name(‘input-name’)
input_field.send_keys(‘Hello, World!’)
# Locate and interact with a link
link = driver.find_element_by_link_text(‘Click Here’)
link.click()
Web Scraping | 103

In this example, we use the find_element_by_* methods of the


web driver to locate elements based on different criteria. Once we
have obtained a reference to an element, we can perform actions on
it using methods like click() to simulate a click, send_keys() to type
text, or submit() to submit a form.
Web Scraping and Automation: The web browser module is
commonly used for web scraping and automation tasks. With the
ability to locate and interact with web elements, developers can
extract data from websites or perform automated actions like form
filling, clicking, scrolling, and navigation.
# Extract information from a web page
heading = driver.find_element_by_tag_name(‘h1’).text
print(heading)
# Automate a web interaction
form_field = driver.find_element_by_id(‘form-field’)
form_field.send_keys(‘Data to submit’)
submit_button = driver.find_element_by_id(‘submit-button’)
submit_button.click()
In this example, we extract the text content of an <h1> element
and print it. We also locate an input field, type some data into it,
and locate and click a submit button.
The web browser module in Python, powered by Selenium,
provides a robust set of tools for automating web interactions
and extracting data from websites. It enables developers to build
sophisticated web scraping and automation scripts, making it a
valuable tool in various web-related projects.

9.2.1 Overview of the Web Browser Module

The web browser module is a powerful library in Python that


allows us to control web browsers programmatically. It provides a
high-level interface to interact with web pages, fill out forms, click
buttons, and extract data from websites. The web browser module
is built on top of Selenium, a popular web automation tool.
104 | Python Programming

9.2.2 Installing the Web Browser Module

To use the web browser module, we need to install it. Open the
terminal and run the following command:
pip install webbrowser

9.3 BUILDING MAPIT.PY


9.3.1 Project Overview

MAPIT.PY is a command-line application that takes an address


as input from the user and opens the corresponding location on
Google Maps in a web browser. The application uses web scraping to
extract the latitude and longitude coordinates for the given address.

9.3.2 Importing the Required Libraries

Let’s start by importing the necessary libraries:


import webbrowser
import sys
import requests
import bs4

9.3.3 Retrieving Map Coordinates

We will define a function called get_coordinates() that takes the


address as input and returns the latitude and longitude coordinates.
Here’s the code:
def get_coordinates(address):
# Construct the URL for the Google Maps search
url = ‘https://www.google.com/maps/search/’ + address
# Open the URL in a web browser
webbrowser.open(url)
# Fetch the HTML content of the search results page
res = requests.get(url)
res.raise_for_status()
# Parse the HTML content
Web Scraping | 105

soup = bs4.BeautifulSoup(res.text, ‘html.parser’)


# Find the latitude and longitude coordinates
coordinates = soup.select(‘.widget-reveal-card-container’)[0].
get(‘data-card-params’)
# Extract the latitude and longitude from the coordinates
lat, lng = coordinates.split(‘,’)[1], coordinates.split(‘,’)[2]
return lat, lng

9.3.4 Handling User Input

Now, we need to handle the user’s input and pass it to the get_
coordinates() function. Here’s the code:
def main():
if len(sys.argv) > 1:
address = ‘ ‘.join(sys.argv[1:])
else:
address = input(“Enter an address: “)
# Get the coordinates for the address
lat, lng = get_coordinates(address)
# Print the coordinates
print(f”Latitude: {lat}\nLongitude: {lng}”)

if __name__ == ‘__main__’:
main()

9.4 RUNNING MAPIT.PY

9.4.1 Executing the Application

To run the MAPIT.PY application, open the terminal and


navigate to the directory where the script is located. Then, execute
the following command:
python mapit.py
106 | Python Programming

9.4.2 Testing the Application

When prompted, enter the address for which you want to retrieve
the coordinates. The application will then open the corresponding
location on Google Maps in your web browser and display the
latitude and longitude coordinates in the terminal.
Section 1: Understanding the requests Module
The requests module is a popular Python library that simplifies
the process of making HTTP requests. It allows us to send GET and
POST requests, handle cookies, headers, sessions, and much more.
Before diving into downloading files, let’s understand the basics of
the requests module.
Subsection 1.1: Installation and Importing
To get started, we need to install the requests module. Open your
terminal or command prompt and execute the following command:
$ pip install requests
Once installed, import the module into your Python script using
the following line of code:
import requests
Subsection 1.2: Making GET Requests
The requests module provides a simple interface to make GET
requests. Let’s see an example:
import requests
response = requests.get(‘https://api.example.com/data’)
print(response.text)
In the above example, we import the requests module and use
the get function to send a GET request to the specified URL. The
response object contains the server’s response, and we can access
the response content using the text attribute.
Section 2: Downloading Files from the Web
Now that we have a basic understanding of the requests module,
let’s explore how to download files from the web using Python. We
will focus on downloading image files in this section, but the same
concepts apply to other file types as well.
Web Scraping | 107

Subsection 2.1: Downloading Images


To download an image file from the web, we need the URL of
the image. Here’s an example of downloading an image using the
requests module:
import requests
image_url = ‘https://example.com/image.jpg’
response = requests.get(image_url)
with open(‘downloaded_image.jpg’, ‘wb’) as file:
file.write(response.content)
In the above code, we use the get function of the requests module
to retrieve the image from the specified URL. The response object’s
content attribute contains the binary data of the image. We open
a file in binary write mode using the open function and write the
content to the file using the write method.
Subsection 2.2: Downloading Other File Types
The process of downloading files other than images is similar.
We just need to specify the correct file extension when saving the
downloaded file. Let’s see an example of downloading a PDF file:
import requests
pdf_url = ‘https://example.com/document.pdf’
response = requests.get(pdf_url)
with open(‘downloaded_document.pdf’, ‘wb’) as file:
file.write(response.content)
Section 3: Handling HTML Files in Python
HTML (Hypertext Markup Language) is the standard language
for creating web pages. In Python, there are several libraries and
modules available that allow you to handle and manipulate HTML
files effectively. In this guide, we will explore some of the common
tasks involved in working with HTML files in Python.
Parsing HTML with BeautifulSoup: BeautifulSoup is a popular
Python library that provides convenient methods for parsing HTML
and extracting data from it. To work with HTML files, you need to
install the BeautifulSoup library using the following command:
108 | Python Programming

pip install beautifulsoup4


Once installed, you can use BeautifulSoup to parse HTML files
and navigate their elements. Here’s an example of how to parse an
HTML file and extract information using BeautifulSoup:
from bs4 import BeautifulSoup
# Open and read the HTML file
with open(‘example.html’, ‘r’) as file:
html_content = file.read()
# Create a BeautifulSoup object
soup = BeautifulSoup(html_content, ‘html.parser’)
# Extract information from the HTML file
title = soup.title.text
paragraphs = soup.find_all(‘p’)
# Print the extracted data
print(“Title:”, title) for paragraph in paragraphs: print(“Paragraph:”,
paragraph.text)
In this example, we open an HTML file (‘example.html’) and
read its content. Then, we create a BeautifulSoup object by passing
the HTML content and specifying the parser to use. We can use
BeautifulSoup’s methods and functions to navigate and search for
specific elements in the HTML file. In this case, we extract the title
and all paragraph elements from the file and print their content.
Modifying HTML with BeautifulSoup: Besides extracting data,
you can also use BeautifulSoup to modify HTML files. You can add,
remove, or update elements within the HTML structure. Here’s an
example of how to modify an HTML file using BeautifulSoup:
from bs4 import BeautifulSoup
# Open and read the HTML file
with open(‘example.html’, ‘r’) as file:
html_content = file.read()
# Create a BeautifulSoup object
soup = BeautifulSoup(html_content, ‘html.parser’)
# Modify the HTML file
Web Scraping | 109

title = soup.title
title.string = “New Title”
paragraph = soup.find(‘p’)
paragraph.string = “Modified paragraph text”
# Save the modified HTML to a new file
with open(‘modified.html’, ‘w’) as file:
file.write(str(soup))
In this example, we open an HTML file (‘example.html’) and read
its content. Then, we create a BeautifulSoup object and modify
specific elements within the HTML structure. In this case, we change
the title and the text content of a paragraph element. Finally, we
save the modified HTML to a new file (‘modified.html’).
•• Other Libraries for Handling HTML: Besides BeautifulSoup,
there are other Python libraries that can assist in handling
HTML files. Some notable ones include:
•• lxml: A powerful library for processing XML and HTML files.
It provides a fast and efficient way to parse and manipulate
HTML structures.
•• html5lib: A pure-Python library that parses HTML according
to the HTML5 specification. It is generally slower than lxml
or BeautifulSoup but handles malformed HTML better.
Depending on your requirements, you can choose the library
that best suits your needs for working with HTML files in Python.
Working with HTML files in Python enables you to extract
data, manipulate the structure, and perform various tasks
programmatically. Libraries like BeautifulSoup, lxml, and html5lib
provide the necessary tools and functionalities to handle HTML files
effectively, making it easier to automate tasks, scrape data from
websites, or generate HTML content dynamically.
110 | Python Programming

EXERCISE

Short Answer Questions (2 Marks)

1. What is web scraping?


2. How can the web browser module be used in web scraping
projects?
3. What is the purpose of the requests module in web scraping?
4. How can downloaded files be saved to the hard drive in web
scraping?
5. What is the role of HTML in web scraping?

Long Answer Questions (5 Marks)

1. Can you explain the process of web scraping and its


applications? How does it relate to the project MAPIT.PY?
2. In the context of web scraping, how does the web browser
module facilitate the extraction of data from websites? Could
you provide an example of its usage?
3. What functionalities does the requests module provide in
web scraping projects? How can it be utilized to download
files from the web?
4. When saving downloaded files to the hard drive in a web
scraping project, what factors should be considered to ensure
efficient storage and organization of the data? Are there any
best practices to follow?
5. HTML plays a significant role in web scraping. Could you
elaborate on its importance and how it is used to extract
information from websites? Are there any specific HTML
elements or attributes that are commonly targeted during
the scraping process?

Multiple Choice Questions

1. What is web scraping?


a) A technique for downloading files from the internet
b) A method to save web pages as HTML files
Web Scraping | 111

c) The process of extracting data from websites


d) A programming language used for web development
Answer: c) The process of extracting data from websites
2. Which module is commonly used in web scraping projects to
interact with web browsers?
a) requests
b) BeautifulSoup
c) web browser
d) pandas
Answer: c) web browser
3. Which module in Python is commonly used for downloading
files from the web?
a) BeautifulSoup
b) requests
c) web browser
d) pandas
Answer: b) requests
4. How can downloaded files be saved to the hard drive in web
scraping projects?
a) Using the save() function from the requests module
b) By calling the save_file() method from the web browser
module
c) By writing the file data to a local file using Python’s file
handling operations
d) By using the download() function from the web browser
module
Answer: c) By writing the file data to a local file using Python’s
file handling operations
5. Which of the following is an HTML element commonly
targeted during web scraping?
a) <url>
b) <div>
112 | Python Programming

c) <http>
d) <data>
Answer: b) <div>
6. What is the purpose of the BeautifulSoup library in web
scraping?
a) It is used to download files from the web.
b) It is used to parse HTML and XML documents.
c) It provides a web browser interface for scraping data.
d) It is used to save downloaded files to the hard drive.
Answer: b) It is used to parse HTML and XML documents.
7. Which attribute is commonly used in HTML tags to uniquely
identify elements for web scraping?
a) class
b) id
c) name
d) href
Answer: b) id
8. Which method is commonly used in the requests module to
make HTTP GET requests?
a) get()
b) fetch()
c) retrieve()
d) request()
Answer: a) get()
9. Which of the following is NOT a common challenge faced in
web scraping?
a) Captchas
b) Rate limiting
c) HTML validation errors
d) Broken links
Answer: c) HTML validation errors
Web Scraping | 113

10. What is the role of headers in the requests module?


a) They are used to specify the data format for POST requests.
b) They provide information about the web page being
requested.
c) They control the browser behavior during web scraping.
d) They are used to authenticate the user for accessing
restricted content.
Answer: b) They provide information about the web page
being requested.
11. Which of the following is an advantage of web scraping?
a) It ensures data security and privacy.
b) It guarantees real-time data updates.
c) It allows for automated data extraction.
d) It provides a standardized format for data storage.
Answer: c) It allows for automated data extraction.
12. Which method in the web browser module is used to open a
new browser window?
a) open()
b) navigate()
c) start()
d) launch()
Answer: a) open()
13. In web scraping, what is the purpose of robots.txt?
a) It specifies the list of allowed URLs for scraping.
b) It prevents web scraping by restricting access to certain
URLs.
c) It provides a list of instructions for web scrapers to follow.
d) It verifies the authenticity of web scraping requests.
Answer: b) It prevents web scraping by restricting access to
certain URLs.
114 | Python Programming

14. Which Python library provides support for handling


JavaScript rendering in web scraping?
a) Selenium
b) Requests
c) Beautiful Soup
d) Pandas
Answer: a) Selenium
15. Which of the following is an example of an unethical use of
web scraping?
a) Extracting publicly available data for research purposes
b) Gathering competitive intelligence for market analysis
c) Scraping personal information without consent for
spamming
d) Extracting product information for price comparison
Answer: c) Scraping personal information without consent
for spamming

You might also like