0% found this document useful (0 votes)
2 views174 pages

Introduction to Python and Its Features...

Uploaded by

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

Introduction to Python and Its Features...

Uploaded by

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

Introduction and features of Python

Introduction to Python
Python is a high-level, interpreted programming language created by Guido van

Rossum and first released in 1991. It's known for its simplicity, readability, and

versatility, making it one of the most popular programming languages today. Python is

widely used in various fields, such as web development, data analysis, artificial

intelligence, scientific computing, and automation.

Python's design philosophy emphasizes code readability and simplicity, with a syntax

that allows programmers to express concepts in fewer lines of code compared to

languages like C++ or Java. Its extensive standard library and large ecosystem of

third-party libraries make it a powerful tool for both beginners and experienced

developers.

Features of Python
1.​ Simple and Easy to Learn: Python's straightforward syntax and readability make
it easy to learn, especially for beginners. The language is designed to be intuitive
and mirrors natural language to some extent.
2.​ Interpreted Language: Python code is executed line by line, which makes
debugging easier and more interactive. You don't need to compile your code
before running it, which speeds up the development process.
3.​ Cross-Platform Compatibility: Python is available on various platforms, including
Windows, macOS, Linux, and even mobile devices. This allows you to write code
that can run on multiple systems without modification.

1
4.​ Extensive Standard Library: Python comes with a rich standard library that
provides modules and functions for various tasks, such as file I/O, regular
expressions, web services, and more. This reduces the need to write code from
scratch for common tasks.
5.​ Large Ecosystem of Libraries: Python has a vast collection of third-party libraries
and frameworks for different domains, such as NumPy and pandas for data
analysis, TensorFlow and PyTorch for machine learning, Django and Flask for
web development, and many more.
6.​ Object-Oriented Programming: Python supports object-oriented programming
(OOP) paradigms, allowing you to create reusable code and build complex
applications. It also supports procedural and functional programming styles,
making it a flexible language.
7.​ Dynamic Typing: Python is dynamically typed, meaning you don't need to declare
the type of a variable. The type is inferred at runtime, which simplifies the code
and makes it more flexible.
8.​ Memory Management: Python handles memory management automatically with
built-in garbage collection, so developers don't need to worry about manually
allocating and deallocating memory.
9.​ Community Support: Python has a large and active community, which means
there are plenty of resources, tutorials, and forums where you can get help and
share knowledge.
10.​Extensible and Embeddable: Python can be extended with modules written in C
or C++, and it can also be embedded into other applications as a scripting
language, allowing for more flexibility and integration with other systems.
11.​High-Level Language: Python abstracts many complex details of the machine,
allowing you to focus more on problem-solving than on the intricacies of
hardware-level programming.
12.​Scalable and Versatile: Python can be used for small-scale scripts to automate
tasks, as well as for large-scale enterprise applications. It is versatile enough to

2
be used in web development, scientific computing, data analysis, artificial
intelligence, and more.
13.​Support for Scripting and Automation: Python is often used as a scripting
language for automating repetitive tasks. Its ability to interface with system calls
and other languages makes it ideal for writing scripts that control other software
applications.

These features make Python a powerful, flexible, and accessible programming

language suitable for a wide range of applications.

Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) is a programming paradigm that organizes code

around objects rather than functions or logic. An object is a collection of data (attributes)

and methods (functions) that operate on the data. OOP allows you to model real-world

things like cars, animals, or even more abstract concepts like a bank account, as

objects in your code.

In OOP, you focus on creating classes, which are blueprints for objects. A class defines

the properties (attributes) and behaviors (methods) that the objects created from that

class will have. Once you create a class, you can create multiple objects (instances)

from it.

Key Concepts of OOP:

1.​ Class: A blueprint or template for creating objects. It defines what attributes and
methods the objects will have.

3
2.​ Object: An instance of a class. It represents a specific item or concept created
from the class.
3.​ Encapsulation: The practice of keeping data (attributes) and methods (functions)
within a class and controlling access to them, often using access modifiers like
private or public.
4.​ Inheritance: The ability to create a new class based on an existing class,
inheriting its properties and behaviors while allowing for modifications or
extensions.
5.​ Polymorphism: The ability to use the same method name in different classes,
where each class defines the method differently, allowing for flexible code.
6.​ Abstraction: The practice of hiding complex implementation details and showing
only the essential features of an object.

Example:

python
Copy code

class Car: def __init__(self, make, model): self.make = make self.model =

model def start_engine(self): print(f"{self.make} {self.model}'s engine

started.") my_car = Car("Toyota", "Corolla") my_car.start_engine() #

Output: Toyota Corolla's engine started.

In this example, Car is a class, and my_car is an object (instance) of that class. The

start_engine method is a behavior that can be performed by the object.

Procedural-Oriented Programming (POP)


Procedural-Oriented Programming (POP) is a programming paradigm that organizes

code around procedures or functions. In this approach, the program is divided into small

4
chunks of code, called functions, that perform specific tasks. The focus is on writing

sequences of instructions to be executed by the computer.

In POP, you think of the program as a series of steps or procedures to be followed. Data

and functions are typically separate, and functions operate on data passed to them.

Key Concepts of POP:

1.​ Procedure/Function: A block of code that performs a specific task. You can call
the function whenever you need to perform that task.
2.​ Global and Local Variables: Variables can be defined globally (accessible
throughout the program) or locally (accessible only within a specific function).
3.​ Modularity: The program is divided into small, manageable functions that can be
reused in different parts of the program.
4.​ Top-Down Approach: The program is structured in a step-by-step manner, often
starting with the main function and breaking down tasks into smaller functions.

Example:

python
Copy code

def start_engine(make, model): print(f"{make} {model}'s engine started.")

car_make = "Toyota" car_model = "Corolla" start_engine(car_make,

car_model) # Output: Toyota Corolla's engine started.

In this example, start_engine is a function that performs a specific task. The data

(car_make and car_model) is passed to the function as arguments, and the function

operates on that data.

5
Key Differences:
●​ Focus: OOP focuses on objects (data + behavior), while POP focuses on
functions and the sequence of tasks.
●​ Data and Functions: In OOP, data and methods are bundled together within
objects. In POP, data and functions are separate.
●​ Reusability: OOP encourages code reusability through inheritance and
polymorphism. POP achieves reusability by breaking down the program into
reusable functions.
●​ Approach: OOP takes a bottom-up approach (starting with objects), while POP
takes a top-down approach (starting with the main function and breaking it
down).

Both paradigms are useful, and the choice between them depends on the nature of the

problem you are trying to solve. OOP is often preferred for large, complex applications,

while POP can be simpler and more efficient for smaller tasks or straightforward

problems.

Procedural-Oriented Programming (POP)


In Procedural-Oriented Programming, you think of your program as a list of

instructions or steps to get something done. You write functions (small pieces of

code) to perform each task, and you call these functions whenever you need

them.

6
Example: Making a Sandwich

Imagine you're writing a program to make a sandwich. In POP, you would write

functions for each step:

1.​ Get the bread


2.​ Add the filling
3.​ Close the sandwich

Here’s how you might write that in code:

python code

def get_bread::

print ("Getting two slices of bread")))

def add_filling :():

print ("Adding filling to the bread")

def close_sandwich(:): print(("Closing the sandwich"))

# #Main program

get_bread()

add_filling()

close_sandwich()

In this program, each function does one job. The program runs from top to

bottom, calling each function in order to make the sandwich. Everything is done

step by step, just like following a recipe.

7
Object-Oriented Programming (OOP)
In Object-Oriented Programming, instead of thinking about steps, you think about

things (objects) that have properties and actions. These things can interact with

each other.

Example: Making a Sandwich (with Objects)

Now, instead of just steps, you think of a sandwich as an object. A sandwich has

properties (like the type of bread and filling) and actions (like adding filling or

closing the sandwich).

You create a class (a blueprint) for a sandwich, and then you can create different

sandwich objects.

python code

class Sandwich:

def __init__(self,bread,filling): self.bread =

bread

self.filling = filling

def make_sandwich(self): print(f"Getting two slices of

{self.bread}")

print(f"Adding {self.filling} to the bread")

print("Closing the sandwich")

# Creating a sandwich object my_sandwich = Sandwich("wheat bread",

"turkey") my_sandwich.make_sandwich()

8
In this example:

●​ Class: Sandwich is like a recipe or blueprint for making sandwiches.


●​ Object: my_sandwich is a specific sandwich you’re making.
●​ Properties: The sandwich has a type of bread and filling.
●​ Action (Method): The sandwich can make itself using the make_sandwich
method.

Summary of Differences:
●​ POP: Focuses on functions (steps) to get the job done. You think about
what steps need to be done, and you write those steps as functions.​
Example: Making a sandwich step by step with individual functions.
●​ OOP: Focuses on objects (things) that have properties and actions. You
think about the "thing" you're working with (like a sandwich), and you write
a class that describes how that thing works.​
Example: Creating a sandwich object with properties (bread, filling) and
actions (make the sandwich).

In simple terms, POP is like following a recipe one step at a time, while OOP is

like thinking of a sandwich as a whole thing that can make itself when you tell it

to.

2.

Execution mode

9
Python is a programming language that lets you work quickly and integrate

systems more efficiently. It is a widely-used general-purpose, high-level

programming language. It was designed with an emphasis on code

readability, and its syntax allows programmers to express their concepts in

fewer lines of code. In the Python programming language, there are two

ways in which we can run our code:

1. Interactive mode

2. Script mode

In this article, we’ll get to know what these modes are and how they differ

from each other.

Interactive mode

Interactive etymologically means “working simultaneously and creating

impact of our work on the other’s work”. Interactive mode is based on this

ideology only. In the interactive mode as we enter a command and press

enter, the very next step we get the output. The output of the code in the

interactive mode is influenced by the last command we give. Interactive

mode is very convenient for writing very short lines of code. In python it is

also known as REPL which stands for Read Evaluate Print Loop. Here, the

read function reads the input from the user and stores it in memory. Eval

function evaluates the input to get the desired output. Print function outputs

the evaluated result. The loop function executes the loop during the

10
execution of the entire program and terminates when our program ends.

This mode is very suitable for beginners in programming as it helps them

evaluate their code line by line and understand the execution of code well.

How to run python code in Interactive mode?

In order to run our program in the interactive mode, we can use command

prompt in windows, terminal in Linux, and macOS. Let us see understand

the execution of python code in the command prompt with the help of an

example:

Example 1:

To run python in command prompt type “python”. Then simply type the

Python statement on >>> prompt. As we type and press enter we can see

the output in the very next line.

Python3
# Python program to display "Hello GPF"
print("Hello GPF")
Output:

11
Let us take another example in which we need to perform addition on two
numbers and we want to get its output. We will declare two variables a and
b and store the result in a third variable c. We further print c. All this is
done in the command prompt.

Python3
# Python program to add two numbers

a = 2

b = 3

# Adding a and b and storing result in c

C = A + B

# Printing value of c

12
print (c)

Output:

We can see the desired output on the screen. This kind of program is a
very short program and can be easily executed in interactive mode.

Example 3:

In this example, we will multiply two numbers and take the numbers as an
input for two users. You will see that when you execute the input
command, you need to give input in the very next line, i.e. code is
interpreted line by line.

13
Python3
# Python program to take input from user
# Taking input from user
a = int(input())
# Taking input from user
b = int(input())
# Multiplying and storing result
c = a * b
# Printing the result
print ©
Output:

Disadvantages of interactive mode

The interactive mode is not suitable for large programs.

