0% found this document useful (0 votes)
37 views102 pages

I - AI & DS_Python

Uploaded by

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

I - AI & DS_Python

Uploaded by

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

Sri Vidya Mandir Arts and Science College

(Autonomous)
(Accredited by NAAC with ‘A’ Grade[3.27])
(Recognized 2(f) & 12(B) under UGC Act of 1956)
(Affiliated to Periyar University, Salem-11)
Katteri, Uthangarai.

Introduction to Python Programming

I B.Sc. CS (AI & DS)


Introduction to Python Programming

SYLLABUS
Unit I - Algorithmic Problem Solving
Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation
(pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion).
Unit II - Data, Expressions, Statements
Python interpreter and interactive mode, values and types: int, float, boolean, string and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments,
modules and functions, function definition and use, flow of execution, parameters and
arguments.
Unit III - Control Flow, Functions
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else). Iteration: state, while, for, break, continue, pass. Fruitful functions:
return values, parameters, local and global scope, function composition, recursion. Strings: string
slices, immutability, string functions and methods, string module, Lists as arrays.
Unit IV - Lists, Tuples, Dictionaries
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters. Tuples: tuple assignment, tuple as return value, Dictionaries: operations and
methods, advanced list processing - list comprehension.
Unit V - Files, Modules, Packages

Files and exception: text files, reading and writing files, format operator, command line
arguments, errors and exceptions, handling exceptions, modules, packages.

Text Book(s)
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‟‟, 2nd
edition, Updated for Python 3, Shroff/O‟Reilly Publishers, 2016.
2. Guido van Rossum and Fred L. Drake Jr, “An Introduction to Python – Revised and
updated for Python 3.2, Network Theory Ltd., 2011.
Reference Book(s)
1. John V Guttag, “Introduction to Computation and Programming Using Python‟‟, Revised
and expanded Edition, MIT Press, 2013
Introduction to Python Programming

2. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in


Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd.,
2016.
3. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,,
2015.
4. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning,
2012.
5. Charles Dierbach, “Introduction to Computer Science using Python: A Computational
Problem- Solving Focus, Wiley India Edition, 2013.
6. Paul Gries, Jennifer Campbell and Jason Montojo, “Practical Programming: An
Introduction to Computer Science using Python 3”, Second edition, Pragmatic
Programmers, LLC, 2013.
Introduction to Python Programming

Unit – I

Algorithms

➢ Algorithms are step-by-step sets of instructions or rules to perform a specific task


or solve a particular problem.
➢ Algorithms provide a systematic approach to problem-solving and are used to
automate processes, make decisions, or analyze data.
Some key points about algorithms
Purpose
➢ Algorithms are designed to achieve a specific objective or solve a particular problem.
➢ They can be used in a wide range of applications, from sorting a list of numbers to
searching for information on the internet.
Efficiency
➢ Efficiency is an important aspect of algorithms.
➢ An algorithm is considered efficient if it performs
❖ The task in a reasonable amount of time and
❖ Uses a reasonable amount of resources, such as memory or processing power.
Analysis
➢ The performance of algorithms is analyzed in terms of time complexity and space
complexity.
➢ Time complexity refers to the amount of time an algorithm takes to complete
➢ Space complexity refers to the amount of memory or space it requires.
Common Algorithms
Sorting Algorithms
➢ Arrange elements in a specific order (e.g., alphabetical or numerical).
Examples
Bubble Sort, Quick Sort, Merge Sort.
Searching Algorithms
➢ Find the location of a specific item in a collection of items.
Examples
Linear Search, Binary Search.
Graph Algorithms
➢ Analyze relationships between entities in a graph.
Introduction to Python Programming

Examples
Depth-First Search (DFS), Breadth-First Search (BFS).
Dynamic Programming
➢ Solve complex problems by breaking them down into simpler, overlapping
subproblems.
Example
Fibonacci sequence calculation.
Greedy Algorithms
➢ Make locally optimal choices at each stage with the hope of finding a global optimum.
Example
Dijkstra's algorithm for finding the shortest path in a graph.
Algorithmic Paradigms
Divide and Conquer
➢ Break a problem into subproblems, solve them independently, and combine their
solutions.
Dynamic Programming
➢ Solve a problem by solving its subproblems and storing their solutions.
Greedy Algorithms
➢ Make a series of locally optimal choices to reach a global optimum.
Pseudocode and Flowcharts
➢ Algorithms are often expressed using pseudocode (a high-level, informal description
of a computer program) or flowcharts (visual representations of a process with
different symbols representing different steps).
Data Structures
➢ Algorithms often work in conjunction with data structures, which are organized ways
to store and manipulate data.
➢ Common data structures include arrays, linked lists, stacks, and queues.

Building blocks of algorithms (statements, state, control flow, functions)


The building blocks of algorithms are fundamental components used to design and
implement algorithms.
The building blocks can be combined and structured to create algorithms.
Algorithms are step-by-step procedures or formulas for solving problems and
performing tasks.
Introduction to Python Programming

Building blocks allows for the creation of organized, efficient, and maintainable code.
These building blocks include:
Statements
➢ Statements are individual instructions or commands that perform a specific action.
Examples
Assignment statements, input/output statements, conditional statements, loop
statements.
State
➢ State refers to the current condition or values of variables in a program.
Examples
Variables, data structures (arrays, lists, etc.), memory.
Control Flow
➢ Control flow refers to the order in which statements are executed in a program.
Examples:
Conditional Statements: if, else, switch.
Loop Statements
for, while, do-while.
Control Flow Statements
break, continue, return.
Functions
➢ Functions are reusable blocks of code that perform a specific task.
➢ They help in organizing and modularizing code.

Function Components
Function Signature
Includes the function name, parameters, and return type.
Function Body
Contains the actual code that gets executed when the function is called.
Parameters
Input values passed to a function.
Return Type
The type of value the function returns.
Introduction to Python Programming

Example
def add(a, b):

return a + b

Notation (pseudo code, flow chart, programming language)


Notation is a symbolic representation used to describe algorithms and processes.
Three common notations used are:
❖ Pseudo Code
❖ Flowchart
❖ Programming Language
Pseudo Code
➢ Pseudo code is a high-level description of an algorithm
➢ It uses a mixture of natural language and simple code-like statements.
Advantages
• It is language-agnostic.
• Easy to understand without being tied to a specific programming language
syntax.
Example
Initialize sum to 0
For each element in the list
Add the element to sum
Output sum
Flowchart

➢ A flowchart is a graphical representation of a process or algorithm.

➢ It uses different shapes to represent different types of steps, decisions, or actions.

Shapes
Oval: Start/End
Rectangle: Process or action
Diamond: Decision or branching point
Arrow: Flow direction
Introduction to Python Programming

Example

Programming Language
➢ Writing an algorithm using the syntax and structure of a specific programming
language.
Advantages
➢ Provides a direct translation of the algorithm into executable code.
Example
def calculate_sum(lst):
sum = 0
for element in lst:
sum += element
return sum
Pseudo code and flowcharts are used during the initial design phase before
implementation.

Programming language notation is used for actual coding and implementation of


algorithms in a specific language.
Introduction to Python Programming

Algorithmic problem solving


➢ It is the process of designing and implementing a step-by-step procedure or set of
rules to solve a specific computational problem.
➢ It involves breaking down a complex problem into smaller, more manageable
subproblems and then developing systematic and efficient solutions for each
subproblem.

Concepts involved in algorithmic problem solving are:

Understanding the Problem


➢ Clearly define the problem and its requirements.
➢ Identify the input and output specifications.
➢ Consider any constraints or limitations on the problem.

Breaking down the Problem


➢ Decompose the problem into smaller, more manageable subproblems.
➢ Identify patterns, repetitions, or similarities within the problem.

Developing an Algorithm
➢ Create a step-by-step plan or set of instructions to solve each subproblem.
➢ Use pseudocode, flowcharts, or a programming language to express the algorithm.

Algorithm Analysis
➢ Analyze the time and space complexity of the algorithm.
➢ Consider efficiency, scalability, and resource requirements.

Iterative Refinement
➢ Test the algorithm with sample inputs to identify and fix potential issues.
➢ Refine the algorithm based on testing and analysis.

Optimization
➢ Explore opportunities to improve the efficiency of the algorithm.
➢ Consider alternative approaches and optimizations.

Implementation
➢ Translate the algorithm into a specific programming language.
➢ Write clean, readable, and maintainable code.
Introduction to Python Programming

Testing and Debugging


➢ Test the implementation with various inputs, including edge cases.
➢ Debug and fix any issues that arise during testing.

Documentation
➢ Provide clear documentation for the algorithm, including its purpose, inputs, outputs,
and usage instructions.

Maintenance
➢ Regularly review and update the algorithm to adapt to changing requirements.
➢ Address any issues that arise over time.

Algorithmic problem solving is a crucial skill in computer science and programming.


It involves creativity, logical reasoning, and the ability to break down complex problems
into manageable components.

Simple strategies for developing algorithms (iteration, recursion)

➢ Developing algorithms involves various strategies to design step-by-step procedures


for solving problems.
➢ Here are two fundamental strategies commonly used:
❖ Iteration
❖ Recursion

Iteration
Iteration involves repeating a set of instructions or steps multiple times until a certain
condition is met.

Key Concepts
Loop Structures
Use loops (e.g., for loop, while loop) to repeat a block of code.
Initialization and Update
Initialize variables before the loop and update them within the loop.
Termination Condition
Define a condition that, when met, exits the loop.
Introduction to Python Programming

Example
def sum_of_numbers(n):
result = 0
for i in range(1, n + 1):
result += i
return result
Recursion
Recursion involves solving a problem by breaking it down into smaller instances of
the same problem.
A function calls itself to solve subproblems.
Key Concepts
Base Case
Define a condition that stops the recursive calls.
Recursive Call
Call the function within itself to solve a smaller instance of the problem.
Example
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Iteration is suitable for tasks that involve repetition, such as traversing elements in a
list.
Recursion is useful when a problem can be divided into smaller subproblems.
When developing algorithms, it's essential to consider factors such as efficiency,
readability, and maintainability.
Introduction to Python Programming

Unit - II

Python interpreter and interactive mode

➢ The interpreter is a program that reads and executes Python code.


➢ It allows to run Python scripts or interact with the Python programming language in
an interactive mode.
➢ Two ways to interact with the Python interpreter:
❖ Script mode
❖ Interactive mode
Script Mode
➢ In script mode, you write your Python code in a script file (usually with a .py
extension).
➢ Then execute the script by running it through the Python interpreter.
Example

If you have a script called myscript.py, you can run it from the command line with:

python myscript.py

Interactive Mode

➢ In interactive mode, you can enter Python commands one at a time, and the interpreter
executes them immediately.
➢ You can start interactive mode by typing python in the command line without
specifying a script file.
➢ Once in interactive mode, you'll see the Python prompt (>>>), you can type Python
code directly and see the results immediately.

