I - AI & DS_Python
I - AI & DS_Python
(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.
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
Unit – I
Algorithms
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 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
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.
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
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.
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
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
>>>
Now you can enter Python commands directly at the >>> prompt:
Introduction to Python Programming
➢ 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]
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
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
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
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
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
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
Comments
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
➢ 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
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
➢ 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
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 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.")
if statements
Syntax
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
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
Output
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
State
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.
While loop
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
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
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
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)
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
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
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
def double(x):
return 2 * x
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
Example
# Python program to find factorial of given number
def factorial(n):
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
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.
Example
>>> greeting = 'Hello, world!'
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
'Jello, world!'
This example concatenates a new first letter onto a slice of greeting. It has no effect
on the original string.
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( )
Example
num = 42
str_num = str(num)
print(str_num)
Output
'42'
ord( )
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
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
'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
1
Introduction to Python Programming
In this example, we invoke find on word and pass the letter we are looking for as a
parameter.
Example
>>> word.find('na')
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
Example
s = "Hello, Hello, World!"
count = s.count("Hello")
print(count)
Introduction to Python Programming
Output
2
These methods return True if the string satisfies the condition specified by the
method name; otherwise, they return False.
Example
s = "123"
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)
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!")
String module
It contains a set of constants (such as ASCII letters, digits, and punctuation) and
functions that are useful for working with strings.
Constants
ascii_letters
Example
import string
print(string.ascii_letters)
Output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
ascii_lowercase
Example
import string
print(string.ascii_lowercase)
Output
Abcdefghijklmnopqrstuvwxyz
ascii_uppercase
Example
import string
print(string.ascii_uppercase)
Introduction to Python Programming
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits
Example
import string
print(string.digits)
Output
0123456789
Punctuation
Example
import string
print(string.punctuation)
Output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Whitespace
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.
Dynamic Sizing
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]
# Appending elements
my_list.append(4)
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
Mutable
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
# Repetition
repeated_list = my_list * 2
# Length
length = len(my_list)
print(length) #Output: 4
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
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
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.
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
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_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
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
>>> List1.sort( )
>>> List1 #Sorted List
[‘A’, ‘B’, ‘C’, ‘F’, ‘G’]
List loop
Example
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.
Modifying Elements
Example
# Original list
my_list = [1, 2, 3, 4, 5]
Introduction to Python Programming
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]
my_list.append(6)
my_list.remove(3)
print(my_list)
Output
[1, 2, 4, 5, 6]
Example
# Original list
my_list = [1, 2, 3, 4, 5]
print(my_list)
Introduction to Python Programming
Output
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]
# 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.
Example
def modify_list(my_list):
my_list.append(6)
my_list[1] = 100
# Creating a list
original_list = [1, 2, 3, 4, 5]
modify_list(original_list)
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
Example
def calculate_values(x, y):
# Perform some calculations
sum_result = x + y
product_result = x * y
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
result_tuple = calculate_values(3, 4)
print("Sum:", result_tuple[0])
print("Product:", result_tuple[1])
Output
Sum: 7
Product: 12
Example
Example
#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”
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
The subscript[ ] can also be used to obtain the value associated with a
key.
Syntax
Example
P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}
>>> P #Display P
Introduction to Python Programming
>>> P[“Sridharan”] #Display the value associated with the key “Sridharn”
‘919766962920’
Formatting Dictionaries
>>> D[“Laptop”]=”MAC”
>>> D[“Count”]=10
>>> P
We can delete any entry from a dictionary. The del operator is used to
remove a key and its associated value.
Syntax
del dictionary_name[key]
Example
>>>P={“Senthil”:”918624986968”, “Sridharan”:”919766962920”}
Introduction to Python Programming
{‘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
>>> B={“I”:”Italy”,”A”:”America”}
>>> B
>>> A==B
False
>>> A!=B
True
Methods of Dictionary Class
keys( )
Values( )
Returns a sequence of values.
Example
>>> ASCII_CODE={“A”:65,”B”:66,”C”:67,”D”:68}
items( )
Returns a sequence of tuples.
Example
>>>ASCII_CODE={“A”:65,”B”:66,”C”:67,”D”:68}
>>>ASCII_CODE.items( )
{}
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
Example
>>> Temperature={“Mumabai”:35,”Delhi”:40,”Chennai”:54}
>>> Temperature.clear( )
>>> Temperature
List Comprehensions
They can also be used for filtering and transforming existing lists.
Example
print(squares)
print(even_squares)
Output
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]
print(evens)
Output
[2, 4, 6, 8]
Example
numbers = [1, 2, 3, 4, 5]
print(squares)
Output
Example
numbers = [1, 2, 3, 4, 5]
print(product)
Output
120
Introduction to Python Programming
The zip( ) function combines multiple iterables element-wise, and zip(*iterables) can
be used to unzip a list of tuples.
Example
print(combined)
print(unzipped_names)
print(unzipped_ages)
Output
Enumerate
The enumerate( ) function provides an index along with the value during iteration.
Example
Output
Person 1: Elayaraj
Person 2: Dhanush
Person 3: Suriya
Introduction to Python Programming
print(sorted_by_length)
Output
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
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
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
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)
Example 2
with open("filename.txt", "r") as file:
content = file.read( )
# Do something with the content
Example
name = "Elayaraj"
age = 20
height = 175.5
formatted_string = "Name: %s, Age: %d, Height: %.2f" % (name, age, height)
print(formatted_string)
Output
In this example:
The values to be substituted for the placeholders are specified after the %
operator in a tuple (name, age, height).
Introduction to Python Programming
%s: String
%f: Floating-point
%x: Hexadecimal
Using str.format( )
name = "Elayaraj"
age = 20
height = 175.5
print(formatted_string)
Output
name = "Elayaraj"
age = 20
height = 175.5
print(formatted_string)
Output
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
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 Python sys module provides access to any command-line arguments via the
sys.argv.
Example 1
import sys
script_name = sys.argv[0]
arguments = sys.argv[1:]
print("Arguments:", arguments)
When running the script with command line arguments like this:
❖ Syntax Errors
❖ Runtime Errors
❖ Logical Errors
❖ Exceptions
Syntax Errors
Syntax errors occur when the code violates the rules of the programming language.
Example
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:
except SomeException as e:
else:
finally:
The try block contains the code that may raise an exception.
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!
Modules
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.
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
You can import specific functions or variables from a module using the from ...
import ... syntax.
Example
# another_script.py
greet("Suriya")
Module Search Path
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/
├── module1.py
└── module2.py
def greet(name):
print(f"Hello, {name}!")
It allows you to structure your code in a more modular and organized way, making it
easier to manage and maintain large projects.
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/
├── module1.py
└── module2.py
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:
Accessing Subpackages
You can access submodules and subpackages using the dot notation.
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.
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
_ _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.
Namespace Packages
This is particularly useful in scenarios where modules are distributed across different
locations.