Unit-1
Problem solving statements
1. Types of Statements in Programming
Sequential: Executes step by step.
Decision-Making: Executes based on condition (branching).
Iterative: Executes repeatedly (looping).
Recursive: Function calls itself until base condition is met.
Sequential Statement
Definition:
Statements executed one after another in the order they appear.
Example (Python):
a = 10
b = 20
sum = a + b
print("Sum =", sum)
Decision-Making Statement
Definition:
Statements where the program makes a choice based on a condition (e.g., if, if-else,
switch).
Example (Python):
num = 5
if num % 2 == 0:
print("Even")
else:
print("Odd")
Iterative Statement (Looping)
Definition:
Statements that repeat execution until a condition is met (e.g., for, while).
Example (Python):
for i in range(1, 6):
print(i)
Recursive Statement
Definition:
A function that calls itself to solve a problem by breaking it into smaller
sub-problems.
Example (Python):
#Function definition
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
#main program
print(factorial(5)) # Output: 120
2. Problem Solving steps :
Problem solving using computers follows a systematic approach. The major steps are:
Problem Definition → Understand the problem.
Analysis → Identify inputs, outputs, processing.
Design → Algorithm, flowchart, pseudocode.
Coding → Write program.
Testing/Debugging → Verify correctness.
Documentation → Record details.
Maintenance → Update and improve program.
Problem Definition
Clearly state the problem to be solved.
Identify inputs, outputs, and constraints.
Example: “Calculate the average of 5 student marks.”
Problem Analysis
Break the problem into smaller parts.
Decide what data is required and how it will be processed.
Example: Collect marks → Add them → Divide by number of students.
Designing the Solution
Develop an algorithm (step-by-step procedure).
Represent the algorithm using flowchart or pseudocode.
Example Algorithm:
1. Read 5 marks
2. Add marks
3. Divide by 5
4. Display average
Coding (Implementation)
Translate the algorithm into a programming language (Python, C, Java, etc.).
Example in Python:
marks = [80, 75, 90, 85, 70]
avg = sum(marks) / len(marks)
print("Average =", avg)
Testing and Debugging
Run the program with sample data.
Check if the output is correct.
Identify and fix syntax errors, logical errors, runtime errors.
Documentation
Record the problem statement, algorithm, flowchart, and program details.
Helps others understand, use, and maintain the program.
Maintenance
Update the program when requirements change.
Correct errors discovered during real use.
Ensure the program remains efficient and reliable.
3. Flowchart – 16 Marks Answer
Definition
A flowchart is a diagrammatic representation of an algorithm, process, or
workflow.
They make it easier to understand, analyze, and communicate the steps of a
problem.
Flowchart Symbols
Name of the
Symbol (Picture) Description
Symbol
Terminal
(Oval / Ellipse) Indicates the beginning or end of a process.
(Start/End)
(Rectangle) Process / Represents a step, action, or calculation in
Instruction the process.
Represents a condition or branching point
Decision
(Diamond) (Yes/No, True/False).
Used for data input (e.g., read) or output
Input / Output
(e.g., display).
(Parallelogram)
➝
Flow Line Shows the direction of flow between steps.
(Arrow)
⭕ Connects flow when space is limited or
Connector
(Small Circle) flow continues elsewhere.
Looping It is used to represent for Loop statement
Rules / Guidelines for Drawing Flowcharts
Start and End must be clearly indicated with terminal symbols.
Flow should proceed from top to bottom or left to right.
Use standard symbols consistently.
Arrows must clearly show the direction of flow.
Keep the chart simple, neat, and uncluttered.
Avoid crossing lines; use connectors if necessary.
Each step should be clearly described inside the symbol.
Decisions must have two branches (Yes/No or True/False).
Ensure logical sequence; no missing steps.
Advantages of Flowcharts
Easy to understand and communicate logic.
Useful for debugging and documentation.
Provides a visual overview of the process.
Acts as a blueprint before coding.
Disadvantages of Flowcharts
Time-consuming to draw and update.
Difficult to modify once drawn.
Complexity increases for large problems.
Not suitable for representing detailed program logic.
4. Python Operators – 16 Marks Answer
Arithmetic Operators → Perform mathematical operations.
Relational Operators → Compare values.
Logical Operators → Combine conditions.
Assignment Operators → Assign and update values.
Bitwise Operators → Work on binary bits.
Membership Operators → Check presence in sequence.
Identity Operators → Compare object identity.
1. Arithmetic Operators
Operator Description Example Python Statement Output
+ Addition print(5 + 3) 8
- Subtraction print(10 - 4) 6
* Multiplication print(7 * 2) 14
/ Division print(9 / 2) 4.5
// Floor Division print(9 // 2) 4
% Modulus print(9 % 2) 1
** Exponentiation print(2 ** 3) 8
2. Relational (Comparison) Operators
Operator Description Example Python Statement Output
== Equal to print(5 == 5) True
!= Not equal to print(5 != 3) True
> Greater than print(7 > 4) True
< Less than print(3 < 5) True
>= Greater or equal print(5 >= 5) True
<= Less or equal print(4 <= 6) True
3. Logical Operators
Operator Description Example Python Statement Output
and Logical AND print(5 > 3 and 6 > 2) True
or Logical OR print(5 > 3 or 2 > 6) True
not Logical NOT print(not(5 > 3)) False
4. Assignment Operators
Operator Description Example Python Statement Output
= Assigns value x = 10; print(x) 10
+= Add & assign x = 5; x += 3; print(x) 8
-= Subtract & assign x = 5; x -= 2; print(x) 3
*= Multiply & assign x = 4; x *= 2; print(x) 8
/= Divide & assign x = 9; x /= 3; print(x) 3.0
//= Floor divide & assign x = 9; x //= 2; print(x) 4
%= Modulus & assign x = 9; x %= 2; print(x) 1
**= Exponent & assign x = 2; x **= 3; print(x) 8
5. Bitwise Operators
Operator Description Example Python Statement Output
& Bitwise AND print(5 & 3) 1
` Bitwise OR print(5 | 3) 7
^ Bitwise XOR print(5 ^ 3) 6
~ Bitwise NOT print(~5) -6
<< Left Shift print(5 << 1) 10
>> Right Shift print(5 >> 1) 2
6. Membership Operators
Operator Description Example Python Statement Output
in True if value exists print('a' in 'apple') True
not in True if value not exists print('x' not in 'apple') True
7. Identity Operators
Operator Description Example Python Statement Output
is True if objects are same x = [1,2]; y = x; print(x is y) True
is not True if objects differ x = [1,2]; y = [1,2]; print(x is not y) True
5. Data Types in Python (8m)
Definition
A data type specifies the kind of value a variable can hold and the operations that can
be performed on it.
Python is dynamically typed, meaning you don’t need to declare the type explicitly;
Major Data Types in Python (List)
Numeric Types → int, float, complex
Sequence Types → str, list, tuple
Mapping Type → dict
Set Types → set
Boolean Type → bool
Data Type Description Example of Declaration
Int Integer numbers (positive, negative, zero) x = 10
Float Decimal numbers (real numbers) y = 3.14
Complex numbers with real and imaginary
complex z = 2 + 3j
part
Str Sequence of characters (string) name = "Python"
List Ordered, mutable collection nums = [1, 2, 3]
Tuple Ordered, immutable collection coords = (10, 20)
Dict Key–value pairs (mapping) student = {"name":"John", "age":20}
Set Unordered collection of unique elements colors = {"red", "blue", "green"}
Bool Boolean values (True/False) flag = True
Unit – II
1. Python Conditional Statements
Python supports four main types of conditional statements:
1. Simple if
2. if…else
3. else-if ladder (elif)
4. Nested if
Simple if Statement
o Executes a block of code only if the condition is true.
o If the condition is false, the statement is skipped.
Syntax:
if condition:
true block
next statement
Workflow:
o If the condition is true control goes to true block and then to next statement.
o If the condition is false control goes to next statement directly.
Flowchart
Condition T , True Block
Next statement
Example Program :
num = 10
if num > 5:
print("Number is greater than 5")
Input: num = 10
Output: Number is greater than 5
if…else Statement
Executes one block of code if the condition is true.
Executes another block if the condition is false.
Syntax:
if condition:
true block
else:
false block
next statement
Workflow:
If the condition is true → control goes to true block → then to next statement.
If the condition is false → control goes to false block → then to next statement.
Flowchart:
, False Block F
Condition T , True Block
Next statement
Example Program:
num = 4
if num % 2 == 0:
print("Even")
else:
print("Odd")
Input: num = 4
Output: Even
else…if Ladder (elif)
Used to check multiple conditions sequentially.
Executes the block of the first true condition.
Syntax:
if condition1:
block1
elif condition2:
block2
elif condition3:
block3
else:
else part
next statement
Workflow:
Check condition1 → if true → block1 → next statement
Else check condition2 → if true → block2 → next statement
Else check condition3 → if true → block3 → next statement
Else → default block → next statement
Flowchart:
Example Program:
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Input: marks = 85
Output: Grade B
Nested if Statement
An if statement inside another if.
Used when one condition depends on another.
Syntax:
if condition1:
if condition2:
block A
else:
block B
else:
block C
next statement
Workflow:
Check condition1 → if true → check condition2
o If condition2 is true → block A
o Else → block B
If condition1 is false → block C
Then → next statement
Example Program:
num = 15
if num > 0:
if num % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Non-positive number")
Input: num = 15
Output: Positive Odd
2. While Statement in Python
A while loop is used to repeatedly execute a block of code as long as a condition is
true.
It is a pre-test loop: the condition is checked before each iteration.
Syntax
while condition:
statement(s)
next statement
Workflow
Start → Check condition.
If condition is true → execute loop body → go back to condition check.
If condition is false → exit loop → continue with next statement.
Flowchart Description
Example Program
# Print numbers from 1 to 5 using while loop
num = 1
while num <= 5:
print(num)
num += 1
print("Loop finished")
Sample Input & Output
Input: (no user input, program runs directly)
Output:
1
2
3
4
5
Loop finished
6. For Loop in Python
A for loop is used to iterate over a sequence (like list, tuple, string, or range).
It executes the block of code for each element in the sequence until all elements are
processed.
Syntax
for variable in sequence:
statement(s)
next statement
Workflow
Start → Initialize loop variable from the sequence.
Execute the loop body with the current value.
Move to the next element in the sequence.
Repeat until all elements are processed.
Exit loop → Continue with next statement.
Example Program
# Print first 5 natural numbers using for loop
for num in range(1, 6):
print(num)
print("Loop finished")
Sample Input & Output
Input: (no user input, program runs directly)
Output:
1
2
3
4
5
Loop finished
Great! Let’s walk through your Python for loop examples one by one and show their
outputs clearly.
1. for num in range(5):
for num in range(5):
print(num)
Output:
0
1
2
3
4
2. for num in range(1,5):
for num in range(1,5):
print(num)
Output:
1
2
3
4
3. for num in range(1,10,2):
for num in range(1,10,2):
print(num)
Output:
1
3
5
7
9
4. for num in range(10,1,-1):
for num in range(10,1,-1):
print(num)
Output:
10
9
8
7
6
5
4
3
2
5. for num in 10,11,23:
for num in 10,11,23:
print(num)
Output:
10
11
23
6. Using a List
l = [10,11,23]
for num in l:
print(num)
Output:
10
11
23
7. Using range(len(l))
l = [10,11,23]
for i in range(len(l)):
print(l[i])
Output:
10
11
23
Unit -3
1. Functions in python
Definition
A function is a block of reusable code that performs a specific task.
It helps in modular programming, reduces repetition, and improves readability.
Syntax
def function_name(parameters):
"""optional docstring"""
statement(s)
return value
Description
Functions are defined using the keyword def.
They may take parameters (inputs) and may return a value (output).
Functions can be called multiple times with different arguments.
They improve code reusability, clarity, and maintainability.
Example Program
# Function to calculate square of a number
def square(num):
return num * num
# Calling the function
result = square(5)
print("Square =", result)
Sample Input & Output
Input: num = 5
Output: Square = 25
2. Types of arguments used in python
Positional: Values matched by order.
Keyword: Values matched by parameter name.
Default: Parameters can have default values.
Arbitrary (*args): Variable number of positional arguments.
Positional Arguments
Definition: Values are passed in the same order as parameters are defined.
Program:
def add(a, b):
print("Sum =", a + b)
add(5, 3)
Output:
Sum = 8
Here, 5 is assigned to a and 3 to b by position.
Keyword Arguments
Definition: Values are passed by explicitly naming the parameter.
Program:
def greet(name, message):
print(message, name)
greet(name="Alice", message="Hello")
Output:
Hello Alice
Order doesn’t matter since parameters are matched by name.
Default Arguments
Definition: Parameters can have default values if no value is provided.
Program:
def power(base, exp=2):
print(base ** exp)
power(5) # uses default exp=2
power(5, 3) # overrides default
Output:
25
125
If exp is not passed, it defaults to 2.
Arbitrary Arguments (*args)
Definition: Allows passing a variable number of positional arguments.
Program:
def show_numbers(*args):
for num in args:
print(num)
show_numbers(1, 2, 3, 4)
Output:
1
2
3
4
*args collects all values into a tuple.
3. Types of Functions in Python
Python supports different types of functions based on their usage and definition.
Built-in Functions: Predefined in Python (e.g., print(), len()).
User-Defined Functions: Created by programmer using def.
Recursive Functions: Function calls itself (e.g., factorial).
Lambda Functions: Anonymous, single-line functions using lambda.
1. Built-in Functions
Definition: Functions that are already defined in Python library.
Description: They can be used directly without defining them. Examples include
print(), len(), type(), sum().
Example Program:
numbers = [10, 20, 30]
print("Length =", len(numbers))
print("Sum =", sum(numbers))
Output:
Length = 3
Sum = 60
User-Defined Functions
Definition: Functions created by the programmer to perform specific tasks.
Description: Defined using the def keyword, can take parameters and return values.
Example Program:
def greet(name):
return "Hello " + name
print(greet("Alice"))
Output:
Hello Alice
3. Recursive Functions
Definition: Functions that call themselves within their definition.
Description: Useful for problems that can be broken into smaller sub-problems (e.g.,
factorial, Fibonacci).
Example Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
print("Factorial of 5 =", factorial(5))
Output:
Factorial of 5 = 120
4. Lambda Functions (Anonymous Functions)
Definition: Functions defined without a name using the lambda keyword.
Description: Used for short, simple operations; often passed as arguments to other
functions.
Example Program:
square = lambda x: x * x
print("Square of 6 =", square(6))
Output:
Square of 6 = 36
Unit – 4
1. Strings in Python
A string is a sequence of characters
It is enclosed in single quotes (' '), double quotes (" "), or triple quotes (''' ''' / """ """).
Strings are immutable (cannot be changed after creation).
String Declaration and Assignment
s1 = 'Hello'
s2 = "World"
s3 = '''Python Programming'''
Access using Positive and Negative Index
s = "Python"
print(s[0]) # Positive index → P
print(s[-1]) # Negative index → n
Concatenation
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
Repetition
s = "Hi "
print(s * 3) # Hi Hi Hi
String Slicing
s = "Programming"
print(s[0:6]) # from index 0 to 5
Output:
Progra
String Reverse using Slicing
s = "Python"
print(s[::-1]) #nohtyP
Membership Operator
s = "Python"
print("Py" in s) # True
print("Java" not in s) # True
Built-in Functions
s = "banana"
print(len(s)) #6
print(max(s)) # 'n'
print(min(s)) # 'a'
print(sorted(s)) # ['a','a','a','b','n','n']
print([Link]('a')) # 3
String Special Methods (Tabular Form)
Method Description Example Output
capitalize() Converts first character to uppercase "python".capitalize() Python
Converts first letter of each word to
title() "hello world".title() Hello World
uppercase
swapcase() Swaps case of each character "PyThOn".swapcase() pYtHoN
upper() Converts all characters to uppercase "python".upper() PYTHON
lower() Converts all characters to lowercase "PYTHON".lower() python
lstrip() Removes leading spaces " hello".lstrip() hello
rstrip() Removes trailing spaces "hello ".rstrip() hello
strip() Removes leading & trailing spaces " hello ".strip() hello
replace() Replaces substring with another "hello".replace("h","H") Hello
find() Returns index of substring "banana".find("na") 2
count() Counts occurrences of substring "banana".count("a") 3
2. Lists in Python
Definition
A list is an ordered, mutable collection of items in Python.
Lists can store elements of different data types (integers, strings, floats, etc.).
List Declaration and Assignment
l1 = [10, 20, 30]
l2 = ["apple", "banana", "cherry"]
l3 = [1, "Python", 3.14]
Access using Positive and Negative Index
l = [10, 20, 30, 40]
print(l[0]) # Positive index → 10
print(l[-1]) # Negative index → 40
Concatenation
l1 = [1, 2]
l2 = [3, 4]
print(l1 + l2)
Output:
[1, 2, 3, 4]
Repetition
l = [5, 6]
print(l * 3)
Output:
[5, 6, 5, 6, 5, 6]
List Slicing
l = [10, 20, 30, 40, 50]
print(l[1:4]) # [20, 30, 40]
print(l[::-1]) # Reverse list
Membership Operator
l = [10, 20, 30]
print(20 in l) # True
print(50 not in l) # True
Built-in Functions
l = [3, 1, 4, 1, 5]
print(len(l)) #5
print(max(l)) #5
print(min(l)) #1
print(sorted(l)) # [1, 1, 3, 4, 5]
print([Link](1)) # 2
List Methods (Tabular Form)
Method Description Example Output
append(x) Adds element at end l=[1,2]; [Link](3) [1,2,3]
extend(iter) Adds all elements from another iterable l=[1]; [Link]([2,3]) [1,2,3]
insert(i,x) Inserts element at index i l=[1,3]; [Link](1,2) [1,2,3]
remove(x) Removes first occurrence of element l=[1,2,2]; [Link](2) [1,2]
Removes and returns element at index (default
pop(i) l=[1,2,3]; [Link]() [1,2]
last)
index(x) Returns index of first occurrence l=[10,20]; [Link](20) 1
count(x) Counts occurrences of element l=[1,1,2]; [Link](1) 2
sort() Sorts list ascending l=[3,1,2]; [Link]() [1,2,3]
reverse() Reverses list order l=[1,2,3]; [Link]() [3,2,1]
clear() Removes all elements l=[1,2]; [Link]() []
copy() Returns shallow copy l=[1,2]; m=[Link]() [1,2]
3. Tuples in Python
Definition
A tuple is an ordered collection of elements, similar to a list, but immutable (cannot
be changed after creation).
Tuples are written with parentheses ( ).
Tuple Declaration and Assignment
t1 = (10, 20, 30)
t2 = ("apple", "banana", "cherry")
t3 = (1, "Python", 3.14)
Access using Positive and Negative Index
t = (10, 20, 30, 40)
print(t[0]) # Positive index → 10
print(t[-1]) # Negative index → 40
Concatenation
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2)
Output:
(1, 2, 3, 4)
Repetition
t = (5, 6)
print(t * 3)
Output:
(5, 6, 5, 6, 5, 6)
Tuple Slicing
t = (10, 20, 30, 40, 50)
print(t[1:4]) # (20, 30, 40)
print(t[::-1]) # Reverse tuple
Membership Operator
t = (10, 20, 30)
print(20 in t) # True
print(50 not in t) # True
Built-in Functions
t = (3, 1, 4, 1, 5)
print(len(t)) #5
print(max(t)) #5
print(min(t)) #1
print(sorted(t)) # [1, 1, 3, 4, 5]
print([Link](1)) # 2
print([Link](4)) # 2
Tuple Methods (Tabular Form)
Method Description Example Output
count(x) Counts occurrences of element t=(1,1,2); [Link](1) 2
index(x) Returns index of first occurrence t=(10,20,30); [Link](20) 1
4. Dictionaries in Python
Definition
A dictionary is an unordered collection of key–value pairs in Python.
Keys must be unique and immutable (like strings, numbers, tuples).
Values can be of any data type.
Dictionaries are mutable (can be changed after creation).
Dictionary Declaration and Assignment
d1 = {"name": "Alice", "age": 25, "city": "Coimbatore"}
d2 = dict(id=101, dept="CSE")
Accessing Elements
Access values using keys:
print(d1["name"]) # Alice
print([Link]("age")) # 25
Adding and Updating Elements
d1["email"] = "alice@[Link]" # Add new key–value
d1["age"] = 26 # Update existing value
print(d1)
Output:
{'name': 'Alice', 'age': 26, 'city': 'Coimbatore', 'email': 'alice@[Link]'}
Deleting Elements
del d1["city"] # Delete by key
[Link]("age") # Remove and return value
[Link]() # Remove all items
Membership Operator
d = {"a": 1, "b": 2}
print("a" in d) # True (checks keys)
print("z" not in d) # True
Built-in Functions
d = {"x": 10, "y": 20, "z": 30}
print(len(d)) #3
print(sorted(d)) # ['x', 'y', 'z'] (sorted keys)
print([Link]()) # dict_keys(['x','y','z'])
print([Link]()) # dict_values([10,20,30])
print([Link]()) # dict_items([('x',10),('y',20),('z',30)])
Dictionary Methods (Tabular Form)
Method Description Example Output
get(key) Returns value for key d={"a":1}; [Link]("a") 1
keys() Returns all keys d={"a":1,"b":2}; [Link]() dict_keys(['a','b'])
d={"a":1,"b":2};
values() Returns all values dict_values([1,2])
[Link]()
d={"a":1,"b":2};
items() Returns key–value pairs [('a',1),('b',2)]
[Link]()
d={"a":1};
update() Updates dictionary with another {'a':1,'b':2}
[Link]({"b":2})
d={"a":1,"b":2};
pop(key) Removes key and returns value 1
[Link]("a")
d={"a":1,"b":2};
popitem() Removes last inserted key–value e.g. ('b',2)
[Link]()
clear() Removes all items d={"a":1}; [Link]() {}
copy() Returns shallow copy d={"a":1}; c=[Link]() {'a':1}
Returns value if key exists, else adds d={"a":1};
setdefault() 2
key with default [Link]("b",2)
5. Sets in Python
Definition
A set is an unordered collection of unique elements in Python.
Sets are mutable (can be changed), but they do not allow duplicate values.
Written with curly braces { } or using the set() constructor.
Set Declaration and Assignment
s1 = {10, 20, 30}
s2 = {"apple", "banana", "cherry"}
s3 = set([1, 2, 2, 3]) # duplicates removed
print(s3)
Output:
{1, 2, 3}
Accessing Elements
Sets are unordered, so indexing is not allowed.
Elements can be accessed only by iteration:
s = {10, 20, 30}
for x in s:
print(x)
Membership Operator
s = {10, 20, 30}
print(20 in s) # True
print(50 not in s) # True
Built-in Functions
s = {3, 1, 4, 5}
print(len(s)) #4
print(max(s)) #5
print(min(s)) #1
print(sorted(s)) # [1, 3, 4, 5]
Set Methods (Tabular Form)
Method Description Example Output
union() Returns union of sets {1,2}.union({2,3}) {1,2,3}
intersection() Common elements {1,2}.intersection({2,3}) {2}
Elements in first but not
difference() {1,2,3}.difference({2,3}) {1}
in second
Elements in either but
symmetric_difference() {1,2}.symmetric_difference({2,3}) {1,3}
not both
issubset() Checks if set is subset {1,2}.issubset({1,2,3}) True
Unit – 5
1. Files in Python
Definition
A file is a collection of data stored on a disk.
In Python, files are used to store, retrieve, and manipulate data permanently.
Types of Files
Text Files (.txt):
o Store data in human-readable form (characters).
o Example: "Hello World" stored as plain text.
Binary Files (.bin, .dat, images, audio, video):
o Store data in binary format (0s and 1s).
o Example: images, executables, audio files.
File Opening Modes (Tabular Form)
Mode Description Example
'r' Read (default). Error if file doesn’t exist. open("[Link]","r")
'w' Write. Creates new file or overwrites existing. open("[Link]","w")
'a' Append. Adds data at end of file. open("[Link]","a")
'r+' Read and Write. File must exist. open("[Link]","r+")
'w+' Write and Read. Creates new file or overwrites. open("[Link]","w+")
'a+' Append and Read. Creates file if not exists. open("[Link]","a+")
'rb' Read binary file. open("[Link]","rb")
'wb' Write binary file. open("[Link]","wb")
Open a File – Syntax and Example
# Syntax
file_object = open("filename", "mode")
# Example
f = open("[Link]", "w")
[Link]("Hello, Python File Handling!")
[Link]()
Read Values from a File
(a) read()
Reads entire file or specified number of characters.
f = open("[Link]","r")
print([Link]()) # Reads whole file
[Link]()
(b) readline()
Reads one line at a time.
f = open("[Link]","r")
print([Link]()) # Reads first line
[Link]()
(c) readlines()
Reads all lines into a list.
f = open("[Link]","r")
print([Link]()) # Returns list of lines
[Link]()
Write into a File
(a) write()
Writes a single string.
f = open("[Link]","w")
[Link]("First line\n")
[Link]()
(b) writelines()
Writes a list of strings.
f = open("[Link]","w")
[Link](["Line1\n","Line2\n","Line3\n"])
[Link]()
Close a File
f = open("[Link]","r")
print([Link]())
[Link]()
Always close files after use to free system resources.
Unit – 6
1. Modules in Python
Definition
A module in Python is a file containing Python code (functions, classes, variables).
A user-defined module is a module created by the programmer to organize and reuse
code.
Description
Modules help in modular programming by splitting large programs into smaller,
manageable files.
They improve code reusability, readability, and maintainability.
Python allows importing both built-in modules (like math, os) and user-defined
modules.
How to Define a Module
Create a Python file (e.g., [Link]) and define functions inside it.
# [Link]
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
How to Use a Module (Two Ways)
(a) Using import
import mymodule
print("Addition:", [Link](10, 5))
print("Subtraction:", [Link](10, 5))
(b) Using from ... import
from mymodule import mul, div
print("Multiplication:", mul(10, 5))
print("Division:", div(10, 5))
Example Program: Arithmetic Calculation Using Module
File 1: [Link]
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
File 2: [Link]
import mymodule
x, y = 20, 10
print("Addition:", [Link](x, y))
print("Subtraction:", [Link](x, y))
print("Multiplication:", [Link](x, y))
print("Division:", [Link](x, y))
Output:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2.0
2. Packages in Python
Definition
It is a collection of modules grouped together.
It is a way of organizing related modules into a single directory.
It contains a special file called __init__.py which makes Python treat the directory as
a package.
Packages help in modular programming and code reusability.
Usage
They are used to:
o Group related modules (e.g., arithmetic operations).
o Avoid naming conflicts.
o Improve readability and maintainability.
o Reuse code across multiple projects.
How to Define a Package
1. Create a directory (folder) with the package name.
2. Add an empty file __init__.py inside the folder.
3. Create multiple modules (Python files) inside the folder.
How to Use a Package (Two Ways)
Method 1: import [Link]
Method 2: from [Link] import function
Example Program: Simple Calculator Using Package
Step 1: Create Package Folder → calc_pkg/
Inside calc_pkg, create these files:
(a) __init__.py
# Empty file to mark this directory as a package
(b) [Link]
def add(a, b):
return a + b
(c) [Link]
def sub(a, b):
return a - b
(d) [Link]
def mul(a, b):
return a * b
(e) [Link]
def div(a, b):
return a / b
Step 2: Main Program → [Link]
# Method 1: Importing modules from package
import calc_pkg.add
import calc_pkg.sub
import calc_pkg.mul
import calc_pkg.div
print("Addition:", calc_pkg.[Link](10, 5))
print("Subtraction:", calc_pkg.[Link](10, 5))
print("Multiplication:", calc_pkg.[Link](10, 5))
print("Division:", calc_pkg.[Link](10, 5))
# Method 2: Importing functions directly
from calc_pkg.add import add
from calc_pkg.sub import sub
from calc_pkg.mul import mul
from calc_pkg.div import div
print("Addition:", add(20, 10))
print("Subtraction:", sub(20, 10))
print("Multiplication:", mul(20, 10))
print("Division:", div(20, 10))
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2.0
3. NumPy in Python
Definition
NumPy (Numerical Python) is a powerful open-source library in Python used for
scientific computing.
It provides support for large, multi-dimensional arrays and matrices, along with a
wide collection of mathematical functions to operate on these arrays efficiently.
Description
NumPy is the foundation of data science and machine learning in Python.
It is faster than Python lists because it uses C-based optimized code.
Key features:
o Efficient array operations
o Mathematical, logical, and statistical functions
o Linear algebra, Fourier transforms
o Integration with other libraries (Pandas, SciPy, Matplotlib)
Important Methods in NumPy with Examples
(a) Creating Arrays
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr)
Output:
[1 2 3 4]
(b) Zeros and Ones
import numpy as np
z = [Link]((2,3))
o = [Link]((2,3))
print(z)
print(o)
Output:
[[0. 0. 0.]
[0. 0. 0.]]
[[1. 1. 1.]
[1. 1. 1.]]
(c) Arange and Linspace
import numpy as np
print([Link](1,10,2)) # step of 2
Output:
[1 3 5 7 9]
(d) Reshape
import numpy as np
arr = [Link](6)
reshaped = [Link](2,3)
print(reshaped)
Output:
[[0 1 2]
[3 4 5]]
(e) Mathematical Operations
import numpy as np
arr = [Link]([10,20,30])
print(arr + 5) # Add scalar
print(arr * 2) # Multiply scalar
Output:
[15 25 35]
[20 40 60]
(f) Aggregate Functions
import numpy as np
arr = [Link]([1,2,3,4,5])
print([Link](arr))
print([Link](arr))
print([Link](arr))
print([Link](arr))
Output:
15
3.0
5
1
(g) Indexing and Slicing
import numpy as np
arr = [Link]([10,20,30,40,50])
print(arr[0]) # First element
print(arr[-1]) # Last element
print(arr[1:4]) # Slice
Output:
10
50
[20 30 40]
(h) Matrix Operations in NumPy
1. Matrix Addition,Subtraction,multiplication and Transpose
import numpy as np
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print("Addition:\n", A + B)
print("Subtraction:\n", A - B)
print("Multiplication:\n", [Link](A, B))
print("Transpose:\n", A.T)
Output:
Addition:
[[ 6 8]
[10 12]]
Subtraction:
[[-4 -4]
[-4 -4]]
Multiplication:
[[19 22]
[43 50]]
Transpose:
[[1 3]
[2 4]]
4. SciPy in Python
Definition
SciPy stands for Scientific Python.
It is an open-source library that extends NumPy by adding advanced mathematical
algorithms and functions.
Used widely in engineering, data science, and scientific computing.
Description
Built on top of NumPy arrays for efficiency.
Provides specialized modules for:
o Integration ([Link])
o Optimization ([Link])
o Interpolation ([Link])
o Linear Algebra ([Link])
o Statistics ([Link])
o Signal/Image Processing ([Link], [Link])
Important Methods with Examples
(a) Integration
from scipy import integrate
import numpy as np
f = lambda x: x**2
result, _ = [Link](f, 0, 3)
print("Integration:", result)
Output:
Integration: 9.0
(b) Linear Algebra
from scipy import linalg
import numpy as np
A = [Link]([[1,2],[3,4]])
det = [Link](A)
print("Determinant:", det)
Output:
Determinant: -2.0
(c) Statistics
from scipy import stats
data = [2,4,4,4,5,5,7,9]
print("Mean:", [Link](data))
print("Mode:", [Link](data).mode[0])
Output:
Mean: 5.0
Mode: 4
(d) Solve simultaneous equations
The module [Link] provides the function solve() to handle systems of linear equations
of the form:
Ax = b
where A is the coefficient matrix and b is the constants vector.
Let us consider the following equations:
2x + y = 5
x-y=1
Program:
import numpy as np
from scipy import linalg
A = [Link]([[2, 1],
[1, -1]])
b = [Link]([5, 1])
x = [Link](A, b)
print("Solution:", x)
Output:
Solution: [2. 1.]
So, (x = 2, y = 1).
5. Pandas in Python
Definition
Pandas is an open-source Python library used for data analysis and manipulation.
It provides two main data structures:
o Series → one-dimensional labeled array.
o DataFrame → two-dimensional labeled data structure (like a table in Excel).
Description
Built on top of NumPy for fast performance.
Used for loading, cleaning, analyzing, and visualizing data.
Provides powerful tools for:
o Handling missing data
o Filtering, grouping, merging, and joining datasets
o Statistical analysis
o Input/Output with CSV, Excel, SQL, JSON, etc.
Important Methods with Examples
(a) Creating Series
import pandas as pd
s = [Link]([10, 20, 30], index=['a','b','c'])
print(s)
Output:
a 10
b 20
c 30
dtype: int64
(b) Creating DataFrame
import pandas as pd
data = {'Name':['Alice','Bob','Charlie'],
'Age':[25,30,35]}
df = [Link](data)
print(df)
Output:
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
(c) Head and Tail
print([Link](2)) # First 2 rows
print([Link](1)) # Last row
(d) Indexing and Slicing
print(df['Name']) # Column selection
print([Link][0]) # Row by index
print([Link][1,'Age']) # Specific cell
(e) Adding New Column
df['Salary'] = [50000,60000,70000]
print(df)
(f) Dropping Column/Row
df = [Link]('Salary', axis=1) # Drop column
df = [Link](0, axis=0) # Drop row
(g) Descriptive Statistics
print([Link]())
Output (summary statistics):
Age
count 2.000000
mean 32.500000
std 3.535534
min 30.000000
max 35.000000
(h) Handling Missing Data
df2 = [Link]({'A':[1,2,None], 'B':[4,None,6]})
print([Link](0)) # Replace NaN with 0
print([Link]()) # Drop rows with NaN
(i) GroupBy
data = {'Dept':['CSE','CSE','ECE'],
'Marks':[85,90,88]}
df = [Link](data)
print([Link]('Dept')['Marks'].mean())
Output:
Dept
CSE 87.5
ECE 88.0
Name: Marks, dtype: float64
(j) Reading/Writing Files
df.to_csv("[Link]", index=False) # Write to CSV
df2 = pd.read_csv("[Link]") # Read from CSV
print(df2)
4. Tabular Chart of Pandas Methods
Method Description Example Output
Series() Creates 1D labeled array [Link]([1,2,3]) [1,2,3]
DataFrame() Creates 2D table [Link]({'A':[1,2]}) Table
head() First n rows [Link](2) First 2 rows
tail() Last n rows [Link](1) Last row
iloc[] Index-based selection [Link][0] First row
loc[] Label-based selection [Link][1,'Age'] Value at row 1, col Age
drop() Removes row/column [Link]('Age',axis=1) Removes Age column
describe() Summary statistics [Link]() Mean, std, min, max
fillna() Replace missing values [Link](0) NaN → 0
dropna() Remove missing values [Link]() Removes NaN rows
groupby() Group data and aggregate [Link]('Dept').mean() Mean per group
to_csv() Save DataFrame to CSV df.to_csv("[Link]") File created
read_csv() Load CSV file pd.read_csv("[Link]") DataFrame
6. Scikit-learn in Python
Definition
Scikit-learn is an open-source machine learning library in Python.
It simplifies the implementation of ML algorithms for predictive data analysis and
data mining.
Description
Built on NumPy, SciPy, and Matplotlib for efficiency.
Provides a consistent API for supervised and unsupervised learning.
Common uses:
o Classification (predict categories)
o Regression (predict continuous values)
o Clustering (group similar data)
o Dimensionality Reduction (reduce features)
o Model Selection (cross-validation, hyperparameter tuning)
o Preprocessing (scaling, encoding, normalization)
Important Methods with Examples
(a) Regression (Linear Regression)
from sklearn.linear_model import LinearRegression
import numpy as np
X = [Link]([[1],[2],[3],[4]])
y = [Link]([2,4,6,8])
model = LinearRegression()
[Link](X,y)
print("Prediction for 5:", [Link]([[5]]))
(b) Clustering (KMeans)
from [Link] import KMeans
import numpy as np
X = [Link]([[1,2],[1,4],[1,0],[10,2],[10,4],[10,0]])
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
print("Cluster centers:", kmeans.cluster_centers_)
print("Labels:", kmeans.labels_)
Output:
Cluster centers: [[ 1. 2.]
[10. 2.]]
Labels: [0 0 0 1 1 1]
(c) Classification (Logistic Regression)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from [Link] import load_iris
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LogisticRegression(max_iter=200)
[Link](X_train, y_train)
print("Accuracy:", [Link](X_test, y_test))
Output (approx):
Accuracy: 0.93
Output:
Prediction for 5: [10.]
(d) Dimensionality Reduction (PCA)
from [Link] import PCA
from [Link] import load_iris
X, y = load_iris(return_X_y=True)
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print("Reduced shape:", X_reduced.shape)
Output:
Reduced shape: (150, 2)
(e) Preprocessing (StandardScaler)
from [Link] import StandardScaler
import numpy as np
X = [Link]([[1,2],[3,4],[5,6]])
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print(X_scaled)
Output (approx):
[[-1.2247 -1.2247]
[ 0. 0. ]
[ 1.2247 1.2247]]
4. Tabular Chart of Scikit-learn Methods
Method Description Example Output
LogisticRegression() Classification Fit on Iris dataset Accuracy ≈ 0.93
LinearRegression() Regression Predict y for X=5 10
KMeans() Clustering Cluster 2 groups Centers [[1,2],[10,2]]
PCA() Dimensionality reduction Reduce Iris features Shape (150,2)
StandardScaler() Preprocessing Scale features Normalized values
train_test_split() Splits dataset 80% train, 20% test Train/Test sets
[Link]() Train model Fit classifier Model trained
[Link]() Predict values Predict new data Output labels/values
[Link]() Evaluate accuracy Test set Accuracy %