Example

$ python

Python 3.9.6 (default, Jul 16 2021, 00:00:00)

[GCC 4.2.1 Compatible Apple LLVM 12.0.0 (clang-1200.0.32.29)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>>

Now you can enter Python commands directly at the >>> prompt:
Introduction to Python Programming

>>> print("Hello, World!")


Hello, World!
➢ Interactive mode is useful for quickly testing code snippets, experimenting with
features, or learning Python interactively.
➢ To exit the Python interpreter, you can type exit( ) or Ctrl+D (on Unix-based systems)
or Ctrl+Z (on Windows) and press Enter.
➢ Python provides both script mode for running scripts and interactive mode for
executing commands interactively.
➢ It a versatile language for different types of development and exploration.

Values and types: int, float, boolean, string and list

➢ A value is one of the basic things a program works with, like a letter or a number.
Example
2, 42.0, and 'Hello, World!'.
➢ These values belong to different types: 2 is an integer, 42.0 is a floating-point
number, and 'Hello, World!' is a string.
➢ If you are not sure what type a value has, the interpreter can tell you.
Example
>>> type(2)
<class 'int'>
➢ Common data types in Python:
Integers (int)
➢ Integers are whole numbers without a decimal point.
Example
42, -10, 0
Floating-Point Numbers (float)
➢ Floating-point numbers represent real numbers and can have decimal points.
Example
3.14, -0.5, 2.0
Boolean (bool)
➢ Booleans represent truth values, either True or False.
Example
True, False
Introduction to Python Programming

String (str)
➢ Strings are sequences of characters, enclosed in single (') or double (") quotes.
Example
'hello', "Python", '123'
List
➢ A list is a mutable, ordered collection of values.
➢ It can contain elements of different types.
Example
[1, 2, 3], ['apple', 'orange', 'banana'], [1, 'two', 3.0]
Example
# Integer
integer_value = 42

# Float
float_value = 3.14

# Boolean
boolean_value = True

# String
string_value = 'Hello, World!'

# List
list_value = [1, 2, 3, 'four', 5.0]

# Printing the values and their types


print("Integer:", integer_value, type(integer_value))
print("Float:", float_value, type(float_value))
print("Boolean:", boolean_value, type(boolean_value))
print("String:", string_value, type(string_value))
print("List:", list_value, type(list_value))
Output
Integer: 42 <class 'int'>
Float: 3.14 <class 'float'>
Introduction to Python Programming

Boolean: True <class 'bool'>


String: Hello, World! <class 'str'>
List: [1, 2, 3, 'four', 5.0] <class 'list'>
Variables

➢ A variable is a named storage location used to store data (a value or


an object).
➢ Variables allow to manipulate and work with data in the program by
referring to it with a name.
➢ In Python, you can create variables and assign values to them using
the assignment operator (=).
➢ Variable is a sequence of characters that consists of letters, digits and
underscore
➢ Can be of any length
➢ Starts with a letter which can be either lower or upper case
➢ Can start with an underscore ‘_’
➢ Cannot start with a digit
➢ Cannot be a keyword.

Example
Valid variables Invalid variables
Name First Name
Roll_NO 12Name
A1 for
_Address Salary@
➢ If we type the invalid identifiers, it will show an error as invalid syntax.
Example
>>> First Name
SyntaxError: invalid syntax
>>> 12Name
SyntaxError: invalid syntax
>>> for
SyntaxError: invalid syntax

Variable Assignment
To assign a value to a variable, use the = operator.
Introduction to Python Programming

Examples of variable assignment


x=5 # Assigning an integer
y = 3.14 # Assigning a float
name = 'Elayaraj' # Assigning a string
is_valid = True # Assigning a Boolean
Variable Usage
You can use variables in expressions and operations.
result = x + y
greeting = 'Hello, ' + name
Reassignment
You can change the value of a variable by reassigning it.
x = 10
Multiple Assignments
You can assign multiple variables in a single line.
a, b, c = 1, 2, 3
Expressions

➢ An expression is a combination of values, variables, and operators.


➢ Expressions are the building blocks of code.
➢ It is used to represent computations or operations.

Some key components of expressions:


Values
These can be literals (like 42, 3.14, or 'hello') or variables that hold values.
Example
x=5 # Variable assignment
value = x + 3 # Expression using a variable
Operators
➢ These are symbols that represent computations. Examples include arithmetic
operators (+, -, *, /), comparison operators (==, !=, <, >), and logical operators (and,
or, not).
Example
result = x + 3 # Addition operator
is_equal = x == 5 # Comparison operator
Function Calls
➢ Functions are reusable pieces of code that perform specific tasks.
Introduction to Python Programming

➢ When a function is called, it returns a value that can be part of an expression.

Example
length = len("hello") # Function call in an expression
Parentheses
➢ These are used to group expressions and control the order of evaluation.

Example
result = (x + 3) * 2 # Using parentheses to control evaluation order
Examples of expressions
# Arithmetic expression
result = 2 * (3 + 4) / 5
# Comparison expression
is_greater = x > 0
# Logical expression
is_valid = (x > 0) and (y < 10)
# Function call in an expression
length = len("hello")
Statements

➢ A statement is a complete line of code that performs a specific action.


➢ Statements in Python can include variable assignments, function calls, control flow
structures, and more.
Some common types of statements in Python
Assignment Statement
Assigns a value to a variable using the = operator.
Example
x=5 # Assigning the value 5 to the variable x
Print Statement
The print statement is used to display output.
Example
print("Hello, World!")
Expression Statement
An expression can stand alone as a statement.
Introduction to Python Programming

Example
result = 2 * (3 + 4) # Expression statement
Conditional Statements (if, elif, else)
Used for conditional execution of code based on the evaluation of an expression.
Example
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
Loop Statements (for, while)
Used for repetitive execution of code.
Example
for i in range(5):
print(i)

while x > 0:
print(x)
x -=1
Import Statement
Used to import modules or specific functions/classes from modules.
Example
import math
from random import randint
Tuple assignment

➢ Tuple assignment allows to assign multiple variables simultaneously using a tuple.


➢ The number of variables on the left side of the assignment must match the length of
the tuple on the right side.
Example
# Tuple assignment
point = (3, 4)
x, y = point
Introduction to Python Programming

print("x:", x)
print("y:", y)
In this example, the values (3, 4) are assigned to the variables x and y using tuple
assignment. After the assignment, x is 3, and y is 4.

You can also use tuple assignment to swap the values of two variables without
needing a temporary variable.

Example
a=5
b = 10

# Swap values using tuple assignment


a, b = b, a

print("a:", a)
print("b:", b)
After this code, the value of a becomes 10, and the value of b becomes 5.
Tuple assignment can be used with a list
Example
# List assignment
values = [1, 2, 3]
a, b, c = values
print("a:", a)
print("b:", b)
print("c:", c)
This assigns the values [1, 2, 3] to variables a, b, and c.
The number of variables on the left side must match the length of the iterable on the
right side, or you'll get a ValueError.
Introduction to Python Programming

Precedence of operators

Operator precedence determines the order in which the Python


interpreter evaluates the operators in an expression.
Example
4+5*3
The order of precedence determines that multiplication is computed
first so the result is 19.
The operator having higher priority is evaluated first.
Operator Precedence
Precedence Operator Name
** Exponential
+,-,~ Plus, Minus, Bitwise not
*,/,//,% Multiplication, division, integer
division, and remainder
+, - Binary Addition, Subtraction
<< , >> Left and Right Shift
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
<,<=,>,>= Comparison
==, != Equality
=,%=,/=,//=,-=,+=,,*=,**= Assignment Operators
is, is not Identity Operators
in, not in Membership Operator
Not Boolean Not
And Boolean and
Or Boolean or

The operators on the top rows have higher precedence and the
operators on the bottom rows have lower precedence.

Example
4+5*3-10
Introduction to Python Programming

As compared to + and * operators, the * operator has higher priority.


Hence, the multiplication operation is performed first.
Therefore, above expression becomes,
4+15-10
Now in above expression, + and – have the same priority.
In such a situation, the leftmost operation is evaluated first.
Hence, the above expression becomes
19 - 10
Subtraction is performed last and the final answer will be 9.

Comments

➢ Comments can be used to explain Python code.


➢ Comments can be used to make the code more readable.
➢ Hash symbol (#) is used for single line comment in python.
Example
#This is a comment
print("Hello, World!")
Output

Hello, World!

➢ Three consecutive single quotation marks ’’’ are used for multiple
comments and called paragraph comment.
Example
#Learn How to Comment in Python
print(‘I Learnt How to Comment in Python’)
’’’ Amazing tool
in Python called Comment’’’
print(‘Bye’)

Output
I Learnt How to Comment in Python
Bye

➢ Python interpreter ignores all the text after # on the same line.
Introduction to Python Programming

➢ Similarly, when it sees the triple quotation marks ’’’ it scans for the
next ’’’ and ignores any text in between the triple quotation marks.

Modules and functions

Modules
➢ A module is a file containing Python definitions and statements.

➢ The file name is the module name with the suffix .py.

➢ Modules allow to organize code logically and break it into reusable components.

Example
# module_example.py

def greet(name):
print("Hello, " + name + "!")

def square(x):
return x ** 2
➢ In another Python script, you can use the module like this:
Example
# main_script.py
import module_example

module_example.greet("Alice")
result = module_example.square(5)
print(result)
➢ In this example, module_example is a module that contains a greet function and a
square function.
➢ The import statement is used to bring in the module, and then you can call functions
using the module name.
Functions

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

➢ Functions provide modularity and help in code reuse.


Introduction to Python Programming

Example
# Function definition
def add_numbers(x, y):
return x + y

# Function call
result = add_numbers(3, 7)
print(result)
➢ In this example, add_numbers is a function that takes two parameters (x and y) and
returns their sum. The function is then called with arguments 3 and 7, and the result is
printed.
➢ Functions can have parameters and return values.
➢ They help in making the code more readable and maintainable.
➢ Combining modules and functions allows you to create organized and reusable code.
➢ You can have multiple functions within a module, and then use that module in other
parts of your program or even in different programs.
➢ This promotes a modular and structured approach to software development.

Function definition and use

Function Definition
➢ You define a function using the def keyword, followed by the function name,
parameters in parentheses, a colon, and the function body.
Syntax
def function_name(parameter1, parameter2, ...):
# Function body
# Code to perform a specific task
return result # Optional: Return a value
Example
# Function that adds two numbers:
def add_numbers(x, y):
result = x + y
return result
Introduction to Python Programming

Function Use (Function Call)


➢ Once you've defined a function, you can use (or call) it by providing the required
arguments.
Syntax
result = function_name(argument1, argument2, ...)

Using the add_numbers function:


sum_result = add_numbers(3, 7)
print(sum_result) # Output: 10
➢ In this example, the add_numbers function is called with arguments 3 and 7, and the
result is stored in the variable sum_result. The function returns the sum of the two
numbers.
Default Arguments
➢ You can provide default values for function parameters. These values are used if the
caller does not provide a value for that parameter.
Example
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")

greet("Elayaraj") # Output: Hello, Elayaraj!


greet("Dhanush", "Good morning") # Output: Good morning, Dhanush!
In the greet function, the parameter greeting has a default value of "Hello". If the
caller provides a value for greeting, it will use that value; otherwise, it uses the default value.
Return Statement
➢ Functions can return a value using the return statement.
➢ If there is no return statement, the function returns None by default.
Example
def multiply(x, y):
result = x * y
return result

product = multiply(4, 5)
print(product) # Output: 20
In this example, the multiply function returns the product of the two numbers.
Introduction to Python Programming

Flow of execution

➢ The flow of execution refers to the order in which statements are executed.
➢ When you run a Python script or program, the interpreter goes through the code
sequentially, executing one statement after another.
Some key concepts related to the flow of execution:
Sequential Execution
➢ By default, statements in a Python script are executed in the order.
➢ The interpreter starts at the top of the script and goes through each line, executing
statements one after the other.
Example
# Sequential execution
print("Statement 1")
print("Statement 2")
print("Statement 3")
Control Flow Statements
➢ Control flow statements, such as conditionals (if, elif, else) and loops (for, while),
alter the normal flow of execution.
➢ Conditional statements allow the program to make decisions based on conditions.
Example
# Conditional statement
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
➢ Loop statements allow the program to repeat a block of code multiple times.
Example
# Loop statement
for i in range(3):
print("Iteration", i)
Function Calls
➢ When a function is called, the flow of execution moves to the function's code.
Introduction to Python Programming

➢ Once the function completes its task, the control returns to the point where the
function was called.
Example
# Function call
def greet(name):
print("Hello, " + name + "!")

greet("Elayaraj")
Exception Handling
➢ Exception handling statements (try, except, finally) allow to handle errors and control
the flow of execution when an exception occurs.
Example
# Exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
Parameters and arguments

➢ In functions and methods, parameters and arguments play crucial roles. They are used
to describe the variables and values passed between different parts of a program.
Parameter
➢ A parameter is a variable in a method or function definition.
➢ It is a placeholder for the actual value (argument) that will be provided when the
function is called.
➢ Parameters define the input for a function or method.
Example
def greet(name):
print("Hello, " + name + "!")
In this example, name is a parameter of the greet function.
Argument
➢ An argument is the actual value that is passed to a function or method when it is
called.
Introduction to Python Programming

➢ Arguments are the real values that are substituted for the parameters defined in the
function or method.
Example
greet("Elayaraj")
In this case, "Elayaraj" is an argument passed to the greet function, and it will be
assigned to the name parameter.
➢ Parameters are the variables defined in a function or method.
➢ Arguments are the values that are passed to those parameters when the function or
method is invoked.
Introduction to Python Programming

Unit - III
Conditionals

Boolean values and operators

➢ Boolean values represent either true or false.


➢ Boolean operators are used to manipulate these values.
Boolean Values
True: Represents a true or affirmative condition.
False: Represents a false or negative condition.
Boolean Operators
AND (&&): Returns true only if both operands are true.
OR (||): Returns true if at least one of the operands is true.
NOT (!): Returns the opposite of the operand; if the operand is true, NOT returns
false, and vice versa.
Example
# Boolean values
x = True
y = False
# Boolean operators
result_and = x and y # False (True only if both x and y are True)
result_or = x or y # True (True if at least one of x or y is True)
result_not = not x # False (Opposite of x, which is True)
# Example in a conditional statement
if x and not y:
print("Both conditions are satisfied.")
else:
print("At least one condition is not satisfied.")
Truth Tables
Truth tables illustrate the outcomes of Boolean operators for all possible combinations
of input values.
Introduction to Python Programming

Boolean values and operators are commonly used in programming for decision-
making, conditional statements, and loops.
Example
age = 25
is_adult = age >= 18 # Evaluates to True or False
if is_adult:
print("You are an adult.")
else:
print("You are not an adult yet.")

Conditional (if), alternative (if-else), chained conditional (if-elif-else)

Python supports various decision-making statements. These are:


1. if statements
2. if-else statements
3. Nested if statements
4. Multi-way if-elif-else statements

if statements

The if statement executes a statement if a condition is true.

Syntax

➢ The condition is a Boolean expression.


➢ A colon (:) must always be followed by the condition.
Introduction to Python Programming

➢ The statement(s) must be indented at least one space right of the if


statement.
➢ The statements are executed only if the condition within the if
statement is true.

Flow Chart

Example
num1=eval(input(“Enter First Number: “))
num2=eval(input(“Enter Second Number: “))
if num1-num2==0:
print(“Both the numbers entered are Equal”)

Output
Enter First Number: 12
Enter Second Number: 12
Both the numbers entered are Equal
if – else statements
➢ The if-else statement consists of a true as well a false condition.
➢ It has two blocks.
➢ One block is for if and it is executed when the condition is true.
➢ The other block is for else. The else block is executed when the
condition is false.
➢ A colon (:) must be followed by the condition.
Introduction to Python Programming

➢ The else keyword must line up with the if statement.


➢ The keyword else should also be followed by a colon (:)
Syntax

Flow Chart

Example
num1=int(input(“Enter the First Number:”))
num2=int(input(“Enter the Second Number:”))
if num1>num2:
print(num1,”is greater than “,num2)
else:
print(num2,”is greater than “,num1)
Output
Enter the First Number:100
Enter the Second Number:43
100 is greater than 43
Introduction to Python Programming

nested if statements
One if statement inside another if statement then it is called a nested
if statement.
Syntax
if Boolean-expression1:
if Boolean-expression2:
statement1
else:
statement2
else:
statement3

If the expression1 and expression2 are correct then statement1 will


execute.
If the expression1 is correct and expression2 is incorrect then
statement2 will execute.
If both expression1 and Boolean-expression2 are incorrect then
statement3 will execute.
Example

num1=int(input(“Enter the number:”))


num2=int(input(“Enter the number:”))
num3=int(input(“Enter the number:”))
if num1>num2:
if num2>num3:
print(num1,”is greater than “,num2,”and “,num3)
else:
print(num1,” is less than “,num2,”and”,num3)
print(“End of Nested if”)

Output

Enter the number:12


Enter the number:34
Enter the number:56
12 is less than 34 and 56
End of Nested if
Introduction to Python Programming

Multi-way if-elif–else statements


➢ In this kind of statements, the conditions are checked from top to
bottom.
➢ When a true condition is found, the statement associated with it is
executed and the rest of the statements are skipped.
➢ If none of the conditions are found true then the last else statement is
executed.
Syntax
If Boolean-expression1:
statement1
elif Boolean-expression2 :
statement2
elif Boolean-expression3 :
statement3
--------------
- - - - - - - - - - - -- -
elif Boolean-expression n :
statement N
else :
Statement(s)
Example
Subject1=float(input(“Enter the Marks of Data-Structure:”))
Subject2=float(input(“Enter the Marks of Python:”))
Subject3=float(input(“Enter the Marks of Java:”))
Subject4=float(input(“Enter the Marks of C Programming:”))
Subject5=float(input(“Enter the Marks of HTML:”))
sum=Subject1+Subject1+Subject3+Subject4+Subject5
per=sum/5
print(“Total Marks Obtained”, sum, “Out of 500”)
print(“Percentage = “,per)
if per>=90:
print(“Distinction”)
else:
Introduction to Python Programming

if per>=80:
print(“ First Class”)
else:
if per>=70:
print(“Second Class”)
else:
if per>=60:
print(“Pass”)
else:
print(“Fail”)
Output
Enter the Marks of Data-Structure: 60
Enter the Marks of Python: 70
Enter the Marks of Java: 80
Enter the Marks of C Programming: 90
Enter the Marks of HTML: 95
Total Marks Obtained 385.0 out of 500
Percentage = 77.0
Second Class

Iteration: state, while, for, break, continue, pass

State

➢ "State" refers to the current progress or condition of the iteration.


➢ Iteration involves repeatedly executing a set of statements or a block of code.
➢ The state of the iteration refers to where the loop currently is, what values are being
processed, and how many iterations have occurred.
Example
# Iterating over a list of numbers
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print("Current number:", num)
Introduction to Python Programming

Output
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5
In this example, the state of the iteration changes with each loop iteration.
The variable num takes value of each element in the numbers list during each iteration.
The state is represented by the value of num for the current iteration.
To track the iteration index, you can use the enumerate function.
Example
# Iterating over a list of numbers with index
numbers = [1, 2, 3, 4, 5]
for index, num in enumerate(numbers):
print("Index:", index, "Current number:", num)
Output
Index: 0 Current number: 1
Index: 1 Current number: 2
Index: 2 Current number: 3
Index: 3 Current number: 4
Index: 4 Current number: 5
In this case, the index variable represents the state of the iteration.

Loop Control Statements

➢ Loops are used to repeat the same code multiple times.


➢ Two types of loop statements:
• while loop
• for loops

While loop

➢ The while loop is a condition controlled loop. It is controlled by true


or false conditions.
➢ It executes a sequence of statements repeatedly until the condition
remains true.
Introduction to Python Programming

Syntax

while test-condition:
#Loop Body
statement(s)

Rules
➢ Begins with the while statement.
➢ The test condition is a Boolean expression.
➢ The while condition is terminated with a colon (:).
➢ The statement(s) within the while loop will be executed till the
condition is true.
➢ If the condition is true then the body of the loop is executed.
➢ When the condition is false, the execution will be completed and the
control goes out of the loop.

Flow Chart

Example
count=0 #initialize the counter
while count<=5: # Test condition
print(“Count = “,count) # print the value of count
count=count+1 # Increment the value of count by 1
Output
Count = 0
Count = 1
Count = 2
Count = 3
Introduction to Python Programming

Count = 4
Count = 5
Program to add 10 consecutive numbers starting from 1 using the
while loop
Program
count=0 #initialize the counter
sum=0 #initialize sum to zero
while count<=10: #test condition if true
sum= sum +count #add sum + count
count=count+1 #increase the value of count by 1
print(“Sum of First 10 Numbers = “,sum) #print sum
Output
Sum of First 10 Numbers = 55

for loop

➢ The for loop is a count controlled loop which repeats for a specific
number of times.
➢ The for loop iterates through a sequence of objects, i.e. it iterates
through each value in a sequence.

Syntax
for var in sequence:
statement(s)
………………………………
………………………………
………………………………
Example
for var in range(m,n):
print var

Example 1
program to print numbers from 1 to 5 using for loop
for i in range(1,6):
print(i)
print(“End of The Program”)
Introduction to Python Programming

Output
1
2
3
4
5
End of The Program
Example 2
program to Display capital letters from A to Z.
print(“ The Capital Letters A to Z are as follows:”)
for i in range(65,91,1):
print(chr(i),end=” “)
Output
The Capital Letters A to Z are as follows:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Nested Loops
The for and while loop statements can be nested as like the if
statements.
Loops within the loops or when one loop is inserted within another
loop, then it is called nested loop.
Example
for i in range(1,4,1):
for j in range(1,4,1):
print("i =",i,"j =",j,"i + j =",i + j)
print(“End of Program”)
Output
i=1j=1i+j=2
i=1j=2i+j=3
i=1j=3i+j=4
i=2j=1i+j=3
i=2j=2i+j=4
i=2j=3i+j=5
i=3j=1i+j=4
i=3j=2i+j=5
i=3j=3i+j=6
Introduction to Python Programming

End of Program

range( ) Function
➢ range( ) function is an inbuilt function in Python.
➢ It is used to generate a list of integers.
➢ The range function has one, two or three parameters.
➢ The last two parameters in range( ) are optional.
Syntax
range(begin, end, step)

➢ The ‘begin’ is the first beginning number. i.e. Starting of the sequence.
➢ The ‘end’ is the limit, i.e. the last number in the sequence.
➢ The ‘step’ is the difference between each number in the sequence.
Example 1
Create a list of integers from 1 to 5.
>>> list(range(1,6))
[1,2,3,4,5]
➢ range(1,6) function generates a list of integers starting from 1 to 5.
Example 2
Create a list of integers from 1 to 20 with a difference of 2 between two
successive integers.
>>> list(range(1,20,2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
➢ range(1,20,2) function generates a list of integers starting from 1with
a difference of two between two integers up to 20.
Examples of range( ) function
Example of Output
Range Function
range(5) [0, 1, 2, 3, 4]
range(1,5) [1, 2, 3, 4]
range(1,10,2) [1, 3, 5, 7, 9]
range(5,0,-1) [5, 4, 3, 2, 1]
range(5,0,-2) [5, 3, 1]
range (-4,4) [-4, -3, -2, -1, 0, 1, 2, 3]
range (-4,4,2) [-4, -2, 0, 2]
Introduction to Python Programming

range(0,1) [0]
range(1,1) Empty
range(0) Empty

Break statement
The break statement is used to exit a loop prematurely, before the loop condition is met.
Working of break in while loop
Syntax

Example using while loop


# Using break in a while loop
count = 0
while count < 5:
print("Current count:", count)
Introduction to Python Programming

count += 1
if count == 3:
print("Breaking out of the loop.")
break
In this example, the loop will iterate as long as count is less than 5.
However, when count becomes 3, the break statement is encountered, and the loop is
immediately exited.
Output
Current count: 0
Current count: 1
Current count: 2
Breaking out of the loop.
Working of break in for loop
Syntax

The break statement can be used with a for loop


Example
# Using break in a for loop
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print("Current number:", num)
if num == 3:
print("Breaking out of the loop.")
break
In this case, the loop will terminate when num becomes 3, and the output will be:
Introduction to Python Programming

Output
Current number: 1
Current number: 2
Current number: 3
Breaking out of the loop.
Continue statement
Continue statement is used to skip the rest of the code inside a loop for the current
iteration and move on to the next iteration.
It is often used in conditional statements to control the flow of a loop.

Syntax

Example
# Using continue in a for loop
numbers = [1, 2, 3, 4, 5]
for num in numbers:
Introduction to Python Programming

if num == 3:
print("Skipping number 3.")
continue
print("Current number:", num)
In this example, when the loop encounters num equal to 3, the continue statement is
executed, and the remaining code inside the loop for that iteration is skipped. The output will
be:
Current number: 1
Current number: 2
Skipping number 3.
Current number: 4
Current number: 5
Similarly, you can use continue with a while loop.
Syntax

Example
# Using continue in a while loop
count = 0
while count < 5:
count += 1
if count == 3:
print("Skipping count 3.")
continue
print("Current count:", count)
In this case, when count becomes 3, the continue statement is encountered, and the
code after it for that iteration is skipped. The output will be:
Current count: 1
Current count: 2
Introduction to Python Programming

Skipping count 3.
Current count: 4
Current count: 5
Pass statement
The Python pass statement is a null statement.
The pass statement is a "do nothing" statement.
The difference between pass and comment is that comment is ignored by the
interpreter whereas pass is not ignored.
Syntax
Pass
When the user does not know what code to write, users can simply place a pass where
empty code is not allowed, like in loops, function definitions, class definitions, or in if
statements.
If we do not use pass or simply enter a comment or a blank here, we will receive an
Indentation Error message.
Example
n = 26
if n > 26:
# write code you’re here
print('welcome')
Output
Indentation Error: expected an indented block after 'if' statement
Use of pass keyword in Function
Python Pass keyword can be used in empty functions
Example
def function:
pass
Example
def example_function( ):
# This function does nothing, but it's syntactically correct.
pass
# Placeholder block that does nothing
if True:
pass
Introduction to Python Programming

else:
pass

# Loop that does nothing


for i in range(5):
pass

# Class definition with no methods or attributes


class ExampleClass:
pass
Return values

The return statement indicates the value that the function should return when it is
called.
It allows a function to send a result back to the caller.
Example
def add_numbers(a, b):
result = a + b
return result
# Calling the function and storing the result

sum_result = add_numbers(3, 4)

# Printing the result

print("Sum:", sum_result)

In this example, the add_numbers function takes two parameters (a and b), and
calculates their sum

Then uses the return statement to send the result back to the caller.

When the function is called with add_numbers(3, 4), it returns the value 7, which is
then assigned to the variable sum_result.

A function can have multiple return statements, but as soon as any one of them is
executed, the function exits.
If no return statement is encountered, the function returns None by default.
Introduction to Python Programming

Example
def example_function(x):
if x > 0:
return "Positive"
elif x < 0:
return "Negative"
else:
return "Zero"
result = example_function(5)
print(result)
Output
Positive
In this example, the example_function returns different strings based on the value of
the parameter x.
Parameters

Function parameters is also known as arguments.


Parameters are values passed to the function when called
Parameters can be used within the function to perform certain operations.
Function parameters are specified in the function definition.
Example
def greet(name):
"""This function takes a name as a parameter and prints a greeting."""
print("Hello, " + name + "!")
# Calling the function with an argument
greet("Elayaraj")
In this example, the greet function takes one parameter, name.
When we call the function with greet("Elayaraj"), the value " Elayaraj " is passed as
an argument to the function, and the function prints the greeting
"Hello, Elayaraj!"

Functions can have multiple parameters:


def add_numbers(a, b):
"""This function takes two numbers as parameters and returns their sum."""
Introduction to Python Programming

result = a + b
return result
# Calling the function with two arguments
sum_result = add_numbers(3, 4)
print("Sum:", sum_result)
Output:
Sum: 7
Here, the add_numbers function takes two parameters, a and b, and returns their sum.
When the function is called with add_numbers(3, 4), it returns 7, and the result is
printed.
You can also define default values for parameters, making them optional:
Example
def power(base, exponent=2):
"""This function raises the base to the specified exponent (default is 2)."""
result = base ** exponent
return result
# Calling the function with one argument (uses default exponent value)
result1 = power(3)
print("Result 1:", result1)
Output
Result 1: 9

# Calling the function with two arguments


result2 = power(3, 3)
print("Result 2:", result2)
Output
Result 2: 27
In this example, the power function has a default value of 2 for the exponent
parameter.
If you don't provide a value for exponent, it will use the default value.
Local and global scope
Variables can have either local or global scope.
The scope of a variable determines where that variable can be accessed or modified.
Introduction to Python Programming

Local Scope
Variables defined inside a function have local scope.
They are only accessible within that function.
Local variables are created when the function is called and destroyed when the
function exits.
Example
def example_function( ):
local_variable = 10
print("Inside the function:", local_variable)
example_function( )
# Uncommenting the next line would result in an error
# print("Outside the function:", local_variable)
The local_variable is accessible only within the example_function.
If you try to print it outside the function, as shown in the commented line, it will
result in an error.
Global Scope
Variables defined outside of any function or block have global scope.
They can be accessed from any part of the code.
Global variables persist throughout the program's execution.
Example
global_variable = 20
def example_function( ):
print("Inside the function:", global_variable)
example_function( )
print("Outside the function:", global_variable)
In this case, global_variable is accessible both inside and outside the
example_function.
However, if you want to modify a global variable within a function, you need to use
the global keyword

Example
global_variable = 20
def modify_global_variable( ):
global global_variable
Introduction to Python Programming

global_variable += 1
modify_global_variable( )
print("Modified global variable:", global_variable)
Using global global_variable inside the function informs Python that you want to use
the global variable, not create a new local one.
Function composition

Function composition is a mathematical concept that involves combining two or more


functions to create a new function.
In Python, function composition can be achieved by defining a new function that calls
other functions in sequence.
The result of one function becomes the input for the next function.
Example
def square(x):
return x ** 2

def double(x):
return 2 * x

# Function composition: (double ∘ square)(x) = double(square(x))


def double_of_square(x):
return double(square(x))
# Test the composed function
result = double_of_square(3)
print("Result:", result)
Output
Result: 18
In this example, we have two simple functions, square and double.
Then a new function, double_of_square is defined, which is the composition of the
double and square functions.
The notation (double ∘ square)(x) means "apply square to x and then apply double to
the result."
When we call double_of_square(3), it is equivalent to calling double(square(3)),
resulting in 2 * (3 ** 2), which is 18.
Introduction to Python Programming

You can also use the compose function from the functools module to create a
composed function.
The compose function takes two or more functions as arguments and returns a new
function that is the composition of those functions.
Example
from functools import compose
def square(x):
return x ** 2

def double(x):
return 2 * x

# Using compose to create a composed function


double_of_square = compose(double, square)

# Test the composed function


result = double_of_square(3)
print("Result:", result)
Output
Result: 18
Recursion

When a function calls itself, it is called as recursion.

Example
# Python program to find factorial of given number

def factorial(n):

if (n==1 or n==0): # Checking the number is 1 or 0 then return 1

return 1 # Otherwise return factorial

else:
return (n * factorial(n - 1))
num = 5
Introduction to Python Programming

print("number : ",num)
print("Factorial : ",factorial(num))
Output
number : 5
Factorial : 120
In this example, the factorial function calculates the factorial of a number using
recursion.
The base case (n == 0 or n == 1) is defined to stop the recursion, and the function
returns 1 in those cases.
Otherwise, it multiplies n by the factorial of n - 1.
Example
# Python program to display the Fibonacci sequence
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
num = 7
# check if the number of terms is valid
if num <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(num):
print(fibo(i))
Output
Fibonacci sequence:
0
1
1
2
3
5
8
Introduction to Python Programming

String slices

A segment of a string is called a slice.

Selecting a slice is similar to selecting a character:

Example
>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'
The operator [n:m] returns the part of the string from the “n-th” character to the “m-
th” character, including the first but excluding the last.

If you omit the first index (before the colon), the slice starts at the beginning of the
string.

If you omit the second index, the slice goes to the end of the string:

Example
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:

Example
>>> fruit = 'banana'

>>> fruit[3:3]

''

An empty string contains no characters and has length 0, but other than that, it is the
same as any other string.
Introduction to Python Programming

String Immutability

In Python, strings are immutable, which means that once a string is created, its
content cannot be changed.

Cannot Modify Characters

We cannot change or modify individual characters of a string directly.

Example
>>> greeting = 'Hello, world!'

>>> greeting[0] = 'J'

TypeError: 'str' object does not support item assignment

The reason for the error is that strings are immutable, which means we can’t change
an existing string.

The best we can do is create a new string that is a variation on the original.

Example
>>> greeting = 'Hello, world!'

>>> new_greeting = 'J' + greeting[1:]

>>> new_greeting

'Jello, world!'

This example concatenates a new first letter onto a slice of greeting. It has no effect
on the original string.

String functions and method

String Functions
len( )
Returns the length of the string.
Example
s = "Hello, World!"
length = len(s)
print(length)
Introduction to Python Programming

Output
13

str( )

Converts other data types to a string.

Example
num = 42

str_num = str(num)

print(str_num)

Output
'42'

ord( )

Returns an integer representing the Unicode character.

Example
char = 'A'

unicode_value = ord(char)

print(unicode_value)

Output:
65
chr( )

Returns a string representing a character whose Unicode code point is the integer.

Example
unicode_value = 65

char = chr(unicode_value)

print(char)

Output:
'A'
Introduction to Python Programming

String Methods

Strings provide methods that perform a variety of useful operations.

A method is similar to a function.

It takes arguments and returns a value but the syntax is different.

For example, the method upper takes a string and returns a new string with all
uppercase letters.

Instead of the function syntax upper(word), it uses the method syntax word.upper( ).

Example
>>> word = 'banana'

>>> new_word = word.upper()

>>> new_word

'BANANA'

The dot notation specifies the name of the method, upper, and the name of the string
to apply the method to word. The empty parentheses indicate that this method takes no
arguments.

A method call is called an invocation; in this case, we would say that we are invoking

upper on word.

Find

Find( ) function is used to return the lowest index value of the first occurrence of the
substring from the input string.

Example
>>> word = 'banana'

>>> index = word.find('a')

>>> index

1
Introduction to Python Programming

In this example, we invoke find on word and pass the letter we are looking for as a
parameter.

The find method can find substrings, not just characters.

Example
>>> word.find('na')

find(sub[, start[, end]]) and index(sub[, start[, end]])

Both methods return the lowest index in the string where the substring sub is found.

The difference is that find( ) returns -1 if the substring is not found, while index( )
raises a ValueError.

Example
s = "Hello, World!"

index1 = s.find("World")

index2 = s.index("World")

print(index1)

print(index2)

Output:
7

count(sub[, start[, end]])

Returns the number of non-overlapping occurrences of the substring sub in the


string.

Example
s = "Hello, Hello, World!"

count = s.count("Hello")

print(count)
Introduction to Python Programming

Output
2

isdigit( ), isalpha( ), isalnum( ), isspace( ), isupper( ), islower( )

These methods return True if the string satisfies the condition specified by the
method name; otherwise, they return False.

Example
s = "123"

print(s.isdigit( )) # Output: True

print(s.isalpha( )) # Output: False

splitlines([keepends])

Returns a list of the lines in the string, breaking at line boundaries. If keepends
is True, the line breaks are included.

Example
s = "Line 1\nLine 2\nLine 3"

lines = s.splitlines()

print(lines)

Output: ['Line 1', 'Line 2', 'Line 3']

startswith(prefix[, start[, end]]) and endswith(suffix[, start[, end]])

These methods check if the string starts with the specified prefix or ends with the
specified suffix.

Example
s = "Hello, World!"

starts_with_hello = s.startswith("Hello")

ends_with_world = s.endswith("World!")

print(starts_with_hello) # Output: True

print(ends_with_world) # Output: True


Introduction to Python Programming

String module

The string module provides a collection of common string operations.

It contains a set of constants (such as ASCII letters, digits, and punctuation) and
functions that are useful for working with strings.

Some commonly used components of the string module

Constants

ascii_letters

Concatenation of ascii_lowercase and ascii_uppercase.

Example

import string

print(string.ascii_letters)

Output

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

ascii_lowercase

A string containing all ASCII lowercase letters.

Example

import string

print(string.ascii_lowercase)

Output

Abcdefghijklmnopqrstuvwxyz

ascii_uppercase

A string containing all ASCII uppercase letters.

Example

import string

print(string.ascii_uppercase)
Introduction to Python Programming

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Digits

A string containing all ASCII digits.

Example

import string

print(string.digits)

Output

0123456789

Punctuation

A string containing all ASCII punctuation characters.

Example

import string

print(string.punctuation)

Output

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Whitespace

A string containing all ASCII whitespace characters.

Example

import string

print(string.whitespace)

Output

>
Introduction to Python Programming

Functions

capwords(s, sep=None)
Capitalize the words in a string, where words are defined as substrings separated by
sep (default is whitespace).
Example
import string
s = "hello world"
capitalized = string.capwords(s)
print(capitalized)
Output
Hello World
Template(substitute)
A class for string templates with placeholders.
Example
from string import Template
template = Template("Hello, $name!")
result = template.substitute(name="Elayaraj")
print(result)
Output
Hello, Elayaraj!
Lists as arrays

In Python, lists can be used as a versatile and dynamic data structure, and they are
often used to implement arrays.

Some key points regarding lists as arrays in Python

Dynamic Sizing

Python lists are dynamically sized.

You can add or remove elements from a list without specifying its size beforehand.

Example

# Creating a list
Introduction to Python Programming

my_list = [1, 2, 3]

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

# Appending elements

my_list.append(4)

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

Indexing and Slicing

Lists in Python support indexing and slicing.

Indexing starts at 0, and negative indices represent elements from the end of the list.

Example

# Accessing elements

print(my_list[0]) # Output: 1

print(my_list[-1]) # Output: 4

# Slicing

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

Mutable

Lists are mutable, meaning you can modify their elements.

Example

# Modifying elements

my_list[1] = 5

print(my_list)

Output

[1, 5, 3,4]
Introduction to Python Programming

Common Operations

Lists support common operations like concatenation, repetition, and length calculation.

Example

# Concatenation

new_list = my_list + [6, 7]

print(new_list) #Output: [1, 5, 3, 4, 6, 7]

# Repetition

repeated_list = my_list * 2

print(repeated_list) #Output: [1, 5, 3, 4, 1, 5, 3, 4]

# Length

length = len(my_list)

print(length) #Output: 4

Built-in Functions and Methods

Python provides various built-in functions and methods for working with lists.

Example

# Built-in functions

print(min(my_list)) #Output: 1

print(max(my_list)) #Output: 5

print(sum(my_list)) #Output: 13

# Methods

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

my_list.remove(3) #Output: [1, 5, 4, 8]


Introduction to Python Programming

Unit - IV

List operations

Lists
List is a sequence of values called items or elements. The elements
can be of any type.

Through a list, we can use a single variable to store all the elements of
the same or different data type and even print them.

Creating Lists
List is created using the list constructor.
Example: Create a list using the constructor of the list class
a. Create an empty list.
L1 = list( );
b. Create a list with any three integer elements, such as 10, 20 and 30.
L2 = list([10,20,30])
c. Create a list with three string elements, such as “Apple”, “Banana” and
“Grapes”.
L3 = list([“Apple”,”Banana”,”Grapes”])
d. Create a list using inbuilt range( ) function.
L4 = list(range(0,6)) # create a list with elements from 0 to 5
e. Create a list with inbuilt characters X, Y and Z.
L5=list(“xyz”)
Example: Creating a list without using the constructor of the list class
a. Create a list with any three integer elements, such as 10, 20 and 30.
L1=[10,20,30]
b. Create a list with three string elements, such as “Apple”, “Banana” and
“Grapes”.
L2 = [“Apple”, “Banana”, “Grapes”]
A list can contain the elements of mixed type.
Example
L3=list([“Senthil”,”Male”,23,5.8])
Introduction to Python Programming

Accessing the Elements of a list


The elements of a list are unidentifiable by their positions. Hence, the
index [ ] operator is used to access them.
Syntax
Name_of_Variable_of_a_List[index]

Example
>>> L1=([10,20,30,40,50]) #Create a List with 5 Different Elements
>>> L1 #print the complete List
[10, 20, 30, 40, 50]
>>> L1[0] #Print the first element of the List
10
Explanation
L1 creates a list of five elements
L1 = [10,20,30,40,50]
where L1 is the reference variable of the list.

Negative List Indices


The negative index accesses the elements from the end of a list
counting in backward direction.
The index of the last element of any non-empty list is always -1.

Example
>>> List1=[10,20,30,40,50,60] #Create a List
>>> List1[-1] #Access Last element of a List
60
>>>List1[-2] #Access the second last element of List
50
>>> List1[-3] #Access the Third last element of List
40
>>>List1[-6] #Access the first Element of the List
10
Introduction to Python Programming

List slices

The slicing operator returns a subset of a list called slice by specifying


two indices, start and end.
Syntax
Name_of_Variable_of_a_List[Start_Index: End_Index]

Example
>>> L1=([10,20,30,40,50])
>>> L1[1:4]
20,30,40
The L1[1:4] returns the subset of the list starting from index the start
index 1 to one index less than that of the end index, i.e. 4-1 = 3.

Example
>>> L1=([10,20,30,40,50]) #Create a List with 5 Different
Elements
>>> L1[2:5]
[30, 40, 50]
L1 creates a list of five elements.
The index operator L1[2:5] returns all the elements stored between the
index 2 and one less than the end index, i.e. 5-1 = 4.

List Slicing with Step Size


➢ Step size is used to select every second or third element of a list.
➢ In slicing, the first two parameters are start index and end index.
➢ Thus, we need to add a third parameter as step size to select a list
with step size.
Syntax

List_Name[Start_Index:End_Index:Step_Size]

Example
>>>MyList1=[“Hello”,1,”Monkey”,2,”Dog”,3,”Donkey”]
>>>New_List1=MyList1[0:6:2]
print(New_List1)
[‘Hello’, ‘Monkey’, ‘Dog’]
Introduction to Python Programming

Explanation
A list named Mylist1 is created with five elements.
The statement MyList1[0:6:2] selects the portion of a list which starts
at index 0 and ends at index 6 with the step size 2.
It means a section or slice of the list which starts at the index 0 and
ends at the index 6 is selected and then selects every other second element.
Example
>>> List1=[“Python”,450,”C”,300,”,C++”,670]
>>> List1[0:6:3] #Start from Zero and Select every Third Element
[‘Python’, 300] #Output

Some more complex examples

>>> List1=[1,2,3,4] #List With Four Elements


>>> MyList1[:2] #Access first two elements of the List.
[1,2]
>>> MyList1[::-1] #Display List in Reverse Order
[4, 3, 2, 1]
#Start index with -1 and End Index with 0 and step Size with -1
>>>MyList1[-1:0:-1]
[4, 3, 2]
List methods

List methods are used to manipulate the list.


None append(object x)
Adds an element x to the end of the list.
None is the return type of method appended.
Example
>>> List1=[‘X’,’Y’,’Z’]
>>> List1
[‘X’, ‘Y’, ‘Z’]
>>> List1.append(‘A’) #Append element ‘A’ to the end of the List1
>>> List1
[‘X’, ‘Y’, ‘Z’, ‘A’]
Introduction to Python Programming

None clear( )
Removes all the items from the list.
Example
>>> List1=[“Red”, “Blue”, “Pink”]
>>> List1
[‘Red’, ‘Blue’, ‘Pink’]
>>> List1.clear( ) # Removes all the element of List
>>> List1 #Returns Empty List after removing all elements

[]
int count(object x)
Returns the number of times the element x appears in the list.
Example
>>> List1=[‘A’,’B’,’C’,’A’,’B’,’Z’]
>>> List1
[‘A’, ‘B’, ‘C’, ‘A’, ‘B’, ‘Z’] #Count the number of times the
element ‘A’ has appeared in the list
>>> List1.count(‘A’)
2 # Thus, ‘A’ has appeared 2 times in List1
List copy( )
This method returns a shallow copy of the list.
Example
>>> List1=[“Red”,”Blue”,”Pink”]
>>> List1
[‘Red’, ‘Blue’, ‘Pink’]
>>> List2=List1.copy( ) # Copy the contents of List1 to List2
>>> List2
[‘Red’, ‘Blue’, ‘Pink’]
Copy( ) Method is equivalent to List2=List1[:] # Copies the content of
List1 to List2
None extend(list L2)
Appends all the elements of list L2 to the list.
Example
>>> List1= [1,2,3]
>>> List2= [4,5,6]
Introduction to Python Programming

>>> List1
[1, 2, 3]
>>> List2
[4, 5, 6]
>>> List1.extend(List2) #Appends all the elements of List2 to List1

>>> List1
[1, 2, 3, 4, 5, 6]
int index(object x)
Returns the index of the first occurrence of the element x from the list.
Example
>>> List1=[‘A’,’B’,’C’,’B’,’D’,’A’]
>>> List1
[‘A’, ‘B’, ‘C’, ‘B’, ‘D’, ‘A’]
#Returns the index of first occurrence of
element ‘B’ from the list1
>>> List1.index(‘B’)
1 #Returns the index of element B
None insert(int index,Object X)
Insert the element at a given index.
Example
>>> Lis1=[10,20,30,40,60]
>>> Lis1
[10, 20, 30, 40, 60]
>>> Lis1.insert(4,50) #Insert Element 50 at index 4
>>> Lis1
[10, 20, 30, 40, 50, 60]
Object pop(i)
Removes the element from the given position.
Also, it returns the removed element.
Example
>>> Lis1=[10,20,30,40,60]
>>> Lis1
[10, 20, 30, 40, 60]
Introduction to Python Programming

>>> Lis1.pop(1) #Remove the element which is at index 1.


20
>>> Lis1 #Display List after removing the
element from index 1.
[10, 30, 40, 60]
>>> Lis1.pop( ) #Remove the last element from the list
60
>>> Lis1
[10, 30, 40] #Display the list after removing last
element
None remove(object x)
Removes the first occurrence of element x from the list.
Example
>>> List1=[‘A’,’B’,’C’,’B’,’D’,’E’]
>>> List1
[‘A’, ‘B’, ‘C’, ‘B’, ‘D’, ‘E’]
>>> List1.remove(‘B’) #Removes the first occurrence of element B
>>> List1
[‘A’, ‘C’, ‘B’, ‘D’, ‘E’]
None reverse( )
Reverses the element of the list.
Example
>>> List1=[‘A’,’B’,’C’,’B’,’D’,’E’]
>>> List1
[‘A’, ‘B’, ‘C’, ‘B’, ‘D’, ‘E’]
>>> List1.reverse( ) # Reverse all the elements of the list.
>>> List1
[‘E’, ‘D’, ‘B’, ‘C’, ‘B’, ‘A’]
None sort( )
Example
>>> List1=[‘G’,’F’,’A’,’C’,’B’]
>>> List1
[‘G’, ‘F’, ‘A’, ‘C’, ‘B’] #Unsorted List
Introduction to Python Programming

>>> List1.sort( )
>>> List1 #Sorted List
[‘A’, ‘B’, ‘C’, ‘F’, ‘G’]

List loop

for loop iterating over a list

Example

# Example: Using a for loop with a list


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

# Loop to print each element in the list


for item in my_list:
print(item)
In this example, the for loop iterates over each element (item) in the my_list and
prints it.
The output will be:
10
20
30
40
50
List Mutability

Lists are mutable, which means that we can modify the list elements, change the size,
and even reassign the entire list.

This mutability allows to alter the content of a list after it has been created.

Some examples to illustrate the mutability of lists

Modifying Elements

Example

# Original list

my_list = [1, 2, 3, 4, 5]
Introduction to Python Programming

# Modifying an element at a specific index

my_list[2] = 10

print(my_list)

Output

[1, 2, 10, 4, 5]

Changing Size

Example

# Original list

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

# Appending an element to the end of the list

my_list.append(6)

# Removing an element by value

my_list.remove(3)

print(my_list)

Output

[1, 2, 4, 5, 6]

Reassigning the Entire List

Example

# Original list

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

# Reassigning the entire list

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

print(my_list)
Introduction to Python Programming

Output

[10, 20, 30, 40, 50]

List Aliasing

List aliasing in Python occurs when two or more variables reference the same list
object.
If a refers to an object and you assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference.
An object with more than one reference has more than one name, so we say that the
object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
Example
# Original list
original_list = [1, 2, 3, 4, 5]

# Creating an alias (another reference) to the same list


alias_list = original_list

# Modifying the list through the alias


alias_list[2] = 10

# Both variables refer to the same list, so changes are reflected in both
print(original_list)
print(alias_list)
Output
[1, 2, 10, 4, 5]
[1, 2, 10, 4, 5]
In this example, original_list and alias_list both refer to the same list object.
Introduction to Python Programming

When an element is modified through the alias_list, the change is visible when
printing the original_list as well.
To avoid aliasing and create a new independent copy of a list, you can use the copy
method or the slicing syntax.
Example
# Creating an independent copy using the copy method
original_list = [1, 2, 3, 4, 5]
copied_list = original_list.copy( )

# Modifying the copied list does not affect the original list
copied_list[2] = 10

print(original_list)
print(copied_list)
Output:
[1, 2, 3, 4, 5]
[1, 2, 10, 4, 5]
Cloning lists

To clone or create an independent copy of a list, three common ways are used.
❖ Using the copy method
❖ Using the list constructor
❖ Using slicing syntax ([:])
Using the copy method
original_list = [1, 2, 3, 4, 5]
cloned_list = original_list.copy()

# Modifying the cloned list does not affect the original list
cloned_list[2] = 10

print(original_list)
print(cloned_list)
Introduction to Python Programming

Output
[1, 2, 3, 4, 5]
[1, 2, 10, 4, 5]
Using the list constructor
original_list = [1, 2, 3, 4, 5]
cloned_list = list(original_list)

# Modifying the cloned list does not affect the original list
cloned_list[2] = 10

print(original_list)
print(cloned_list)
Output
[1, 2, 3, 4, 5]
[1, 2, 10, 4, 5]
Using slicing syntax ([:])
original_list = [1, 2, 3, 4, 5]
cloned_list = original_list[:]

# Modifying the cloned list does not affect the original list
cloned_list[2] = 10

print(original_list)
print(cloned_list)
Output

[1, 2, 3, 4, 5]
[1, 2, 10, 4, 5]
Introduction to Python Programming

List parameters

We can pass a list as a parameter to a function, just like any other variable type.

When passing a list to a function, we can modify the contents of the list within the
function, and the changes will be reflected outside the function.

This is because lists are mutable objects in Python.

Example

def modify_list(my_list):

# Modifying the list inside the function

my_list.append(6)

my_list[1] = 100

# Creating a list

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

# Passing the list to the function

modify_list(original_list)

# Changes made inside the function are reflected outside

print(original_list)

Output

[1, 100, 3, 4, 5, 6]

In this example, the modify_list function takes a list as a parameter (my_list) and
appends an element and modifies an existing element.

When printing the original_list after calling the function, we can see that the changes
made inside the function are reflected in the original list.
Introduction to Python Programming

Tuple as return value


We can use a tuple as a return value from a function.
Returning a tuple allows to return multiple values from a function and the caller can
easily unpack those values.

Example
def calculate_values(x, y):
# Perform some calculations
sum_result = x + y
product_result = x * y

# Return a tuple containing the results


return sum_result, product_result

# Call the function and unpack the returned tuple


result_sum, result_product = calculate_values(3, 4)

# Print the results


print("Sum:", result_sum)
print("Product:", result_product)
Output
Sum: 7
Product: 12

In this example, the calculate_values function takes two parameters x and y, performs
some calculations (sum and product), and returns a tuple (sum_result, product_result).

When calling the function, the returned tuple is unpacked into two variables
(result_sum and result_product), and these values are printed.

We can also directly access elements of the tuple returned by the function using
indexing.

Example

# Call the function and access elements of the returned tuple


Introduction to Python Programming

result_tuple = calculate_values(3, 4)

# Print the individual elements

print("Sum:", result_tuple[0])

print("Product:", result_tuple[1])

Output
Sum: 7
Product: 12

Dictionaries: operations and methods

A dictionary is a collection that stores values along with keys.


The sequence of key and value pairs is separated by commas. These
pairs are sometimes called entries or items.
All entries are enclosed in curly brackets { and }. A colon separates a
key and its value.
Sometimes, items are also called associative arrays because they
associate a key with a value.

Example

Phonebook - {“Senthil”:“918624986968”, “Sridharan”:“919766962920”}

Country Code Information - {“India”:“+91”,“USA”:“+1”,“Singapore”: “+65”}


Introduction to Python Programming

Keys are like an index operator in a dictionary. A key can be of any


type.
Therefore, a dictionary maps a set of objects, i.e. keys to another set of
objects, i.e. values.
It is a mapping of unique keys to values, i.e. each key is mapped to
one value.
Also, dictionaries do not contain any duplicate keys.
Creating a Dictionary
We can create a dictionary by enclosing the items inside a pair of curly
brackets { }.
One way to start a dictionary is to create an empty dictionary first and
then add items to it.
Creating an Empty Dictionary

Example

>>>D1 = { } # Create Empty Dictionary


>>>D1 # Print Empty Dictionary
{}
>>> type(D1) # Check the type of D1
<class ‘dict’>
Python uses curly brackets for sets and dictionaries.
Therefore, to create an empty dictionary, we use { } and to create an
empty set, we use the function set( ).

Creating a Dictionary with Two Items


To create a dictionary of two items, the items should be in the form of
key:value and separated by commas.
Example
>>> P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}
>>> P #Display P
{‘ Senthil’: ‘918624986968’, ‘Sridharan’: ‘919766962920’}
Creating Dictionaries in Four Different Ways
Example
Introduction to Python Programming

#Way 1
>>>D1={‘Name’:’Senthil’,’Age’:23}
>>> D1
{‘Name’: ‘Senthil’, ‘Age’: 23}
#Way 2
>>> D2={ }
>>> D2[‘Name’]=’Senthil’
>>> D2[‘Age’]=23
>>> D2
{‘Name’: ‘Senthil’, ‘Age’: 23}
#Way 3
>>> D3=dict(Name=’Senthil’,Age=23)
>>> D3
{‘Name’: ‘Senthil’, ‘Age’: 23}
#Way 4
>>> dict([(‘name’,’Senthil’),(‘age’,23)])
{‘age’: 23, ‘name’: ‘Senthil’}
Explanation
In the above example, we have created dictionaries in four different
ways.
We can select the first way if we know all the contents of a dictionary
in advance.
The second way, if we want to add one field at a time.
The third way requires all keys to string.
The fourth way is good if we want to build keys and values at runtime.
Adding, Replacing and Retrieving Values
To add a new item to a dictionary, we can use the subscript[ ]
operator.
Syntax
Dictionary_Name[key] = value

Example

P[“Mani”]=”913456789087”

In the above example, the name of the dictionary is P.


Introduction to Python Programming

We are adding the phone number of “Mani” into the phonebook.

The “Mani” will act as the key and the phone number of Mani will be its
value.
#Running the above example in Python interactive mode
#Create Dictionary of Phonebook
P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}
>>> P #Display P
{‘Senthil’: ‘918624986968’, ‘Sridharan’: ‘919766962920’}
#Add another element to the existing Dictionary of Phone Book P
>>> P[“Mani”]=”913456789087” #Add New element
>>> P
{‘Mani’: ‘913456789087’, ‘Senthil’: ‘918624986968’, ‘Sridharan’:
‘919766962920’}

If a key is already present in a list then it replaces the old value with the
new value.

Example

P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}

>>> P #Display P

{‘Senthil’: ‘918624986968’, ‘Sridharan’: ‘919766962920’}

>>> P[“Senthil”]=”921029087865” #Replace the Old value by New

>>> P #Print After Replacing

{‘Senthil’: ‘921029087865’, ‘Sridharan’: ‘919766962920’}


Retrieving Values

The subscript[ ] can also be used to obtain the value associated with a
key.

Syntax

Dictinoary_Name[Key] #Retrieve the value associated with the key

Example

P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}

>>> P #Display P
Introduction to Python Programming

{‘Senthil’: ‘918624986968’, ‘Sridharan’: ‘919766962920’}

>>> P[“Sridharan”] #Display the value associated with the key “Sridharn”

‘919766962920’
Formatting Dictionaries

The % operator is used to substitute values from a dictionary, into a


string by a name.
Example
>>> D={ }

>>> D[“Laptop”]=”MAC”

>>> D[“Count”]=10

>>> D #Print Dictionary D

{‘Laptop’: ‘MAC’, ‘Count’: 10}

>>> P=”I want %(Count)d %(Laptop)s Laptops”%D

>>> P

‘I want 10 MAC Laptops’


Explanation
In the above program, initially a dictionary is created containing two keys,
‘Laptop’ and ‘Count’.

In the statement, “I want %(Count)d %(Laptop)s Laptops”%D.”

The characters ‘d’ and ‘s’ for integer and string.


Deleting Items

We can delete any entry from a dictionary. The del operator is used to
remove a key and its associated value.

If a key is in a dictionary then it is removed otherwise Python raises an


error.

Syntax

del dictionary_name[key]

Example

>>>P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}
Introduction to Python Programming