14
The interactive mode doesn’t save the statements. Once we make a program
it is for that time itself, we cannot use it in the future. In order to use it in the
future, we need to retype all the statements.

Editing the code written in interactive mode is a tedious task. We need to


revisit all our previous commands and if still, we could not edit we need to
type everything again

.Script Mode
Script etymologically means a system of writing. In the script mode, a
python program can be written in a file. This file can then be saved and
executed using the command prompt. We can view the code at any time
by opening the file and editing becomes quite easy as we can open and
view the entire code as many times as we want. Script mode is very
suitable for writing long pieces of code. It is much preferred over interactive
mode by experts in the program. The file made in the script mode is by
default saved in the Python installation folder and the extension to save a
python file is “.py”.

How to run python code in script mode?

In order to run a code in script mode follow the following steps.

Step 1: Make a file using a text editor. You can use any text editor of your
choice(Here I use notepad).

Step 2: After writing the code save the file using “.py” extension.

15
Step 3: Now open the command prompt and command directory to the
one where your file is stored.

Step 4: Type python “filename.py” and press enter.

Step 5: You will see the output on your command prompt.

Let us understand these steps with the help of the examples:

Example 1:

In order to execute “Hello gfg” using script mode we first make a file and
save it.

Now we use the command prompt to execute this file.

16
Output:

Example 2:

Our second example is the same addition of two numbers as we saw in the
interactive mode. But in this case, we first make a file and write the entire
code in that file. We then save it and execute it using the command
prompt.

17
Output:

Example 3:

In this example, we write the code for multiplying two numbers. And the
numbers which are to be multiplied are taken by the user as an input. In
the interactive mode, we saw that as we write the command so does it

18
asks for the input in the very next line. But in script mode we first code the
entire program save and then run it in command prompt. The python
interpreter executes the code line by line and gives us the result
accordingly.

In this example, we see that the whole program is compiled and the code
is executed line by line. The output on the shell is entirely different from the
interactive mode.

Difference between Interactive mode and Script mode

●​ It is a way of executing a Python program in which statements are


written in command prompt and result is obtained on the same.

19
●​ In the script mode, the Python program is written in a file. Python
interpreter reads the file and then executes it and provides the
desired result. The program is compiled in the command prompt,
●​ The interactive mode is more suitable for writing very short
programs.​
●​ Script mode is more suitable for writing long programs.
●​ Editing of code can be done but it is a tedious task.​
●​ Editing of code can be easily done in script mode.
●​ We get output for every single line of code in interactive mode i.e.
result is obtained after execution of each line of code.​
●​ In script mode entire program is first compiled and then executed.
●​ Code cannot be saved and used in the future.​
●​ Code can be saved and can be used in the future.
●​ It is more preferred by beginners.​
●​ It is more preferred by experts than the beginners to use script
mode.

Python uses a specific character set (Unicode) that includes letters, digits,

punctuation, and various symbols. Here are some key aspects:

Character Set:
●​ Letters: Python supports both uppercase and lowercase letters (e.g., A-Z,
a-z).

●​ Digits: Python recognizes digits (e.g., 0-9).