>>> del P[“Senthil”] #delete key “Amit”

>>> P #Print after deleting

{‘Sridharan’: ‘919766962920’}
Comparing Two Dictionaries

The == operator is used to test if two dictionaries contain the same items.
The != operator returns True if the items within dictionaries are not the
same.
Example

>>> A={“I”:”India”,”A”:”America”}

>>> A

{‘I’: ‘India’, ‘A’: ‘America’}

>>> B={“I”:”Italy”,”A”:”America”}

>>> B

{‘I’: ‘Italy’, ‘A’: ‘America’}

>>> A==B

False

>>> A!=B

True
Methods of Dictionary Class

Python contains dict class for dictionaries.

To see the complete documentation for dictionaries we can run help(dict) in


Python interactive mode.

Some commonly used dictionary operations

keys( )

Returns a sequence of keys.


Example
>>> ASCII_CODE={“A”:65,”B”:66,”C”:67,”D”:68}

>>> ASCII_CODE #Print Dictionary named ASCII_CODE


Introduction to Python Programming

{‘D’: 68, ‘B’: 66, ‘A’: 65, ‘C’: 67}

>>> ASCII_CODE.keys( ) #Return all keys

dict_keys([‘D’, ‘B’, ‘A’, ‘C’])

Values( )
Returns a sequence of values.
Example
>>> ASCII_CODE={“A”:65,”B”:66,”C”:67,”D”:68}

>>> ASCII_CODE.values( ) #Return Values

dict_values([68, 66, 65, 67])

items( )
Returns a sequence of tuples.
Example
>>>ASCII_CODE={“A”:65,”B”:66,”C”:67,”D”:68}

>>>ASCII_CODE.items( )

dict_items([(‘D’, 68), (‘B’, 66), (‘A’, 65), (‘C’, 67)])


clear( )
Deletes all entries.
Example
>>>ASCII_CODE={“A”:65,”B”:66,”C”:67,”D”:68}

>>> ASCII_CODE.clear( ) # Delete all entries

>>> ASCII_CODE # Print after

{}
get(key)
Returns the value for a key.
Example
>>> Temperature={“Mumbai”:35,”Delhi”:40,”Chennai”:54}

>>> Temperature.get(“Mumbai”)

35
pop(key)
Removes a key and returns the value if the key exists.
Introduction to Python Programming

Example
>>> Temperature.pop(“Mumbai”)

35

>>> Temperature #Print after removing key “Mumbai”.

{‘Delhi’: 40, ‘Chennai’: 54}


clear( )
Removes all the keys.

Example
>>> Temperature={“Mumabai”:35,”Delhi”:40,”Chennai”:54}

>>> Temperature.clear( )
>>> Temperature

Advanced list processing