●​ Symbols: Python uses various symbols (e.g., +, -, *, /, =, @, #, &, etc.).

20
●​ Whitespace Characters: Python recognizes spaces, tabs, and newlines as
whitespace.

Python Character Set


Python's character set is a collection of characters that are used in
writing Python programs. This set includes:

1.​ Letters:
○​ Lowercase letters: a, b, c, ..., z
○​ Uppercase letters: A, B, C, ..., Z
○​ Python is case-sensitive, which means a and A are
considered different characters.
2.​ Digits:
○​ Numeric digits: 0, 1, 2, ..., 9
○​ These are used in defining numbers (e.g., 123, 4.56).
3.​ Special Characters:
○​ Operators: +, -, *, /, %, =, ==, !=, etc.
○​ Punctuation: ,, :, ;, ., () (parentheses), [] (square
brackets), {} (curly braces).
○​ Other symbols: @, #, $, &, ^, *, _, etc.
○​ Whitespace characters: Space, Tab (\t), and Newline
(\n).
4.​ Unicode Support:

21
○​ Python supports Unicode characters, meaning you can
include characters from different languages and symbols
in your code ChatGPT

Indentation in Python

What is Indentation?
Indentation refers to the spaces or tabs at the beginning of a line of code. In

Python, indentation is not just a matter of style—it is syntactically significant and

mandatory. Python uses indentation to define the structure of the code,

specifically to denote blocks of code that belong together.

For example, when you define a function or use a control structure like an if

statement, you need to indent the lines of code that are part of that function or

statement.

Why is Indentation Important?


In many programming languages, blocks of code are defined using braces {} or

keywords like begin and end. However, Python uses indentation to define blocks

of code. This makes Python code visually cleaner but also means that the correct

use of indentation is essential for your code to run correctly.

Rules of Indentation:

22
1.​ Consistent Indentation: You must use the same number of spaces or tabs
for each level of indentation within a block. Mixing spaces and tabs in the
same block will result in an error.
2.​ Recommended Indentation: Python's official style guide, PEP 8,
recommends using 4 spaces per indentation level. While you can use tabs
or any other number of spaces, 4 spaces is the standard.
3.​ Indentation Levels: Each level of indentation represents a new block of
code. For example, after an if statement, the next line must be indented
to indicate that it is part of the if block. If you need to create a sub-block
within that block, you would increase the indentation further.
4.​ SyntaxError for Incorrect Indentation: If you do not follow the indentation
rules, Python will raise a SyntaxError. This error indicates that the code
structure is not defined properly.

Example 1: Function Definition with Indentation

python
Copy code

23
def greet(name):

print("Inside the function")

# This line is indented with 4 spaces

if name:

# The 'if' statement starts a new block

print(f"Hello, {name}!")

# This line is part of the 'if' block

else:

# The 'else' statement is at the same indentation level as 'if'

print("Hello, World!")

# This line is part of the 'else' block

In this example:

●​ The print("Inside the function") line is part of the greet function, so


it is indented.
●​ The lines print(f"Hello, {name}!") and print("Hello, World!")
are indented further to show they are part of the if and else blocks,
respectively.

Example 2: Nested Blocks with Indentation

def check_number(num):

if num > 0:

print("Positive number")

24
if num % 2 == 0:

print("Even number")

else:

print("Odd number")

else:

print("Non-positive number")

Here:

●​ The print("Positive number") line is indented inside the if block.


●​ The nested if-else block is further indented within the first if block.

Example 3: Incorrect Indentation (causing an error)

def greet(name):

print("Inside the function")

if name: # This will cause an error because the


indentation is inconsistent

print(f"Hello, {name}!")

In this case, the if statement is indented with 4 spaces, but the print("Inside
the function") line is indented with only 2 spaces. This inconsistency will cause
Python to raise a SyntaxError.

Best Practices:

25
●​ Stick to 4 spaces per level: This is the convention and makes your code
consistent with most Python code you'll encounter.
●​ Avoid mixing tabs and spaces: Python 3 disallows mixing tabs and spaces
in indentation. Stick to one or the other (preferably spaces).
●​ Use a text editor or IDE that automatically handles indentation: Most
modern text editors and IDEs (like PyCharm, VSCode, or even Jupyter
Notebook) will automatically indent your code correctly.

PYTHON TOKENS

In Python, the program is broken down into various components


that are referred to as tokens. These tokens form the smallest
unit of the program and can be broadly categorized into five main
types: keywords, identifiers, literals, operators, and
punctuators. Below is a detailed explanation of each type of
token:

KEYWORDS

In Python, the program is broken down into various components


that are referred to as tokens. These tokens form the smallest
unit of the program and can be broadly categorized into five main
types: keywords, identifiers, literals, operators, and
punctuators. Below is a detailed explanation of each type of
token:

1. Keywords:

26
Definition: Keywords are reserved words in Python that have a
predefined meaning and cannot be used for anything other than their
intended purpose.

Examples: if, else, while, for, break, continue, class, def,


return, try, except, etc.

Usage: Keywords define the structure and flow of the program. For
example:​
if x > 0:

print("Positive")

else:

print("Non-positive")

2. Identifiers:

Definition: Identifiers are names given to variables, functions, classes,


or other entities in the program.

Rules:

Must start with a letter (A-Z or a-z) or an underscore (_), followed by


letters, digits (0-9), or underscores.

Python is case-sensitive, so myVar and myvar are considered different


identifiers.

27
Cannot be a keyword (e.g., if, for).

Examples: variable_name, my_function, ClassName,


_private_var, PI.

Usage: Identifiers are used to label and refer to values or objects in


your code. For example:​
def my_function():

pass

3. Literals:

Definition: Literals are fixed values in Python, such as numbers,


strings, or boolean values.

Types of Literals:

Numeric Literals: Represent numbers. E.g., 10, 3.14, 0xFF


(hexadecimal), 0b1010 (binary).

String Literals: Represent text. E.g., "Hello", 'Python',


"""Multi-line string""".

Boolean Literals: Represent truth values. E.g., True, False.

Special Literals: None is used to denote the absence of a value or a


null value.

28
Usage: Literals are the raw data you work with in your program. For
example:

age = 25 # Numeric Literal

name = "Alice" # String Literal

is_student = True # Boolean Literal

4. Operators:

Definition: Operators are symbols that perform operations on


variables and values (operands).

Types of Operators:

Arithmetic Operators: +, -, *, /, %, **, //

Comparison Operators: ==, !=, >, <, >=, <=

Logical Operators: and, or, not

Bitwise Operators: &, |, ^, ~, <<, >>

Assignment Operators: =, +=, -=, *=, /=, etc.

Identity Operators: is, is not

Membership Operators: in, not in

29
Usage: Operators are used to manipulate data. For example:​

result = 5 + 3 # Arithmetic Operator

is_equal = (5 == 5) # Comparison Operator

is_true = (5 > 3) and (10 < 20) # Logical Operator

5. Punctuators:

Definition: Punctuators (also known as delimiters or separators) are


symbols that are used to structure and organize the code.

Examples:

Parentheses: (), used in function calls and for grouping expressions.

Braces: {}, used for defining dictionaries and code blocks in some
contexts (e.g., lambda functions).

Brackets: [], used for list indexing and slicing.

Comma: ,, used to separate items in a list, tuple, or function


parameters.

Colon: :, used in function definitions, if-else statements, loops, and


dictionary key-value pairs.

30
Semicolon: ;, used to separate multiple statements on a single line
(though it's rarely used in Python).

Dot: ., used for attribute access or method calls.

Assignment and comparison punctuators: =, ==, !=

Usage: Punctuators help in organizing code and defining the structure


of Python syntax. For example:​

def my_function(a, b): # Parentheses and Colon

return a + b # Return statement and Indentation

my_dict = {"key": "value"} # Braces and Colon

my_list = [1, 2, 3] # Brackets and Comma

Conclusion:

These tokens form the building blocks of Python code. Understanding


how they interact and are used together is key to mastering Python
programming. Each token serves a specific role in defining the
structure, data, and operations in your program.

KEYWORDS

31
Keywords in Python are reserved words that have specific meanings
and purposes. These words are part of the syntax and structure of the
language and cannot be used as identifiers (names for variables,
functions, classes, etc.). Python's keywords define the control flow,
variable management, and overall structure of a Python program.

Characteristics of Keywords:

Reserved: Keywords are reserved and cannot be used for anything


other than their intended purpose.

Case-sensitive: All keywords in Python are in lowercase, except for


True, False, and None.

Fixed: The meaning and function of keywords cannot be altered by the


user.

Categories of Keywords:

Keywords can be grouped based on their usage in Python


programming:

1. Control Flow Keywords:

These keywords are used to control the flow of the program (i.e.,
decisions and loops).

if / elif / else: These keywords are used for conditional branching.

32
Example:​
if condition:

# code block

elif another_condition:

# another code block

else:

# default code block

for / while: These keywords are used for looping.

Example:​
for i in range(5):

print(i)

while condition:

# code block

break / continue / pass: These keywords control the loop execution.

33
break: Exits the loop entirely.

continue: Skips the rest of the code inside the loop for the current
iteration and moves to the next iteration.

pass: Does nothing; it's a null operation when a statement is


syntactically required but no code needs to be executed.

Example:​

for i in range(10):

if i == 5:

break

elif i % 2 == 0:

continue

else:

pass

2. Function and Class Definition Keywords:

These keywords are used for defining functions, classes, and methods.

def: Used to define a function.

34
Example:​

def my_function():

print("Hello, World!")

return: Used to return a value from a function.

Example:​

def add(a, b):

return a + b

lambda: Used to define an anonymous function.

Example:​

square = lambda x: x ** 2

print(square(4)) # Output: 16

class: Used to define a class.

35
Example:​
class MyClass:

def _init_(self, name):

self.name = name

3. Exception Handling Keywords:

These keywords are used to handle exceptions (errors) in Python


programs.

try / except / finally: Used to catch and handle exceptions.

try: Block of code to be tested for errors.

except: Block of code to handle the error if it occurs.

finally: Block of code that will be executed no matter what, after try
and except.

Example:​

try:

result = 10 / 0

except ZeroDivisionError:

36
print("Division by zero is not allowed.")

finally:

print("This will run no matter what.")

raise: Used to raise an exception manually.

Example:​
if x < 0:

raise ValueError("Negative value not allowed.")

assert: Used for debugging purposes. It tests if a condition is true and


raises an AssertionError if it is not.

Example:​

assert x >= 0, "x should be non-negative"

4. Variable Management Keywords:

These keywords are used for variable assignment and management.

37
global: Used to declare a global variable inside a function, making it
accessible throughout the program.

Example:​
global_var = 10

def modify_global():

global global_var

global_var = 20

nonlocal: Used to declare a variable that is not local to the function


but not global either, typically used in nested functions.

Example:​

def outer():

x = 10

def inner():

nonlocal x

x = 20

38
inner()

print(x) # Output: 20

del: Used to delete objects (variables, lists, dictionary keys, etc.).

Example:​

del my_variable

5. Boolean and None Keywords:

These keywords represent truth values and the absence of a value.

True / False: Boolean literals representing true and false conditions.

Example:​
is_active = True

None: Represents the absence of a value or a null value.

Example:​
result = None

6. Context Management Keywords:

39
These keywords help in managing resources (e.g., files) and ensuring
that they are properly closed after use.

with: Simplifies the management of resources, like file handling.

Example:​
with open('file.txt', 'r') as file:

content = file.read()

as: Used to create an alias while importing a module or in with


statements.

Example:​

import numpy as np

7. Miscellaneous Keywords:

These keywords have specific functions that don't fall into the above
categories.

import / from: Used to import modules or specific components from a


module.

40
Example:​
import math

from math import sqrt

in / not in: Used to check for membership in sequences like lists,


tuples, or strings.

Example:​

if 'a' in 'apple':

print("Found")

is / is not: Used to test object identity, i.e., whether two objects are
the same in memory.

Example:​
if a is b:

print("a and b are the same object")

and / or / not: Logical operators used to perform logical operations.

41
Example:​
if a > 0 and b > 0:

print("Both are positive")

yield: Used in functions to return a generator instead of a single value,


allowing the function to return values one at a time.

Example:​

def generator():

yield 1

yield 2

yield 3

Full List of Python Keywords (Python 3.x):

False await else import pass


None break except in raise. True
class finally is return

42
and continue for lambda try as
def from nonlocal while assert del
global not with async elif
if or yield

These keywords are fundamental to writing Python programs.


Understanding them and their usage is key to becoming proficient in
Python programming.

IDENTIFIERS

In Python, identifiers are names used to identify a variable, function,


class, module, or other object. An identifier is essentially a name that
you assign to different elements in your Python code. Understanding
how to correctly create and use identifiers is fundamental to writing
clear and efficient Python code.

Key Points About Identifiers:

Naming Rules:

First Character: An identifier must start with a letter (A-Z or a-z) or an


underscore (_). It cannot begin with a digit.

Valid examples: my_var, _privateVar, variable1.

43
Invalid examples: 1variable, @name, #value.

Subsequent Characters: After the first character, the identifier can


contain letters, digits (0-9), or underscores.

Valid examples: my2ndVariable, func_name_1.

Invalid examples: my-var (hyphens are not allowed).

Case Sensitivity:

Python is case-sensitive, meaning that myVariable, MyVariable, and


myvariable are considered three different identifiers.

Example:​
var1 = 10

Var1 = 20

print(var1) # Outputs: 10

print(Var1) # Outputs: 20

Cannot Be a Keyword:

44
Python keywords (e.g., if, for, class, etc.) cannot be used as
identifiers. These are reserved for specific purposes in the Python
language.

Invalid examples: if, else, True.

Length:

There is no specific length limit for identifiers in Python, but it's a good
practice to keep them reasonably short and descriptive. Very long
identifiers can make your code hard to read and maintain.

Underscores in Identifiers:

Single Leading Underscore (_variable): This convention is used to


indicate that a variable or method is intended for internal use (though it
can still be accessed directly).

Example:​
_private_var = 42

Double Leading Underscore (__variable): Used for name mangling,


where the interpreter changes the name of the variable to avoid
conflicts in subclasses.

Example:​
class MyClass:

45
def __init__(self):

self.__private = 10 # Internally, it becomes


_MyClass__private

Trailing Double Underscore (variable__): This is used for special


methods (also known as "magic methods") in Python, such as
__init__, __str__, etc.

Example:​
class MyClass:

def __init__(self):

self.value = 0

Conventions:

PEP 8: The Python Enhancement Proposal (PEP 8) provides guidelines


on naming conventions:

Variable and Function Names: Use lowercase words separated by


underscores (snake_case). Example: my_variable,
calculate_total.

46
Class Names: Use CamelCase, where each word starts with an
uppercase letter. Example: MyClass, EmployeeData.

Constants: Use all uppercase letters with underscores separating


words. Example: MAX_SIZE, PI.

Best Practices for Choosing Identifiers:

Descriptive Names: Choose names that clearly describe the purpose


of the variable or function. Avoid single-letter names except for loop
counters.

Good example: total_sales, calculate_area.

Bad example: a, foo, x1.

Avoid Confusing Similarities: Avoid using identifiers that are easily


confused, such as l (lowercase L), O (uppercase O), and I (uppercase i),
as they can look similar to numbers.

Good example: index, order_count.

Bad example: l, o, i.

Use Meaningful Abbreviations: If you use abbreviations, make sure


they are common and recognizable.

47
Good example: avg_temp for average temperature.

Bad example: tmpr for temperature.

Examples of Identifiers:

# Variable identifier

student_name = "Alice"

# Function identifier

def calculate_area(radius):

return 3.14 * radius * radius

# Class identifier

class Car:

def __init__(self, make, model):

self.make = make # Instance variable


identifiers

self.model = model

48
# Constant identifier

MAX_SPEED = 120

Invalid Identifiers:

Some examples of identifiers that would raise errors in Python:

Starting with a number:​

2ndVar = 10 # SyntaxError

Using a special character other than underscore:​

my-var = 5 # SyntaxError

Using a keyword:​
for = 100 # SyntaxError

Identifier Use Cases:

Variables: Identifiers are most commonly used as names for variables.​


age = 25

49
Functions: When defining functions, identifiers are used as function
names.​

def greet(name):

return "Hello, " + name

Classes: In object-oriented programming, identifiers are used for class


names.​

class Person:

pass

Modules: Identifiers are also used for module names when importing
modules in Python.​

import math

3. LITERALS

50
In Python, literals are fixed values or constants that you write directly in
your code. These values are not calculated or evaluated but are
hard-coded in the program. Python supports several types of literals, each
corresponding to different data types. Let’s explore them in detail.

1. Numeric Literals

Numeric literals represent numbers and are of three types: integers,


floats, and complex numbers.

a. Integer Literals

Integers are whole numbers, without a decimal point.

They can be positive, negative, or zero.

Python supports four types of integers:

Decimal (Base 10): The most common integer format.

Example: 10, -20, 0

Binary (Base 2): Prefixed with 0b or 0B.

Example: 0b1010 (which is 10 in decimal)

Octal (Base 8): Prefixed with 0o or 0O.

Example: 0o12 (which is 10 in decimal)

Hexadecimal (Base 16): Prefixed with 0x or 0X.

51
Example: 0xA (which is 10 in decimal)

decimal_number = 10 # Decimal

binary_number = 0b1010 # Binary

octal_number = 0o12 # Octal

hexadecimal_number = 0xA # Hexadecimal

b. Floating-Point Literals

Floats represent real numbers that have a decimal point.

They can also be written in scientific notation (exponential form), where e


or E indicates the power of 10.

Examples:

float_number = 3.14 # Standard float

negative_float = -0.001 # Negative float

52
scientific_float = 1.5e2 # Scientific notation (1.5 *
10^2 = 150.0)

c. Complex Literals

Complex numbers consist of a real part and an imaginary part.

The imaginary part is represented with a suffix j or J.

Example:

complex_number = 3 + 4j # Complex number with real


part 3 and imaginary part 4

2. String Literals

String literals represent sequences of characters, enclosed within single


quotes ('), double quotes ("), triple single quotes ('''), or triple double
quotes ("""). Strings can include letters, numbers, symbols, and spaces.

a. Single-line Strings

Single-line strings are enclosed in either single quotes (') or double quotes
(").

Examples:

53
single_quote_string = 'Hello'

double_quote_string = "World"

b. Multi-line Strings

Multi-line strings are enclosed in triple quotes (''' or """). They can span
multiple lines and are often used for docstrings or longer text blocks.

Examples:

multi_line_string = '''This is a multi-line string'''

c. Escape Sequences in Strings

Escape sequences allow you to include special characters in strings, such


as newlines (\n), tabs (\t), backslashes (\\), and quotes (\', \").

Examples:

54
escaped_string = "He said, \"Hello!\""

newline_string = "First line\nSecond line"

d. Raw Strings

Raw strings are prefixed with an r or R, and they treat backslashes (\) as
literal characters, meaning escape sequences are not processed.

Example:

raw_string = r"C:\Users\Name\Documents"

3. Boolean Literals

Boolean literals represent the two truth values in Python: True and
False. These literals are used in conditional expressions and logical
operations.

Examples:

is_true = True

is_false = False

55
4. None Literal

None is a special literal in Python that represents the absence of a value or


a null value. It is often used to signify that a variable has no value or to
indicate the end of a list in certain algorithms.

Example

empty_value = None

5. Collection Literals

Python also supports literals for collections such as lists, tuples,


dictionaries, and sets.

a. List Literals

Lists are ordered, mutable collections of items, enclosed in square brackets


([]).

Lists can contain elements of different types.

Example:

my_list = [1, 2, 3, "apple", True]

b. Tuple Literals

56
Tuples are ordered, immutable collections of items, enclosed in
parentheses (()).

Like lists, tuples can contain elements of different types.

Example:

my_tuple = (1, 2, 3, "apple", True)

c. Dictionary Literals

Dictionaries are collections of key-value pairs, enclosed in curly braces


({}).

Keys and values can be of any data type, and each key is associated with
a value.

Example:

my_dict = {"name": "Alice", "age": 25, "is_student":


False}

d. Set Literals

57
Sets are unordered collections of unique items, enclosed in curly braces
({}).

Sets do not allow duplicate elements.

Example:

my_set = {1, 2, 3, 4, 5}

6. Special Literals

Python also has special literals, such as Ellipsis (...), which is used in
certain advanced features like slicing multi-dimensional arrays in NumPy.

Example:

ellipsis_literal = ...

Summary of Literals:

Numeric Literals: Integers, floats, and complex numbers.

String Literals: Sequences of characters enclosed in quotes (single,


double, or triple).

Boolean Literals: True and False.

None Literal: Represents the absence of a value.

58
Collection Literals: Lists ([]), tuples (()), dictionaries ({}), and sets ({}).

Special Literals: Ellipsis (...) and others used in specific contexts.

Literals are fundamental in Python as they directly represent values that


variables can hold. Understanding literals helps in writing clear and concise
code.

OPERATORS

In Python, operators are special symbols or keywords used to perform


operations on variables and values. Python supports various types of
operators :

1. Assignment operator =

●​ Assignment: Used to assign a value to a variable. Example: x = 5.

2. Comparison operators

●​ Equality (==): Checks if two values are equal. Example: if x ==


5:.
●​ Inequality (!=): Checks if two values are not equal. Example: if x
!= 5:.

59
●​ Greater than (>), Less than (<), Greater than or equal to (>=), Less
than or equal to (<=)**: Used for comparisons. Example: if x > 5:.

3. Logical operators

●​ And (and): Returns True if both operands are true. Example: if x


> 5 and y < 10:.
●​ Or (or): Returns True if at least one operand is true. Example: if x
> 5 or y < 10:.
●​ Not (not): Negates a Boolean expression. Example: if not x >
5:.

4. Ellipsis ...

●​ Placeholder: Used as a placeholder for future code or in slicing


operations. Example: def incomplete_func(...):.

4. Operators +, -, *, /, etc.

●​ Arithmetic operations: These punctuators are used for


mathematical operations.
○​ Addition (+): a + b.
○​ Subtraction (-): a - b.
○​ Multiplication (*): a * b.
○​ Division (/): a / b.
○​ Modulus (%): a % b.
○​ Exponentiation (**): a ** b.

5. Double Asterisk **

60
●​ Exponentiation: Used for raising numbers to a power. Example: x =
2 ** 3.
●​ Dictionary unpacking: Used to unpack dictionaries. Example:
function(**my_dict).

6. At symbol @

Decorators: Used to define decorators in Python, which are functions that


modify other functions. Example:​
@my_decorator

def my_function():

pass

7. Backslash \

Line continuation: Used to split long statements into multiple lines.


Example:​
long_expression = a + b + c + \ d + e + f

8. Tilde ~

●​ Bitwise negation: Performs bitwise negation. Example: ~x.

61
9. Pipe |

●​ Bitwise OR: Performs bitwise OR between two numbers. Example: x


| y.

10. Ampersand &

●​ Bitwise AND: Performs bitwise AND between two numbers.


Example: x & y.

11. Caret ^

●​ Bitwise XOR: Performs bitwise XOR between two numbers.


Example: x ^ y.

12. Plus-equal +=, Minus-equal -=, etc.

●​ Augmented assignment: These are used for shorthand assignment.


Example: x += 5 (equivalent to x = x + 5).

13. Colon-equal := (Walrus operator)

●​ Assignment expression: Assigns a value to a variable as part of an


expression. Example:
●​ if (n := len(data)) > 10:.

14. Underscore _

●​ Ignored variable: Commonly used as a variable name when the


value is to be ignored. Example: for _ in range(5):.

62
●​ Name mangling: Used in class methods to prevent accidental
access to private variables. Example: __my_var.

15. Single and Double Quotes ' ' / " "

●​ String literals: Used to denote strings in Python. Example: 'hello'


or "hello".

16. Triple Quotes ''' ''' / """ """

Multiline strings: Used for strings that span multiple lines. Example:​

"""This is

a multiline

string."""

17. Hash #

●​ Comments: Used to write single-line comments. Example: # This


is a comment.

18. Double Forward Slash //

63
●​ Floor division: Used to perform integer division. Example: 7 // 2
results in 3.

19. Percent %

●​ Modulo operator: Used to get the remainder of a division. Example:


7 % 2.
●​ String formatting (old style): Example: "Name: %s" % "Alice".

Operators can be categorized as follows:

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations between


two values or variables.

Operator Description Example Output

+ Addition 5 + 3 8

- Subtraction 5 - 3 2

64
* Multiplication 5 * 3 15

/ Division (returns 5 / 2 2.5


float)

% Modulus 5 % 2 1
(remainder)

** Exponentiation 2 ** 3 8
(power)

// Floor division 5 // 2 2
(returns integer)

2. Comparison (Relational) Operators

Comparison operators compare two values and return either True or


False.

65
Operator Description Example Output

== Equal to 5 == 3 False

!= Not equal to 5 != 3 True

> Greater than 5 > 3 True

< Less than 5 < 3 False

>= Greater than or 5 >= 5 True


equal to

<= Less than or 5 <= 3 False


equal to

3. Logical Operators

66
Logical operators combine conditional statements and return a boolean
value.

Operator Description Example Output

and Returns True if (5 > 3) and True


both are true (5 < 10)

or Returns True if (5 > 3) or True


at least one is (5 > 10)
true

not Reverses the not(5 > 3) False


logical state

4. Assignment Operators

Assignment operators are used to assign values to variables.

Operator Description Example Equivalent To

67
= Assigns value x = 5 x = 5

+= Adds and x += 3 x = x + 3
assigns

-= Subtracts and x -= 3 x = x - 3
assigns

*= Multiplies and x *= 3 x = x * 3
assigns

/= Divides and x /= 3 x = x / 3
assigns

%= Modulus and x %= 3 x = x % 3
assigns

68
//= Floor division x //= 3 x = x // 3
and assigns

**= Exponent and x **= 3 x = x ** 3


assigns

5. Bitwise Operators

Bitwise operators operate on bits and perform bit-by-bit operations.

Operator Description Example Output

& Bitwise AND 5 & 3 1

` ` Bitwise OR `5

^ Bitwise XOR 5 ^ 3 6

69
~ Bitwise NOT ~5 -6

<< Left shift 5 << 1 10

>> Right shift 5 >> 1 2

6. Membership Operators

Membership operators are used to test whether a value or variable is found


in a sequence (such as a list, string, or tuple).

Operator Description Example Output

in Returns True if 'a' in True


value is found 'apple'

70
not in Returns True if 'b' not in True
value is not 'apple'
found

7. Identity Operators

Identity operators are used to compare objects by their memory locations


(identity), not by their values.

Operator Description Example Output

is Returns True if x is y Depends


both variables
point to the
same object

is not Returns True if x is not y Depends


both variables
point to different
objects

71
8. Ternary Operator

The ternary operator allows conditional expressions in a compact form.

Syntax:

value_if_true if condition else value_if_false

Example:

x = 5

result = "Even" if x % 2 == 0 else "Odd"

print(result) # Output: Odd

9. Operator Precedence

Operator precedence determines the order in which operators are


evaluated. For example, multiplication and division take precedence over
addition and subtraction. Parentheses () can be used to override this
precedence.

These are the core operators in Python, providing flexibility to handle


different operations in mathematical, logical, and custom contexts.

72
PUNCTUATORS

In Python, punctuators are special symbols that serve as operators or


delimiters, which define the structure of Python code. They are essential for
defining the relationships between objects, statements, and blocks. Below
is a detailed explanation of common punctuators in Python:

1. Parentheses ( )

●​ Function calls: Used to invoke functions. Example:


print("Hello").
●​ Grouping expressions: Used to group expressions and control
precedence in operations. Example: 2 * (3 + 4).

2. Square brackets [ ]

●​ List: Used to create lists. Example: my_list = [1, 2, 3].


●​ Indexing: Used for accessing elements in lists, tuples, or strings.
Example: my_list[0] or my_string[2].
●​ Slicing: Used for slicing sequences like lists or strings. Example:
my_list[1:3].

3. Curly braces { }

●​ Dictionaries: Used to create dictionaries. Example: my_dict =


{"key": "value"}.

73
●​ Set: Also used to define sets. Example: my_set = {1, 2, 3}.
●​ Formatted strings (f-strings): Used in f-strings to embed
expressions. Example: f"Value is {variable}".

4. Colon :

●​ Function definition: Used to define the beginning of a function body.


Example: def my_function():.
●​ Class definition: Used to define a class body. Example: class
MyClass:.
●​ For, while, if, elif, else blocks: Used to define the beginning of
control flow blocks. Example: if condition:.
●​ Dictionary key-value separator: Used to separate keys from values
in a dictionary. Example: {"name": "John"}.

5. Semicolon ;

●​ Multiple statements on a single line: You can use a semicolon to


separate multiple statements on a single line, though it is not
recommended in Python. Example: x = 5; y = 10.

6. Comma ,

●​ Function arguments: Used to separate arguments in function calls.


Example: print(a, b, c).
●​ List, tuple, and dictionary items: Used to separate elements in lists,
tuples, and dictionaries. Example: my_tuple = (1, 2, 3).

74
●​ Multiple assignment: Used to assign multiple variables in one line.
Example: x, y = 1, 2.

7. Period .

●​ Attribute access: Used to access an attribute or method of an


object. Example: object.method().
●​ Floating-point numbers: Used in defining floating-point numbers.
Example: pi = 3.14.

These punctuators allow Python to interpret the structure, logic, and flow of
your code effectively.

ERRORS

Python, errors and exceptions are inevitable, and they occur when the
interpreter encounters something that prevents the program from
executing. The three main categories of errors are syntax errors, logical
errors, and runtime errors. Let's explore each in detail:

1. Syntax Errors

Definition:​
A syntax error occurs when the Python interpreter encounters invalid
syntax. In simpler terms, the code does not follow the rules and structure

75
that Python expects. These errors are usually caught by the interpreter at
the time of code parsing before execution begins.

Common Causes:

●​ Missing colons (:) at the end of control structures.


●​ Mismatched parentheses or brackets.
●​ Misspelled keywords (e.g., Print instead of print).
●​ Incorrect indentation (since Python relies heavily on indentation).

Example:

if x > 5 # Syntax error: missing colon

print("x is greater than 5")

Error Message:

SyntaxError: invalid syntax

Characteristics:

●​ Detected at compile-time (before the code runs).


●​ The program will not run until all syntax errors are corrected.
●​ Easily identifiable because the interpreter pinpoints the line with the
error.

2. Logical Errors

76
Definition:​
Logical errors occur when the program runs successfully but produces
incorrect or unintended results. These errors are due to a flaw in the logic
or algorithm used in the code, but Python itself does not flag these as
errors because they are technically valid operations.

Common Causes:

●​ Using incorrect formulas or conditions.


●​ Incorrectly updating or modifying values.
●​ Errors in the logic flow, such as wrong loops or condition checks.

Example:

x = 10

y = 5

print("The average is:", x + y / 2) # Logical error:


this is not the correct formula for average

Here, the program runs successfully but gives an incorrect output because
the formula for calculating the average is wrong. The correct formula
should be (x + y) / 2.

Characteristics:

●​ Detected at runtime but are not raised as exceptions.

77
●​ The program continues running normally, but it produces the wrong
results.
●​ Debugging logical errors requires testing and analyzing the output.

3. Runtime Errors (Exceptions)

Definition:​
Runtime errors occur while the program is running, leading to abnormal
termination. Unlike syntax errors, the code passes the initial parsing stage
but fails during execution. These errors are typically caused by illegal
operations, such as division by zero, invalid memory access, or
file-handling issues.

Common Causes:

●​ Dividing a number by zero.


●​ Accessing variables that are not defined.
●​ Trying to open a file that does not exist.
●​ Performing an invalid operation on a data type (e.g., adding a string
to an integer).

Example 1: Division by Zero

x = 10

y = 0

print(x / y) # Runtime error: division by zero

78
Error Message:

ZeroDivisionError: division by zero

Example 2: Accessing Undefined Variables

print(z) # Runtime error: variable 'z' is not defined

Error Message:

NameError: name 'z' is not defined

Example 3: File Handling Error

f = open('non_existent_file.txt') # Runtime error:


file does not exist

Error Message:

FileNotFoundError: [Errno 2] No such file or directory:


'non_existent_file.txt'

Characteristics:

79
●​ Detected at runtime (during the execution of the program).
●​ Can cause the program to terminate unless handled properly.
●​ Python provides mechanisms for handling runtime errors through
exception handling using try and except blocks.

Handling Runtime Errors with Exception Handling

In Python, runtime errors can be handled using try-except blocks to


prevent the program from crashing. This ensures that the program handles
the error gracefully.

Example:

try:

x = 10 / 0 # This will cause a ZeroDivisionError

except ZeroDivisionError:

print("You can't divide by zero!")

# The program continues to run normally

print("Program continues...")

Output:

80
You can't divide by zero!

Program continues...

Summary of Differences:

Type of Error When Detected Effect on Example


Program

Syntax Error Compile-time Prevents code Missing colon in


from running an if statement

Logical Error Run-time (no Program runs Incorrect formula


crash) but produces for a calculation
incorrect results

Runtime Error Run-time (crash) Causes the Division by zero,


program to accessing
terminate undefined
unexpectedly variables

Types of Runtime Errors:

Here are some common types of runtime errors (exceptions) in Python:

●​ ZeroDivisionError: When trying to divide by zero.


●​ NameError: When a variable is used before it has been defined.

81
●​ TypeError: When an operation is applied to an object of
inappropriate type.
●​ IndexError: When trying to access an index that is out of range in
a list or tuple.
●​ KeyError: When trying to access a dictionary with a key that doesn't
exist.
●​ FileNotFoundError: When trying to open a file that doesn’t exist.
●​ ValueError: When a function receives an argument of the correct
type but inappropriate value.
●​ ImportError: When an import statement fails to find the module
definition.

These errors can be prevented through careful testing, and runtime errors
can be managed through exception handling, ensuring the program
continues to function even in exceptional circumstances.

UNIT II

1.​ Expression
2.​ Evaluation of an expression
3.​ Type-conversion
4.​ Flow of Control,

82
5.​ Conditional statements
6.​ Iterative Statements

1. Expression
An expression in Python is a combination of values, variables, operators, and function

calls that are evaluated to produce another value. An expression can be as simple as a

single value or as complex as a function call involving several operations.

Example of an expression:

x = 5 + 3 * 2 # 5 + 6 = 11

Here, 5 + 3 * 2 is an expression. It combines numbers and operators (+, *) and is

evaluated to the result 11.

Expressions can include:

●​ Literal values: 5, "hello", True


●​ Variables: x, y, etc.
●​ Operators: +, -, *, etc.
●​ Function calls: len(my_list)

2. Evaluation of an Expression
Evaluation refers to the process of executing an expression and obtaining a final result.

Python follows the rules of operator precedence to determine the order in which parts of

the expression are evaluated. After each operation is performed, Python moves on to

the next until the final value is produced.

83
Example:

x = 10

y = 5

result = (x + 2) * (y - 3) # Evaluates as (10 + 2) * (5 - 3) = 12 * 2 = 24

3. Type Conversion (Type Casting)


Type conversion (also called type casting) refers to converting one data type to another

in Python. There are two types of type conversion:

●​ Implicit Type Conversion (Automatic): Python automatically converts one data


type to another when needed.
●​ Explicit Type Conversion: The programmer manually converts one data type to
another using built-in functions like int(), float(), str(), etc.

Example of Implicit Conversion:

x = 5 # int

y = 2.5 # float

result = x + y # Python automatically converts x to a float print(result)

# Output: 7.5

Example of Explicit Conversion:

x = "100"

y = int(x) # Explicitly converting

string to integer

84
print(y + 10) # Output: 110

4. Flow of Control
Flow of control determines the order in which individual statements, instructions, or

function calls are executed or evaluated. In Python, the flow of control is determined by

the following types of statements:

●​ Sequential statements: Python executes instructions one by one, in sequence.


●​ Conditional statements: Python makes decisions based on conditions (if
statements).
●​ Iterative statements: Python repeats certain blocks of code using loops (for, while
loops).

Example:

x = 10

if x > 5:

print("x is greater than 5") #

Conditional flow of control

else:

print("x is less than or equal

to 5")

5. Conditional Statements

85
Conditional statements allow Python to make decisions based on certain conditions.

These are implemented using the if, elif, and else keywords.

●​ if statement: Executes a block of code if a condition is true.


●​ elif statement: Used after an if statement to check multiple conditions.
●​ else statement: Executes a block of code if none of the conditions are true.

Syntax:

if condition:

# Block of code executed if

condition is true

elif another_condition:

# Block of code executed if

another_condition is true

else:

# Block of code executed if none

of the above conditions are true

Example:

x = 8

if x > 10:

print("x is greater than 10") elif x == 8:

86
print("x is equal to 8")

else:

print("x is less than 8")

Output:

x is equal to 8

Nested if statements:
You can also nest if statements inside each other to evaluate multiple conditions in

sequence.

x = 10

if x > 5:

if x < 20:

print("x is b/w 5 and 20")

6. Iterative Statements (Loops)


Loops are used to execute a block of code repeatedly. Python provides two types of

loops:

●​ for loop: Iterates over a sequence (such as a list, tuple, string, or range).
●​ while loop: Repeats as long as a condition is true.

6.1. for loop

87
The for loop is used to iterate over elements in a sequence or range.

Syntax:

for item in sequence: # Code to

execute in the loop

Example:

for i in range(5): # range(5)

generates numbers 0 to 4

print(i)

Output:

0 1 2 3 4

Looping through a list:

my_list = [1, 2, 3, 4]

for item in my_list:

print(item)

6.2. while loop


The while loop keeps executing as long as a certain condition is true.

Syntax:

while condition: # Code to execute in the loop

Example:

88
x = 5

while x > 0:

print(x)

x -= 1 # Decrement x

Output:

5 4 3 2 1

Controlling Loops:
●​ break statement: Exits the loop immediately.
●​ continue statement: Skips the current iteration and proceeds to the next
iteration.
●​ else with loops: The else clause is executed if the loop completes all iterations
without encountering a break statement.

Example with break:

for i in range(10):

if i == 5:

break # Loop stops when i is 5

print(i)

Output:

0 1 2 3 4

89
Example with continue:

for i in range(5):

if i == 2:

continue # Skips the current iteration when i is 2

print(i)

Output:

0 1 3 4

Example with else in a loop:

for i in range(5):

print(i)

else:

print("Loop completed successfully.")

Output:

0 1 2 3 4

Loop completed successfully.

7. Difference Between for and while Loops


●​ for loop: Used when the number of iterations is known (e.g., iterating over a list
or a range of numbers).

90
●​ while loop: Used when the condition is more dynamic, or the number of
iterations is unknown beforehand (e.g., when waiting for a condition to become
false).

Example Using for Loop:

for i in range(3):

print("Hello")

This loop prints "Hello" 3 times, as the number of iterations is known.

Example Using while Loop:

x = 3

while x > 0:

print("Hello")

x -= 1

This loop prints "Hello" while x is greater than 0, and the iterations depend on the

changing value of x.

Conclusion
●​ Expressions: Combinations of variables and operators that are evaluated to a
result.
●​ Evaluation: The process of calculating the value of an expression.
●​ Type Conversion: Changing data types explicitly or implicitly.
●​ Flow of Control: Determines the execution path of a program.
●​ Conditional Statements: Control decision-making in the program.

91
●​ Iterative Statements (Loops): Repeat actions in a controlled manner using for
and while loops.

Strings in Python

A string in Python is a sequence of characters enclosed within single (' '),


double (" "), or triple quotes (''' ''', """ """). Strings are immutable, meaning
once created, their contents cannot be changed.

String Operations

Concatenation: Combining two or more strings using the + operator.

str1 = "Hello"

str2 = "World"

92
result = str1 + " " + str2

# Output: "Hello World"

Repetition: Repeating a string multiple times using the * operator.

result = "Hello" * 3

# Output: "HelloHelloHello"

Membership: Checking if a substring exists within a string using the in


operator.

result = "Hello" in "Hello World"

# Output: True

93
Slicing: Extracting a portion of the string using slice notation
[start:end:step].

str1 = "Hello World"

result = str1[0:5] # Output: "Hello"

result = str1[-5:] # Output: "World"

Traversing a String Using Loops

You can traverse a string using for or while loops to access each character:

for char in "Hello":

print(char)

This will print each character of the string "Hello" on a new line.

94
Built-in String Functions and Methods

len(): Returns the length of the string.

len("Hello")

# Output: 5

capitalize(): Capitalizes the first character of the string.

"hello world".capitalize()

# Output: "Hello world"

title(): Capitalizes the first character of each word in the string.

"hello world".title()

95
# Output: "Hello World"

lower(): Converts all characters in the string to lowercase.

"Hello".lower()

# Output: "hello"

upper(): Converts all characters in the string to uppercase.

"hello".upper()

# Output: "HELLO"

count(substring): Counts the occurrences of a substring in the string.

"hello hello".count("hello")

96
# Output: 2

find(substring): Returns the index of the first occurrence of a substring, or


-1 if not found.

"hello".find("l")

# Output: 2

index(substring): Similar to find() but raises a ValueError if the substring is


not found.

"hello".index("l")

# Output: 2

endswith(suffix): Checks if the string ends with the given suffix.

97
"hello".endswith("lo")

# Output: True

startswith(prefix): Checks if the string starts with the given prefix.

"hello".startswith("he")

# Output: True

isalnum(): Returns True if all characters in the string are alphanumeric


(letters or digits).

"Hello123".isalnum()

# Output: True

isalpha(): Returns True if all characters in the string are alphabetic.

98
"Hello".isalpha()

# Output: True

isdigit(): Returns True if all characters in the string are digits.

"1234".isdigit()

# Output: True

islower(): Returns True if all alphabetic characters in the string are


lowercase.

"hello".islower()

# Output: True

99
isupper(): Returns True if all alphabetic characters in the string are
uppercase.

"HELLO".isupper()

# Output: True

isspace(): Returns True if the string contains only whitespace characters.

" ".isspace()

# Output: True

lstrip(): Removes leading whitespace from the string.

" hello".lstrip()

# Output: "hello"

100
rstrip(): Removes trailing whitespace from the string.

"hello ".rstrip()

# Output: "hello"

strip(): Removes both leading and trailing whitespace.

" hello ".strip()

# Output: "hello"

replace(old, new): Replaces all occurrences of the old substring with the
new substring.

"hello world".replace("world", "Python")

# Output: "hello Python"

101
join(iterable): Joins the elements of an iterable (like a list) into a string,
separated by the string it's called on.

"-".join(["hello", "world"])

# Output: "hello-world"

partition(separator): Splits the string into three parts: the part before the
separator, the separator itself, and the part after.

"hello world".partition(" ")

# Output: ('hello', ' ', 'world')

split(separator): Splits the string into a list of substrings, separated by the


given separator.

"hello world".split(" ")

102
# Output: ['hello', 'world']

Summary

Strings in Python are powerful and come with various built-in operations
and methods that make manipulation easy, such as concatenation,
repetition, slicing, and several others for transforming and analyzing the
content.

ARRAY IN PYTHON

In Python, arrays can be managed using lists, as Python does not have a
dedicated array data type like some other languages (such as C or Java).
Lists are versatile, dynamic, and allow elements of any data type. Here's a
detailed explanation of common array (or list) operations in Python.

1. Accessing the Elements of an Array

103
To access an element in a list, you use its index in square brackets.
Indexing in Python starts at 0, so the first element is at index 0, the second
at index 1, and so on.

# Define a list

arr = [10, 20, 30, 40, 50]

# Access elements

print(arr[0]) # Output: 10

print(arr[2]) # Output: 30

print(arr[-1]) # Output: 50 (negative index, starts


from end)

2. Length of an Array

To get the length (number of elements) in a list, use the len() function.

104
arr = [10, 20, 30, 40, 50]

print(len(arr)) # Output: 5

3. Adding Array Elements

Python lists support several methods for adding elements:

●​ append(element): Adds an element to the end of the list.


●​ insert(position, element): Adds an element at a specified
index.
●​ extend(iterable): Adds multiple elements from another list or
iterable.

Example

arr = [10, 20, 30]

# Append a single element

arr.append(40)

105
print(arr) # Output: [10, 20, 30, 40]

# Insert an element at a specific position

arr.insert(1, 15) # Adds 15 at index 1

print(arr) # Output: [10, 15, 20, 30, 40]

# Extend with multiple elements

arr.extend([50, 60])

print(arr) # Output: [10, 15, 20, 30, 40, 50, 60]

106
4. Removing Array Elements

Python provides various methods for removing elements from a list:

●​ remove(element): Removes the first occurrence of the specified


element.
●​ pop(index): Removes the element at a specified index (default is
the last element if no index is provided).
●​ clear(): Removes all elements from the list, leaving it empty.

Example

arr = [10, 20, 30, 40, 50]

# Remove a specific element by value

arr.remove(30)

107
print(arr) # Output: [10, 20, 40, 50]

# Remove an element by index

arr.pop(1)

print(arr) # Output: [10, 40, 50]

# Remove the last element

arr.pop()

print(arr) # Output: [10, 40]

108
# Clear all elements

arr.clear()

print(arr) # Output: []

5. Adding and Removing Elements at a Specified Position

You can use the insert() method to add an element at a specific position
and the pop() method with an index to remove an element at a specific
position.

Example

arr = [10, 20, 30, 40, 50]

109
# Adding an element at index 2

arr.insert(2, 25) # Insert 25 at index 2

print(arr) # Output: [10, 20, 25, 30, 40, 50]

# Removing the element at index 3

arr.pop(3) # Removes the element at index 3

print(arr) # Output: [10, 20, 25, 40, 50]

Summary

●​ Accessing Elements: Use list[index] to access an element.


●​ Length: Use len(list) to get the number of elements.

110
●​ Adding Elements: Use append(), insert(), or extend() to add
elements.
●​ Removing Elements: Use remove(), pop(), or clear() to
remove elements.
●​ Adding/Removing at Specific Position: Use insert(position,
element) to add, and pop(index) to remove elements at a
specific position.

These operations make lists in Python a flexible tool for handling arrays.

Lists in Python
A list in Python is an ordered, mutable, and dynamic collection that allows
elements of different data types. Lists are one of the most versatile data
structures in Python and are used widely for data storage and
manipulation.

1. Introduction to Lists

Lists are created by placing elements inside square brackets [ ],


separated by commas. Elements can be of any data type, and lists can
contain duplicate items.

# Creating a list

111
my_list = [1, 2, 3, 4, 5]

mixed_list = [10, "Python", True, 4.5]

2. Indexing in Lists

Elements in a list are accessed by their index, with the first element at
index 0. Negative indexing allows access from the end of the list.

my_list = [10, 20, 30, 40, 50]

# Accessing elements by positive index

print(my_list[0]) # Output: 10

print(my_list[2]) # Output: 30

# Accessing elements by negative index

print(my_list[-1]) # Output: 50 (last element)

print(my_list[-3]) # Output: 30 (third element from the


end)

112
3. List Operations

Concatenation: Combine lists using the + operator.​

list1 = [1, 2, 3]

list2 = [4, 5]

result = list1 + list2 # Output: [1, 2, 3, 4, 5]

●​

Repetition: Repeat elements in a list using the * operator.​

list1 = [1, 2]

result = list1 * 3 # Output: [1, 2, 1, 2, 1, 2]

●​

Slicing: Extract a portion of the list using [start:end:step].​

my_list = [10, 20, 30, 40, 50]

print(my_list[1:4]) # Output: [20, 30, 40]

print(my_list[:3]) # Output: [10, 20, 30]

●​

113
4. Traversing a List Using Loops

You can use a for or while loop to iterate through each element in a list.

my_list = [10, 20, 30, 40]

# Using a for loop

for item in my_list:

print(item)

# Using a while loop

i = 0

while i < len(my_list):

print(my_list[i])

i += 1

5. Built-in Functions and Methods for Lists

len(), list()

114
len(): Returns the number of elements in the list.

len([10, 20, 30]) # Output: 3

●​

list(): Converts other iterables (like tuples or strings) to lists.​

list("hello") # Output: ['h', 'e', 'l', 'l', 'o']

●​

Append, Extend, Insert

append(element): Adds a single element to the end of the list.​

my_list = [1, 2, 3]

my_list.append(4) # Output: [1, 2, 3, 4]

●​

extend(iterable): Adds multiple elements from another list or iterable


to the end of the list.​

my_list = [1, 2, 3]

my_list.extend([4, 5]) # Output: [1, 2, 3, 4, 5]

115
●​

insert(index, element): Inserts an element at a specific index.

my_list = [1, 2, 4]

my_list.insert(2, 3) # Output: [1, 2, 3, 4]

●​

Count, Index

count(element): Returns the number of occurrences of a specified


element in the list.​

my_list = [1, 2, 2, 3, 2]

my_list.count(2) # Output: 3

●​

index(element): Returns the index of the first occurrence of a specified


element. Raises a ValueError if the element is not found.​

my_list = [1, 2, 3]

my_list.index(3) # Output: 2

●​

Remove, Pop

116
remove(element): Removes the first occurrence of the specified
element. Raises a ValueError if the element is not found.​

my_list = [1, 2, 3, 2]

my_list.remove(2) # Output: [1, 3, 2]

●​

pop(index): Removes and returns the element at the specified index. If


no index is specified, removes and returns the last element.​

my_list = [1, 2, 3]

my_list.pop(1) # Output: [1, 3]

my_list.pop() # Output: 3 (returns and removes the


last element)

●​

Reverse, Sort, Sorted

reverse(): Reverses the list in place.​


python​
Copy code​
my_list = [1, 2, 3]

my_list.reverse() # Output: [3, 2, 1]

117
●​

sort(): Sorts the list in ascending order (or descending if reverse=True


is specified).​

my_list = [3, 1, 2]

my_list.sort() # Output: [1, 2, 3]

my_list.sort(reverse=True) # Output: [3, 2, 1]

●​

sorted(list): Returns a new sorted list without modifying the original


list.​

my_list = [3, 1, 2]

sorted_list = sorted(my_list) # Output: [1, 2, 3]

●​

Min, Max, Sum

min(list): Returns the smallest element in the list.​

min([1, 2, 3]) # Output: 1

●​

118
max(list): Returns the largest element in the list.​

max([1, 2, 3]) # Output: 3

●​

sum(list): Returns the sum of all elements in the list. Elements must be
numeric.​

sum([1, 2, 3]) # Output: 6

●​

Summary

Lists in Python provide a wide range of functionality, from basic access and
modification to advanced sorting and aggregation functions. They support
various operations to facilitate data manipulation, making them a powerful
tool in Python programming.

Tuple
Tuples in Python

A tuple in Python is an ordered, immutable sequence of elements. Tuples are


similar to lists, but once a tuple is created, it cannot be modified (elements cannot
be added, removed, or changed). They are often used for data that should not

119
change throughout the program. Tuples are defined using parentheses ( ) and can
contain elements of any data type.

1. Introduction to Tuples

A tuple can hold any number of elements, including nested tuples or mixed data
types. They are defined by placing elements inside parentheses, separated by
commas.

# Creating tuples

my_tuple = (1, 2, 3)

mixed_tuple = (10, "Python", True, 4.5)

# Single element tuple (requires a trailing comma)

single_element_tuple = (42,)

2. Indexing in Tuples

Elements in a tuple are accessed using an index, just like in lists. Indexing starts at
0 for the first element, and negative indexing starts at -1 for the last element.

my_tuple = (10, 20, 30, 40, 50)

120
# Accessing elements by positive index

print(my_tuple[0]) # Output: 10

print(my_tuple[2]) # Output: 30

# Accessing elements by negative index

print(my_tuple[-1]) # Output: 50

print(my_tuple[-3]) # Output: 30

3. Tuple Operations

Since tuples are immutable, they support fewer operations than lists. You can still
concatenate and repeat tuples.

Concatenation: Combine tuples using the + operator.​


tuple1 = (1, 2, 3)

tuple2 = (4, 5)

result = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5)

121
Repetition: Repeat elements in a tuple using the * operator.​
tuple1 = (1, 2)

result = tuple1 * 3 # Output: (1, 2, 1, 2, 1, 2)

Slicing: Extract a portion of the tuple using [start:end:step].​


my_tuple = (10, 20, 30, 40, 50)

print(my_tuple[1:4]) # Output: (20, 30, 40)

print(my_tuple[:3]) # Output: (10, 20, 30)

4. Traversing a Tuple Using Loops

You can iterate through a tuple using a for loop to access each element.

my_tuple = (10, 20, 30, 40)

# Using a for loop

for item in my_tuple:

print(item)

122
# Using a while loop

i = 0

while i < len(my_tuple):

print(my_tuple[i])

i += 1

5. Built-in Functions and Methods for Tuples

len(), tuple(), list()

len(): Returns the number of elements in the tuple.​


my_tuple = (10, 20, 30)

print(len(my_tuple)) # Output: 3

tuple(): Converts other iterables (like lists or strings) to a tuple.​


tuple_from_list = tuple([1, 2, 3]) # Output: (1, 2, 3)

tuple_from_string = tuple("hello") # Output: ('h',


'e', 'l', 'l', 'o')

123
list(): Converts a tuple to a list, allowing modification.​
my_tuple = (1, 2, 3)

my_list = list(my_tuple) # Output: [1, 2, 3]

Count, Index

count(element): Returns the number of occurrences of a specified element in


the tuple.​
my_tuple = (1, 2, 2, 3, 2)

print(my_tuple.count(2)) # Output: 3

index(element): Returns the index of the first occurrence of a specified


element. Raises a ValueError if the element is not found.​
my_tuple = (1, 2, 3)

print(my_tuple.index(3)) # Output: 2

Note: Tuples do not have methods like append(), extend(), insert(), remove(), pop(),
reverse(), or sort(), as they are immutable.

min(), max(), sum()

min(tuple): Returns the smallest element in the tuple. All elements must be of
a comparable type (e.g., all integers or all strings).​
my_tuple = (10, 20, 30)

124
print(min(my_tuple)) # Output: 10

max(tuple): Returns the largest element in the tuple.​


my_tuple = (10, 20, 30)

print(max(my_tuple)) # Output: 30

sum(tuple): Returns the sum of all elements in the tuple. Elements must be
numeric.​
my_tuple = (10, 20, 30)

print(sum(my_tuple)) # Output: 60

Working with Tuples Example

Here’s a comprehensive example using tuples and various functions and methods:

# Creating and accessing tuples

my_tuple = (1, 3, 5, 7)

print("First element:", my_tuple[0]) # Output: 1

print("Last element:", my_tuple[-1]) # Output: 7

# Tuple operations

125
concat_tuple = my_tuple + (9, 11) #
Concatenation

print("Concatenated Tuple:", concat_tuple) # Output:


(1, 3, 5, 7, 9, 11)

repeat_tuple = my_tuple * 2 # Repetition

print("Repeated Tuple:", repeat_tuple) # Output:


(1, 3, 5, 7, 1, 3, 5, 7)

# Built-in functions

print("Length:", len(my_tuple)) # Output: 4

print("Min value:", min(my_tuple)) # Output: 1

print("Max value:", max(my_tuple)) # Output: 7

print("Sum:", sum(my_tuple)) # Output: 16

# Count and index methods

print("Count of 3:", my_tuple.count(3)) # Output: 1

print("Index of 5:", my_tuple.index(5)) # Output: 2

126
Summary

●​ Tuples are immutable, ordered collections.


●​ You can access tuple elements using indexing.
●​ Tuples support basic operations like concatenation, repetition, and slicing.
●​ You can traverse tuples using loops.
●​ Built-in functions like len(), min(), max(), and sum() work with
tuples, but mutating methods like append() or remove() do not exist
due to immutability.
●​ Common tuple methods include count() and index().

Tuples are used when you need a sequence of items that should remain constant
throughout the program.

Application example

Tuples are used in various applications where immutability, ordered data, or


grouping related data is important. Here are a few common applications of tuples
in Python:

1. Storing Coordinates

Tuples are often used to store fixed sets of related data, such as coordinates in a 2D
or 3D space.

127
# Representing a point in 2D space

point_2D = (10, 20)

# Representing a point in 3D space

point_3D = (5, 10, 15)

print("2D Point:", point_2D)

print("3D Point:", point_3D)

2. Returning Multiple Values from a Function

Tuples are useful when a function needs to return multiple values. Instead of
creating separate variables, the function can return a single tuple containing all the
values.

def get_student_details():

# Returning multiple values as a tuple

return "Alice", 22, "Physics"

128
# Unpacking the tuple into separate variables

name, age, major = get_student_details()

print(f"Name: {name}, Age: {age}, Major: {major}")

3. Dictionary Keys

Tuples are often used as keys in dictionaries when you need a composite key (more
than one piece of data to act as a key). Since tuples are immutable, they can be
used as dictionary keys, whereas lists cannot.

# Using a tuple as a composite key for a dictionary

location_data = {

(40.7128, -74.0060): "New York",

(34.0522, -118.2437): "Los Angeles",

(51.5074, -0.1278): "London"

# Accessing data using tuple keys

print(location_data[(40.7128, -74.0060)]) # Output:


"New York"

129
4. Storing Immutable Data in a Collection

Sometimes, you need a list of data items that should not be changed once created.
Using a list of tuples ensures that the data remains immutable.

# List of tuples representing student records (ID,


Name)

students = [

(101, "John Doe"),

(102, "Jane Smith"),

(103, "Emily Jones")

# Displaying all students

for student in students:

print(f"ID: {student[0]}, Name: {student[1]}")

5. Database Records

130
When fetching data from a database, each record can be represented as a tuple.
This helps to group all related fields together as an immutable sequence.

# Simulating data fetched from a database

record = ("John Doe", 35, "Software Engineer")

# Accessing database record data

print("Name:", record[0])

print("Age:", record[1])

print("Job:", record[2])

6. Representing Days of the Week, Months, or Other Constant Values

Since tuples are immutable, they are well-suited to storing constant data like the
days of the week, months, or other fixed categories.

# Representing days of the week

days_of_week = ("Sunday", "Monday", "Tuesday",


"Wednesday", "Thursday", "Friday", "Saturday")

# Accessing days of the week

131
print("First day of the week:", days_of_week[0])

print("Last day of the week:", days_of_week[-1])

7. Packing and Unpacking Data

Tuples make it easy to pack multiple values into one variable and later unpack
them. This can simplify code when handling related values together.

# Packing data into a tuple

employee_info = "Alice", "Developer", 75000

# Unpacking the tuple

name, position, salary = employee_info

print(f"Employee: {name}, Position: {position}, Salary:


${salary}")

Summary

Tuples provide an efficient way to group related data and work especially well
when data immutability is important, such as in storing database records, handling
multiple return values from functions, or using as keys in dictionaries. Their

132
immutability also makes tuples efficient and reliable for storing constant or fixed
data.

Dictionary
In Python, a dictionary is an unordered collection of key-value pairs.
Dictionaries are mutable, which means you can add, update, or delete items.
However, the keys must be unique and immutable (e.g., strings, numbers, or
tuples), while the values can be of any type.

1. Introduction to Dictionaries

Dictionaries are created using curly braces {} with key-value pairs separated by
colons :. Each key-value pair is separated by a comma.

# Creating a dictionary

my_dict = {

"name": "Alice",

"age": 25,

133
"profession": "Engineer"

# Accessing the dictionary

print(my_dict) # Output: {'name': 'Alice', 'age': 25,


'profession': 'Engineer'}

2. Indexing in Dictionaries

Dictionaries are not indexed by position but by keys. You can use a key to access
its associated value.

my_dict = {

"name": "Alice", "age": 25,

"profession": "Engineer"

134
# Accessing values using keys

print(my_dict["name"]) # Output: Alice

print(my_dict["age"]) # Output: 25

# Using the `get()` method (safe access)

print(my_dict.get("profession")) # Output: Engineer

print(my_dict.get("salary")) # Output: None

3. Dictionary Operations

Add, Update, and Remove Elements

●​ Adding a key-value pair: You can add new items by assigning a value to a new
key.
●​ Updating values: Assign a new value to an existing key.
●​ Removing items: Use del or pop() to remove elements.

my_dict = {"name": "Alice", "age": 25}

135
# Adding a key-value pair

my_dict["profession"] = "Engineer"

# Updating a value

my_dict["age"] = 26

# Removing a key-value pair

del my_dict["age"]

print(my_dict) # Output: {'name': 'Alice',


'profession': 'Engineer'}

4. Traversing a Dictionary Using Loops

You can iterate over the keys, values, or both using loops.

136
my_dict = {"name": "Alice", "age": 25, "profession":
"Engineer"}

# Iterating through keys

for key in my_dict:

print(key)

# Iterating through values

for value in my_dict.values():

print(value)

# Iterating through key-value pairs

for key, value in my_dict.items():

print(f"{key}: {value}")

5. Built-in Functions and Methods

len(), list()

137
len(dictionary): Returns the number of key-value pairs in the dictionary.​

my_dict = {"name": "Alice", "age": 25, "profession":


"Engineer"}

print(len(my_dict)) # Output: 3

●​

list(dictionary): Converts the dictionary keys into a list.​

my_dict = {"name": "Alice", "age": 25, "profession":


"Engineer"}

print(list(my_dict)) # Output: ['name', 'age',


'profession']

●​

append(), extend(), insert(), count(), index()

These methods are not applicable to dictionaries as they are specific to lists.

pop(), popitem(), remove()

●​ pop(key): Removes the specified key and returns its value.

138
●​ popitem(): Removes and returns the last key-value pair as a tuple (since
Python 3.7, dictionaries maintain insertion order).

my_dict = {"name": "Alice", "age": 25, "profession":


"Engineer"}

# Removing a specific key-value pair

profession = my_dict.pop("profession")

print(profession) # Output: Engineer

# Removing the last item

last_item = my_dict.popitem()

print(last_item) # Output: ('age', 25)

reverse(), sort()

Dictionaries cannot be reversed or sorted directly since they are unordered.


However:

139
●​ sorted(): Returns a sorted list of keys or values. It does not modify the
dictionary.

my_dict = {"name": "Alice", "age": 25, "profession":


"Engineer"}

# Sorting keys

sorted_keys = sorted(my_dict)

print(sorted_keys) # Output: ['age', 'name',


'profession']

# Sorting values

sorted_values = sorted(my_dict.values())

print(sorted_values) # Output: [25, 'Alice',


'Engineer']

min(), max(), sum()

●​ min(dictionary): Returns the smallest key.

140
●​ max(dictionary): Returns the largest key.
●​ sum(dictionary): Returns the sum of all keys (if numeric).

my_dict = {1: "Alice", 3: "Bob", 2: "Charlie"}

# Finding min and max keys

print(min(my_dict)) # Output: 1

print(max(my_dict)) # Output: 3

# Summing numeric keys

print(sum(my_dict)) # Output: 6

6. Additional Dictionary Methods

●​ keys(): Returns a view object of all keys.


●​ values(): Returns a view object of all values.
●​ items(): Returns a view object of key-value pairs as tuples.

141
●​ update(): Updates the dictionary with another dictionary or key-value
pairs.

my_dict = {"name": "Alice", "age": 25}

# Getting keys, values, and items

print(my_dict.keys()) # Output: dict_keys(['name',


'age'])

print(my_dict.values()) # Output:
dict_values(['Alice', 25])

print(my_dict.items()) # Output: dict_items([('name',


'Alice'), ('age', 25)])

# Updating the dictionary

my_dict.update({"profession": "Engineer", "age": 26})

print(my_dict) # Output: {'name': 'Alice', 'age': 26,


'profession': 'Engineer'}

142
Application Example

Storing and Accessing Student Grades

# Dictionary of student grades

grades = {"Alice": 85, "Bob": 90, "Charlie": 78}

# Add a new student

grades["David"] = 88

# Update a grade

grades["Alice"] = 95

# Remove a student

grades.pop("Charlie")

# Calculate average grade

143
average_grade = sum(grades.values()) / len(grades)

print(f"Average Grade: {average_grade:.2f}")

# Output the updated dictionary

print(grades) # Output: {'Alice': 95, 'Bob': 90,


'David': 88}

Summary

●​ Dictionaries are key-value pairs that provide fast lookups.


●​ You can access, add, update, or remove items using methods like get(),
pop(), and update().
●​ Traversal is done using loops and methods like keys(), values(), and
items().
●​ Built-in functions like len(), min(), max(), and sum() operate on keys
or values (when appropriate).

Ni

Python Modules and Importing Methods

144
In Python, modules are collections of functions, classes, and variables that help
organize and reuse code. You can import these modules using two main
approaches: import and from ... import.

1. Using import Statement

This method imports the entire module, allowing you to access its functions and
variables using the module name as a prefix.

Syntax:

import module_name

Example (Importing math module):

import math

# Using math functions with the module prefix

pi_value = math.pi

sqrt_value = math.sqrt(16)

ceil_value = math.ceil(4.2)

145
Advantages:

●​ Provides clarity by showing which module a function belongs to.


●​ Prevents name conflicts between functions from different modules.

2. Using from ... import Statement

This method imports specific functions or variables directly from a module,


allowing you to use them without the module prefix.

Syntax:

from module_name import function_name, variable_name

Example (Importing specific functions from math):

from math import pi, sqrt, ceil

# Directly using the imported functions and variables

print(pi) # 3.141592653589793

print(sqrt(25)) # 5.0

print(ceil(4.2)) # 5

146
Advantages:

●​ Makes code concise by avoiding repeated use of the module name.


●​ Useful when only a few functions are needed from a module.

3. Detailed Overview of math, random, and statistics Modules

1. math Module

Provides mathematical constants and functions for numerical operations.

Function/Constant Description Example Usage

pi Mathematical constant π print(math.pi)


(≈ 3.14159)

e Base of the natural print(math.e)


logarithm (≈ 2.718)

sqrt() Returns the square root math.sqrt(16) ->


4.0

ceil() Rounds a number up to math.ceil(4.2) ->


the nearest integer 5

147
floor() Rounds a number down math.floor(4.7)
to the nearest integer -> 4

pow() Returns x raised to the math.pow(2, 3) ->


power y 8.0

fabs() Returns the absolute math.fabs(-5) ->


value as a float 5.0

sin() Returns the sine of x (x in math.sin(math.pi/


radians) 2) -> 1.0

cos() Returns the cosine of x (x math.cos(0) ->


in radians) 1.0

tan() Returns the tangent of x math.tan(math.pi/


(x in radians) 4) -> 1.0

Example Usage:

from math import pi, e, sqrt, ceil, floor, pow, fabs,


sin, cos, tan

print(pi) # 3.141592653589793

148
print(e) # 2.718281828459045

print(sqrt(9)) # 3.0

print(ceil(3.7)) # 4

print(floor(3.7)) # 3

print(pow(2, 3)) # 8.0

print(fabs(-5)) # 5.0

print(sin(pi / 2)) # 1.0

print(cos(0)) # 1.0

print(tan(pi / 4)) # 1.0

2. random Module

Provides functions to generate random numbers.

Function Description Example Usage

random() Returns a random float random.random()


between 0.0 and 1.0 -> 0.12345

149
randint(a, b) Returns a random integer random.randint(1,
between a and b 10) -> 5
(inclusive)

randrange() Returns a random integer random.randrange(


from the range() 1, 10, 2) -> 3
sequence

Example Usage:

from random import random, randint, randrange

print(random())

# Example: 0.753849

print(randint(1, 6))

# Example: 4 (random number between 1 and 6)

print(randrange(1, 10, 2))

# Example: 7 (random odd number between 1 and 9)

3. statistics Module

150
Provides functions for statistical calculations.

Function Description Example Usage

mean() Returns the arithmetic statistics.mean([


mean of a data set 1, 2, 3]) -> 2

median() Returns the median statistics.median


(middle value) ([1, 3, 5]) -> 3

mode() Returns the most statistics.mode([


common data point 1, 1, 2, 3]) -> 1

Example Usage:

from statistics import mean, median, mode

data = [1, 2, 2, 3, 4, 4, 4, 5]

print(mean(data)) # 3.125

print(median(data)) # 3.5

print(mode(data)) # 4

151
Summary

●​ import module_name: Imports the entire module, requiring


module_name.function() to access.
●​ from module_name import ...: Imports specific functions or
variables directly.
●​ math, random, and statistics modules provide powerful tools for
mathematical operations, random number generation, and statistical analysis.

Functions in Python

A function is a block of reusable code that performs a specific task. It


allows code reuse, modularity, and improved readability.

1. Types of Functions

1.​ Built-in Functions​


Python comes with many pre-defined functions.​
Examples:
○​ print(): Displays output.
○​ len(): Returns the length of an object.
○​ sum(): Returns the sum of a list of numbers.

152
print("Hello, World!") # Built-in function

print(len([1, 2, 3, 4])) # Output: 4

print(sum([1, 2, 3, 4])) # Output: 10

2.​ Functions Defined in a Module​


Functions that belong to imported libraries or modules.​
Examples:
○​ math.sqrt(): Returns the square root of a number (from
math module).

import math

print(math.sqrt(16)) # Output: 4.0

3.​ User-Defined Functions​


Functions created by users for specific tasks.​
Example:​

def greet(name):

return f"Hello, {name}!"

153
print(greet("Alice")) # Output: Hello, Alice!

2. Function Arguments

Arguments are values passed to functions when called.

Positional Arguments​
Arguments passed in order.​

def add(a, b):

return a + b

print(add(5, 3)) # Output: 8

1.​ Default Parameters​


Provides a default value if no argument is passed.​

def greet(name="World"):

return f"Hello, {name}!"

print(greet()) # Output: Hello, World!

154
print(greet("Alice")) # Output: Hello, Alice!

2.​ Keyword Arguments​


Arguments passed using key-value pairs.​

def describe_pet(pet_name, animal_type="dog"):

return f"I have a {animal_type} named {pet_name}."

print(describe_pet(pet_name="Buddy")) # Output: I have


a dog named Buddy.

3. Function Returning Values

Functions can return a single value or multiple values.

Single Return Value​

def square(x):

return x * x

155
print(square(4)) # Output: 16

1.​ Multiple Return Values​

def math_operations(a, b):

return a + b, a - b, a * b, a / b

add, subtract, multiply, divide = math_operations(10,


2)

print(add, subtract, multiply, divide) # Output: 12 8


20 5.0

4. Recursion

A function calling itself.

Example: Factorial Calculation

def factorial(n):

if n == 0:

156
return 1

else:

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

5. Scope of a Variable

Scope determines where a variable can be accessed.

Local Scope​
Variables declared inside a function.​

def example():

x = 5 # Local variable

print(x)

example() # Output: 5

# print(x) # Error: x is not defined

157
1.​ Global Scope​
Variables declared outside functions.​

x = 10 # Global variable

def example():

print(x)

example() # Output: 10

2.​ Modifying Global Variable in Function​


x = 10

def modify_global():

global x

x += 5

modify_global()

print(x) # Output: 15

158
Summary

Concept Example

Built-in Functions print(), len(), sum()

Module Functions math.sqrt(),


random.randint()

User-Defined Functions def custom_func(): ...

Positional Arguments add(2, 3)

Default Parameters greet(name="World")

Keyword Arguments describe_pet(pet_name="Bud


dy", animal_type="cat")

Return Values return x, y

Recursion factorial(n)

Scope of Variables Local (inside function), Global


(outside function)

159
FILES

Introduction to Files

Files are used to store data permanently on a storage device. In


programming, we use files to read data from and write data to these
storage systems. Python provides built-in functions to work with files
efficiently.

Types of Files

1.​ Text File:


○​ Stores data in plain text format.
○​ Data is readable and uses character encoding like ASCII or
UTF-8.
○​ Example: .txt, .log, .csv.
2.​ Binary File:
○​ Stores data in binary format (0s and 1s).
○​ Not human-readable and is mostly used for non-textual data
like images, audio, and compiled programs.
○​ Example: .bin, .jpg, .exe.
3.​ CSV File (Comma-Separated Values):
○​ A special kind of text file where data is stored in tabular format,
separated by commas.

160
○​ Used for exchanging structured data.
○​ Example: .csv.

Text File Operations

Opening a Text File

To open a file, use Python’s built-in open() function:

file_object = open("file_name", mode)

●​ file_name: The name or path of the file.


●​ mode: Specifies the mode of operation (read, write, append, etc.).

File Open Modes

Mode Description

r Opens a file for reading. (Default


mode)

r+ Opens a file for both reading and


writing.

w Opens a file for writing. Overwrites


if it exists or creates a new one.

161
w+ Opens a file for both writing and
reading.

a Opens a file for appending. Creates


it if it doesn’t exist.

a+ Opens a file for both appending and


reading.

Closing a Text File

Always close a file after use to free resources:

file_object.close()

Using the with Clause

The with statement ensures the file is properly closed after its block of
code is executed:

with open("file_name", "r") as file:

# Perform operations

# File is automatically closed here

162
Writing/Appending to a Text File

Using write()

Writes a single string to the file:

with open("example.txt", "w") as file:

file.write("Hello, World!")

Using writelines()

Writes a list of strings to the file:

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("example.txt", "w") as file:

file.writelines(lines)

Appending Data

with open("example.txt", "a") as file:

file.write("\nAppending another line.")

163
Reading from a Text File

Using read()

Reads the entire content of the file as a single string:

with open("example.txt", "r") as file:

content = file.read()

print(content)

Using readline()

Reads one line at a time:

with open("example.txt", "r") as file:

line = file.readline()

print(line)

Using readlines()

Reads all lines into a list:

164
with open("example.txt", "r") as file:

lines = file.readlines()

print(lines)

Example: Full Workflow

# Writing to a file

with open("example.txt", "w") as file:

file.write("This is the first line.\n")

file.write("This is the second line.\n")

# Appending to the file

with open("example.txt", "a") as file:

file.write("This is an appended line.\n")

# Reading the entire content

165
with open("example.txt", "r") as file:

print("Full content:")

print(file.read())

# Reading line by line

with open("example.txt", "r") as file:

print("\nReading line by line:")

for line in file:

print(line.strip())

# Reading lines into a list

with open("example.txt", "r") as file:

lines = file.readlines()

print("\nLines as a list:")

print(lines)

Output:

166
Full content:

This is the first line.

This is the second line.

This is an appended line.

Reading line by line:

This is the first line.

This is the second line.

This is an appended line.

Lines as a list:

['This is the first line.\n', 'This is the second


line.\n', 'This is an appended line.\n']

r+, w+,and a+ examples

1. r+ (Read and Write)

●​ Opens the file for both reading and writing.

167
●​ The file must exist; otherwise, it raises a FileNotFoundError.
●​ Writing starts at the beginning of the file, overwriting existing content.

# Create a file for the example

with open("example_r+.txt", "w") as file:

file.write("Original content.\n")

# Open in r+ mode

with open("example_r+.txt", "r+") as file:

# Read and display the content

print("Before writing:")

print(file.read())

# Move the cursor to the beginning and write new


data

file.seek(0)

file.write("Updated content.")

168
# Move the cursor to the beginning again to read
updated content

file.seek(0)

print("\nAfter writing:")

print(file.read())

Output:

Before writing:

Original content.

After writing:

Updated content.

2. w+ (Write and Read)

●​ Opens the file for both writing and reading.


●​ If the file exists, it overwrites the content.
●​ If the file does not exist, it creates a new one.

169
# Open in w+ mode

with open("example_w+.txt", "w+") as file:

# Write data to the file

file.write("Writing in w+ mode.\n")

# Move the cursor to the beginning to read what was


written

file.seek(0)

print("File content after writing:")

print(file.read())

Output:

File content after writing:

Writing in w+ mode.

170
3. a+ (Append and Read)

●​ Opens the file for both appending and reading.


●​ If the file exists, it appends new content without overwriting.
●​ If the file does not exist, it creates a new one.

# Create a file for the example

with open("example_a+.txt", "w") as file:

file.write("Initial content.\n")

# Open in a+ mode

with open("example_a+.txt", "a+") as file:

# Append new data to the file

file.write("Appended content.\n")

# Move the cursor to the beginning to read the


updated content

file.seek(0)

print("File content after appending:")

171
print(file.read())

Output:

File content after appending:

Initial content.

Appended content.

Key Differences Between Modes:

Mode File Must Overwrites Allows Allows


Exist? Existing Reading? Writing/App
Content? ending?

r+ Yes No Yes Yes

w+ No Yes Yes Yes

a+ No No (appends Yes Yes


to end) (appends to
end)

172
173
174

You might also like