List Comprehensions

List comprehensions provide a concise way to create lists.

They can also be used for filtering and transforming existing lists.

Example

squares = [x**2 for x in range(10)]

print(squares)

even_squares = [x**2 for x in range(10) if x % 2 == 0]

print(even_squares)

Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[0, 4, 16, 36, 64]

Filtering with filter( ) and lambda functions

The filter( ) function, combined with a lambda function, can be used to filter elements
based on a condition.
Introduction to Python Programming

Example

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens)

Output

[2, 4, 6, 8]

Mapping with map( ) and lambda functions

The map( ) function applies a function to all items in an input list.

Example

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

squares = list(map(lambda x: x**2, numbers))

print(squares)

Output

[1, 4, 9, 16, 25]

Reducing with functools.reduce( )

The functools.reduce( ) function performs a cumulative operation on the items of an


iterable.

Example

from functools import reduce

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

product = reduce(lambda x, y: x * y, numbers)

print(product)

Output

120
Introduction to Python Programming

Zip and Unzip

The zip( ) function combines multiple iterables element-wise, and zip(*iterables) can
be used to unzip a list of tuples.

Example

names = ['Elayaraj', 'Dhanush', 'Suriya']

ages = [18, 20, 22]

combined = list(zip(names, ages))

unzipped_names, unzipped_ages = zip(*combined)

print(combined)

print(unzipped_names)

print(unzipped_ages)

Output

[('Elayaraj', 18), ('Dhanush', 20), ('Suriya', 22)]

('Elayaraj', 'Dhanush', 'Suriya')

(18, 20, 22)

Enumerate

The enumerate( ) function provides an index along with the value during iteration.

Example

names = ['Elayaraj', 'Dhanush', 'Suriya']

for index, name in enumerate(names):

print(f"Person {index + 1}: {name}")

Output

Person 1: Elayaraj

Person 2: Dhanush

Person 3: Suriya
Introduction to Python Programming

List Slicing and Striding


Advanced slicing allows you to extract sublists and apply strides (step values).
Example
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sub_list = numbers[2:7] # Elements from index 2 to 6
reversed_list = numbers[::-1] # Reverse the list
print(sub_list)
print(reversed_list)
Output
[3, 4, 5, 6, 7]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
List Concatenation and Repetition
Lists can be concatenated using the + operator and repeated using the * operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated = list1 + list2
repeated = list1 * 3
print(concatenated)
print(repeated)
Output
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Sorting with Custom Key
The sorted( ) function can be used with a custom key function to sort a list based on
specific criteria.
words = ['apple', 'banana', 'cherry', 'date']

sorted_by_length = sorted(words, key=len)

print(sorted_by_length)

Output

['date', 'apple', 'banana', 'cherry']


Introduction to Python Programming

List Flattening
Flattening a nested list can be achieved using list comprehensions or the
itertools.chain( ) function.
Example
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened = [item for sublist in nested_list for item in sublist]
print(flattened)
Output
[1, 2, 3, 4, 5, 6, 7, 8]
List comprehension

List comprehension is used to create a new list from existing


sequences.
It is a tool for transforming a given list into another list.
List comprehension contains:
a. An input sequence
b. A variable referencing the input sequence
c. An optional expression
d. An output expression or output variable

Example

Advantages
List comprehension requires lesser code and also runs faster.
Example: Without list comprehension
Create a list to store five different numbers such as 10, 20, 30, 40 and
50. Using the for loop, add number 5 to the existing elements of the list.
Introduction to Python Programming

>>> List1= [10, 20, 30, 40, 50]


>>> List1
[10, 20, 30, 40, 50]
>>> for i in range(0,len(List1)):
List1[i]=List1[i]+10 #Add 5 to each element of List1
>>> List1 #print the List1 after Performing
[20, 30, 40, 50,60]
The above code is workable but not the optimal code or the best way.
Using list comprehension, we can replace the loop with a single
expression that produces the same result.
Syntax

[<expression> for <element> in <sequence> if <conditional>]

Example: Using list comprehension


>>> List1= [10,20,30,40,50]
>>> List1= [x+10 for x in List1]
>>> List1
[20, 30, 40, 50, 60]

Program to create a list with elements 1,2,3,4 and 5. Display even elements of
the list using list comprehension.
List1=[1,2,3,4,5]
print(“Content of List1”)
print(List1)
List1=[x for x in List1 if x%2==0]
print(“Even elements from the List1”)
print(List1)

Output
Content of List1
[1, 2, 3, 4, 5]
Even elements from the List1
[2, 4]
Introduction to Python Programming

Unit - V

Files and exception

Text files (Or) Reading and writing files

A file is some information or data which is stored in the computer storage devices.
File operations include:
❖ Open a file
❖ Read or write - Performing operation
❖ Close the file
Opening a Text File:
To open a text file, you can use the open( ) function.
Syntax
File_object = open("filename.txt", "mode")
"filename.txt" is the name of the file.
"mode" specifies the mode in which the file is opened, such as "r" for read, "w" for
write, or "a" for append.
Reading from a Text File
To read the contents of a text file, you can use methods like read( ), readline( ), or
readlines( ).
read( )
Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire
file.
Syntax
File_object.read([n])
readline( )
Reads a line of the file and returns in form of a string.For specified n, reads at most n
bytes. However, does not reads more than one line, even if n exceeds the length of the line.
Syntax
File_object.readline([n])
readlines( )
Reads all the lines and return them as each line a string element in a list.
Syntax
File_object.readlines( )
Introduction to Python Programming

Example 1
File = open (“read.txt”, “r”)
Example 2
# Reading the entire file
with open("filename.txt", "r") as file:
content = file.read( )
print(content)

# Reading line by line


with open("filename.txt", "r") as file:
for line in file:
print(line.strip( )) # strip( ) removes newline characters
Writing to a Text File
To write to a text file, you can use methods like write( ).
Example
# Writing to a file
with open("filename.txt", "w") as file:
file.write("Hello, this is a sample text.\n")
file.write("This is another line.")
Appending to a Text File
To append content to an existing text file, you can use the "a" mode.
Example
# Appending to a file
with open("filename.txt", "a") as file:
file.write("This line will be appended to the file.")
Closing a Text File
Close( ) function closes the file and frees the memory space.
It is used when the file is no longer needed.
Example 1
file1 = open("MyFile.txt","a")
file1.close( )
Introduction to Python Programming

Example 2
with open("filename.txt", "r") as file:
content = file.read( )
# Do something with the content

# File is automatically closed when exiting the "with" block


Format operator

The format operator in Python is %.

It is used for formatting strings by replacing placeholders with values.

Example

name = "Elayaraj"

age = 20

height = 175.5

# Using the format operator to create a formatted string

formatted_string = "Name: %s, Age: %d, Height: %.2f" % (name, age, height)

print(formatted_string)

Output

Name: Elayaraj, Age: 20, Height: 175.50

In this example:

%s is a placeholder for a string (name).

%d is a placeholder for an integer (age).

%.2f is a placeholder for a floating-point number with two decimal places


(height).

The values to be substituted for the placeholders are specified after the %
operator in a tuple (name, age, height).
Introduction to Python Programming

Placeholders commonly used with the % operator:

%s: String

%d: Decimal (integer)

%f: Floating-point

%x: Hexadecimal

Another way to format strings in Python is by using the str.format( ) method or f-


strings (formatted string literals) in Python 3.6 and later versions.

Using str.format( )

name = "Elayaraj"

age = 20

height = 175.5

formatted_string = "Name: { }, Age: { }, Height: {:.2f}".format(name, age, height)

print(formatted_string)

Output

Name: Elayaraj, Age: 20, Height: 175.50

Using f-strings (Python 3.6 and later)

name = "Elayaraj"

age = 20

height = 175.5

formatted_string = f"Name: {name}, Age: {age}, Height: {height:.2f}"

print(formatted_string)

Output

Name: Elayaraj, Age: 20, Height: 175.50


Introduction to Python Programming

Command line arguments

Command Line Arguments provides a convenient way to accept some information at


the command line while running the program.

The arguments that are given after the name of the Python script are known
as Command Line Arguments and they are used to pass some information to the program.

Example

$ python script.py arg1 arg2 arg3

Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3
are command line arguments for the program.

There are several methods for command line arguments such as sys module, getopt
module, argparse module, etc.

The most common method is sys module

sys module - System-specific parameters

The Python sys module provides access to any command-line arguments via the
sys.argv.

It serves two purposes:

➢ sys.argv is the list of command-line arguments.

➢ len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example 1

Consider the following script test.py −

import sys

print('Number of arguments:', len(sys.argv), 'arguments.')

print('Argument List:', str(sys.argv))

While running the code like this

$ python test.py arg1 arg2 arg3


Introduction to Python Programming

The output will be


Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Example 2
import sys
# The first element in sys.argv is the script name

script_name = sys.argv[0]

# The rest of the elements are the command line arguments

arguments = sys.argv[1:]

# Print the script name and arguments

print("Script name:", script_name)

print("Arguments:", arguments)

When running the script with command line arguments like this:

python script.py arg1 arg2 arg3

The output will be

Script name: script.py

Arguments: ['arg1', 'arg2', 'arg3']

Errors and exceptions

❖ Syntax Errors

❖ Runtime Errors

❖ Logical Errors

❖ Exceptions

Syntax Errors

Syntax errors occur when the code violates the rules of the programming language.

Example

Missing parentheses, unmatched braces, or incorrect indentation.


Introduction to Python Programming

Runtime Errors
Runtime errors occur during the execution of the program and are often caused by
unexpected conditions.
Example
Division by zero, accessing an index out of bounds, or using a variable before it is
initialized.
Logical Errors
Logical errors do not result in immediate crashes but cause the program to produce
incorrect results.
Example
Flawed algorithm, incorrect conditional statements, or improper data handling.
Exceptions
Exceptions are events that occur during the execution of a program that disrupt the
normal flow of instructions.
Example
ZeroDivisionError, TypeError, FileNotFoundError, etc.
Handling exceptions
In Python, exceptions are handled using a try-except block.
Syntax
try:

# code that may raise an exception

except SomeException as e:

# code to handle the exception

else:

# optional block that runs if no exception is raised

finally:

# optional block that always runs, whether an exception is raised or not

The try block contains the code that may raise an exception.

The except block is executed if an exception of the specified type (SomeException in


the example) is raised. You can catch specific exceptions or use a more general except block
to catch any exception.
Introduction to Python Programming

The as e part allows you to reference the exception object. This can be useful for
obtaining additional information about the exception.

The else block is optional and is executed only if no exceptions are raised in the try
block.

The finally block is also optional and is always executed, whether an exception is
raised or not. It's often used for cleanup actions (e.g., closing files or network connections).

Example

try:
x = 10
y=0
result = x / y
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print(f"Result: {result}")
finally:
print("This always runs, regardless of whether there was an exception.")
Output

ERROR!

Error: division by zero

This always runs, regardless of whether there was an exception.


You can handle multiple exceptions by using multiple except blocks or a tuple of
exception types.
Syntax
try:
# code that may raise an exception
except (ExceptionType1, ExceptionType2) as e:
# code to handle the exception
Introduction to Python Programming

Modules

A module is a file containing Python definitions and statements.

The file name is the module name with the suffix .py.

Modules allow to organize the code logically and break it into smaller, manageable
files.

Modules also provide a way to reuse code across different Python programs.

Some key concepts related to modules in Python:

Creating a Module
To create a module, you typically write your Python code in a file with a .py
extension.
For example, if you have a file named my_module.py, it becomes a Python module.
Example content of my_module.py
# my_module.py

def greet(name):
print(f"Hello, {name}!")
Using a Module
To use a module in another Python script, you can use the import statement.
Example
# another_script.py
import my_module

my_module.greet("Elayaraj")
Module Namespace
When you import a module, you create a namespace that contains the names defined
in the module.
Example
# another_script.py
import my_module

my_module.greet("Dhanush")
Introduction to Python Programming

Importing Specific Items

You can import specific functions or variables from a module using the from ...
import ... syntax.

Example

# another_script.py

from my_module import greet

greet("Suriya")
Module Search Path

Python searches for modules in directories specified by the sys.path variable.

You can add directories to this list if your module is not in the same directory as your
script.

Example

import sys

sys.path.append("/path/to/your/module")

Standard Library

Python comes with a rich set of standard libraries/modules that provide a wide range
of functionality.

These modules cover areas such as file I/O, networking, mathematics, and more.

Example
import math

print(math.sqrt(25))
Creating Packages
Packages are a way of organizing related modules into a directory hierarchy.

A package is a directory containing an init .py file and one or more module files.
Introduction to Python Programming

Example

my_package/

├── init .py

├── module1.py

└── module2.py

Executing Modules as Scripts


A Python script can be designed to act as either the main program or as a module.
The if _ _name_ _ == "_ _main_ _": construct is often used to distinguish between the
two cases.
Example
# my_module.py

def greet(name):
print(f"Hello, {name}!")

if _ _name_ _ == "_ _main_ _":


# Code to execute when the module is run as a script
greet("World")
Packages

A package is a way of organizing related modules into a directory hierarchy.

A package is a collection of Python module files (.py files) organized in directories.

It allows you to structure your code in a more modular and organized way, making it
easier to manage and maintain large projects.

Overview of how packages work in Python

Package Structure

A package is simply a directory that contains a special file named _ _init_ _.py.

This file can be empty or can contain Python code. The presence of this file tells
Python that the directory should be treated as a package.
Introduction to Python Programming

Example

my_package/

├── _ _init_ _.py

├── module1.py

└── module2.py

Importing Modules from a Package

You can import modules from a package using the dot notation.

For example, if you have a module named module1 inside a package named
my_package, you can import it as follows:

from my_package import module1

Accessing Subpackages

Packages can contain subpackages, creating a nested hierarchy.

You can access submodules and subpackages using the dot notation.

from my_package.subpackage import module3

init .py File

The _ _init_ _.py file can be empty or can contain Python code.

It is executed when the package is imported and can be used to initialize package-
level variables or perform other setup tasks.

# Example init .py

print("Initializing my_package")

Relative Imports
You can use relative imports within a package to reference other modules or
subpackages within the same package.
# Inside module1.py
from .module2 import some_function
Introduction to Python Programming

Absolute Imports

Absolute imports specify the full path to the module or package starting from the top-
level directory. This is the default behavior for imports in Python 3.

# Absolute import

from my_package.module1 import some_function

_ _all_ _ Variable

If you want to control what gets imported when someone uses the from my_package
import *.

you can define the _ _all_ _ variable in your _ _init_ _.py file.

# Inside _ _init_ _.py

_ _all_ _ = ['module1', 'module2']

Namespace Packages

Namespace packages allow you to create a package across multiple directories


without the need for an _ _init_ _.py file.

This is particularly useful in scenarios where modules are distributed across different
locations.

You might also like