Python Notes
Python Notes
1. What is Python?
Advantages of Python
1. Simple and easy to learn
Python syntax is very similar to English.
2. Less code
Programs can be written with fewer lines.
3. Readable language
Anyone can easily understand the code.
4. Open source
Free to use.
5. Large community support
6. Used in many fields
Web development
Artificial Intelligence
Machine Learning
Data Science
Automation
Game development
Google
Netflix
Instagram
NASA
3. Features of Python
1. Simple Language
Python syntax is very simple compared to languages like C or Java.
Example:
C program to print Hello World is longer, but Python needs only one line.
Python example:
print("Hello World")
2. Interpreted Language
Python is an interpreted language.
This means:
3. Portable
Windows
Linux
macOS
4. Object-Oriented Language
Python supports Object-Oriented Programming (OOP) concepts like:
Classes
Objects
Inheritance
Polymorphism
Example:
Math operations
Data processing
Web development
Artificial intelligence
4. Applications of Python
Python is used in many real-world applications.
1. Web Development
Example companies:
Google
Tesla
3. Data Science
Libraries used:
NumPy
Pandas
Matplotlib
4. Automation
Sending emails
File handling
Data processing
5. Basic Python Program
Let us see our first Python program.
print("Welcome to Python Programming")
Explanation
print() → Used to display output on the screen.
Output:
Example activity:
Compilation No Yes
8. Summary
Today we learned:
What Python is
Who developed Python
Features of Python
Applications of Python
Simple Python program
Python is one of the best languages for beginners and
engineers because it is simple, powerful, and widely used in industry.
✅ Simple closing line for class:
Example
print("Hello Students")
Output
Hello Students
In Python, even a beginner can understand the program easily because the
syntax is simple and similar to English.
1. Easy to learn
2. Simple syntax
3. Open source
4. Portable
5. Large library support
6. Used in many modern technologies
Google
Netflix
Instagram
3. Python Interpreter
Now let us understand an important concept called the Python Interpreter.
What is an Interpreter?
An interpreter is a program that reads and executes the program code
line by line.
In Python, the interpreter translates Python code into machine language so
that the computer can understand it.
Python does not require a separate compilation step like C or Java.
Example
If we write:
print(5 + 3)
The interpreter reads the statement, performs the addition, and prints the
result.
Output
1. Interactive Mode
2. Script Mode
First, we will learn Interactive Mode.
>>>
This is called the Python prompt.
>>> 10 * 2
20
Here, Python executes each command immediately and displays the result.
5. Summary
Today we learned:
Introduction to Python
Python interpreter
Interactive mode in Python
Python is easy to learn because its interpreter allows programmers
to execute programs quickly and see results immediately.
Ask students:
If you want, I can also give you the next classroom topic explanation:
Python Script Mode
Structure of Python Program
Variables and Data Types in Python
Python Tokens (Identifiers, Keywords, Literals, Operators)
These are usually the next topics after Python Interpreter in 1st year
syllabus.
Values and types: int, float, boolean, string, list, Variables, expressions, statements,
and tuple assignment
What is a Value?
A value is a piece of data stored in memory.
Examples of values:
10
3.14
"Hello"
True
Each value belongs to a specific type.
Example:
print(type(10))
print(type(3.5))
print(type("Python"))
Output
<class 'int'>
<class 'float'>
<class 'str'>
1. Integer (int)
An integer is a whole number without a decimal point.
Examples:
10
-5
0
100
Example program:
a = 10
b = -5
print(a)
print(b)
Counting
Index values
Mathematical calculations
2. Float (float)
A float represents decimal numbers.
Examples:
3.14
5.0
-2.5
Example:
pi = 3.14
temperature = 36.5
print(pi)
print(temperature)
Scientific calculations
Measurements
Engineering values
3. Boolean (bool)
A Boolean type represents logical values.
True
False
Example:
x = True
y = False
print(x)
print(y)
Decision making
Conditions
Comparisons
Example:
print(5 > 3)
Output
True
4. String (str)
A string is a sequence of characters enclosed in quotes.
Examples:
"Python"
"Hello"
"Engineering"
Example program:
name = "Python"
print(name)
Strings are used for:
Text data
Names
Messages
Sentences
5. List
A list is a collection of multiple values stored in square brackets [ ].
Lists are ordered and changeable.
Example:
Output
Example:
Example:
Output
(10, 20)
Tuples are often used when the values should not be modified.
Variables in Python
Now let us understand variables.
What is a Variable?
A variable is a name used to store a value in memory.
Example:
x = 10
name = "Python"
Here
x → variable
10 → value
Example program:
x = 5
y = 10
sum = x + y
print(sum)
Output
15
Valid examples:
name
age
student_name
_marks
Invalid examples:
1name
student name
class
Expressions
An expression is a combination of values, variables, and operators that
produces a result.
Example:
5 + 3
x * 2
a + b
Example program:
x = 5
y = 3
result = x + y
print(result)
Output
Statements
A statement is a complete instruction that Python executes.
Example statements:
x = 10
print(x)
Types of statements:
Assignment statements
Conditional statements
Loop statements
Function statements
Example:
x = 10
print(x)
Here:
x = 10 → assignment statement
print(x) → output statement
Tuple Assignment
Tuple assignment is a powerful feature in Python where multiple
variables can be assigned values in one statement.
Example:
a, b = 5, 10
print(a)
print(b)
Output
5
10
Here:
a = 5
b = 10
Example:
x = 5
y = 10
x, y = y, x
print(x)
print(y)
Output
10
5
This is one of the most useful features of Python.
Summary
Today we learned the following concepts:
If you want, I can also prepare the next topic explanation in teaching
style:
Operators in Python
Input and Output functions
Conditional statements (if, if-else, nested if)
Loops in Python
These are usually the next topics after variables and data types in 1st
year Python syllabus.
Here are 2 simple Python program questions suitable for 1st year
engineering students. You can give these as class exercises or lab
practice.
1. Program to Add Two Numbers
Question:
Write a Python program to read two numbers from the user and display
their sum.
Example:
Input
Output
Sum = 8
Program:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
Example:
Input
a = 5
b = 10
Output
a = 10
b = 5
Program:
a = 5
b = 10
a, b = b, a
print("a =", a)
print("b =", b)
✅ Teaching Tip:
After explaining, ask students:
What is the use of input() function?
Why do we use int()?
How does tuple assignment swap values?
If you want, I can also give 10 very simple Python programs for
beginners that are perfect for 1st year engineering lab and exams.
Precedence of operators,
For example:
result = 10 + 5 * 2
Example:
print(10 + 5 * 2)
Output
20
Explanation:
5 * 2 = 10
10 + 10 = 20
Multiplication happens first because it has higher precedence than
addition.
1 () Parentheses
2 ** Exponent (power)
4 + - Addition, Subtraction
Precedence Operator Description
8 or Logical OR
Example 1
print(5 + 2 * 3)
Step 1:
2 * 3 = 6
Step 2:
5 + 6 = 11
Output
11
Example 2 (Using Parentheses)
Parentheses change the order of execution.
print((5 + 2) * 3)
Step 1:
5 + 2 = 7
Step 2:
7 * 3 = 21
Output
21
So parentheses have the highest precedence.
Example 3
print(10 - 4 / 2)
Step 1
4 / 2 = 2
Step 2
10 - 2 = 8
Output
8
Example 4
print(2 ** 3 * 2)
Step 1
2 ** 3 = 8
Step 2
8 * 2 = 16
Output
16
Exponent (**) has higher precedence than multiplication.
Associativity of Operators
When two operators have the same precedence, Python
follows associativity.
Most operators are evaluated from left to right.
Example:
print(10 - 5 - 2)
Step 1
10 - 5 = 5
Step 2
5 - 2 = 3
Output
result = a + b * c
Output
Result = 20
Summary
Today we learned:
print(8 + 4 * 2)
Answer:
4 * 2 = 8
8 + 8 = 16
If you want, I can also give 3–5 simple exam or lab problems based on
operator precedence, which are very common in 1st year engineering
exams.
comments
Comments in Python
Good morning students.
Example
# This is a comment
print("Hello Python")
Output
Hello Python
Here,
# This is a comment
is ignored by Python.
Example:
x = 10 # storing value 10
print(x)
Output
10
Here,
# storing value 10
Multi-Line Comments
Python does not have a special symbol for multi-line comments, but we can
write them using:
Method 1: Multiple #
# This program
# adds two numbers
# and prints the result
a = 5
b = 3
print(a + b)
"""
This is a multi-line comment
used to explain the program
"""
print("Python Programming")
Output
Python Programming
Triple quotes are also used for documentation strings (docstrings).
a = 5 # first number
b = 10 # second number
sum = a + b # addition
Sum = 15
Summary
Today we learned:
Example:
1. Functions
2. Modules
These concepts help programmers organize programs and reuse code
efficiently.
1. Functions in Python
What is a Function?
A function is a block of code that performs a specific task.
Instead of writing the same code many times, we can write it once inside
a function and reuse it whenever needed.
Example:
Suppose we want to display a greeting message many times.
Instead of writing the same code repeatedly, we can create a function.
Syntax of a Function
def function_name():
statement
Explanation:
greet()
Output
Hello Students
Example 2: Function with Parameters
Functions can accept inputs called parameters.
def add(a, b):
result = a + b
print("Sum =", result)
add(5, 3)
Output
Sum = 8
Here:
a and b → parameters
5 and 3 → arguments
def square(n):
return n * n
result = square(4)
print(result)
Output
16
Advantages of Functions
Functions help in:
2. Modules in Python
Now let us understand modules.
What is a Module?
A module is a file that contains Python functions, variables, and
classes.
Modules help us organize large programs into smaller files.
In simple words:
Example:
A file named
math_operations.py
can contain functions for mathematical operations.
print([Link](16))
Output
4.0
Here:
import math
means we are using the math module.
print([Link](1,10))
Output
Example:
File name:
[Link]
Program:
def greet():
print("Welcome to Python")
import mymodule
[Link]()
Output
Welcome to Python
A block of code that performs a task A file containing functions and code
Function Module
result = multiply(4, 5)
Output
Result = 20
Summary
Today we learned:
What is a function
Defining and calling functions
Functions with parameters and return values
What is a module
Using built-in modules
Creating our own modules
Functions and modules help programmers write organized, reusable, and
efficient programs.
If you want, I can also prepare the next topic explanation in teaching
style:
Math module functions
String operations in Python
Conditional statements (if, if-else, nested if)
Loops (for loop and while loop)
These are usually the next topics after modules and functions in first
year Python syllabus.
function definition and use
1. What is a Function?
A function is a block of code that performs a specific task.
We write the function once, and we can use it many times in the program.
2. Function Definition
Function definition means creating a function.
def
Syntax
def function_name():
statements
Explanation:
Syntax
function_name()
Example:
def greet():
print("Hello Students")
greet()
Output
Hello Students
Here:
message()
message()
message()
Output
Welcome to Python
Welcome to Python
Welcome to Python
Example:
add(5, 3)
Output
Sum = 8
Explanation:
a, b → parameters
5, 3 → arguments
5. Function with Return Value
Sometimes a function returns a value to the program.
Example:
def square(n):
return n * n
result = square(4)
print(result)
Output
16
Here:
Advantages of Functions
Functions provide many benefits:
def cube(n):
return n * n * n
num = 3
result = cube(num)
Output
Cube = 27
Summary
Today we learned:
What is a function
Function definition using def
Function call (using a function)
Functions with parameters
Functions with return values
Functions are very useful because they make programs modular, reusable,
and easy to maintain.
✅ Classroom Practice Questions
1. Write a Python program to create a function that prints "Hello
Engineering Students".
2. Write a Python program to create a function that finds the sum of two
numbers.
If you want, I can also prepare the next topic explanation in teaching
style:
Math module functions
String operations in Python
Conditional statements (if, if-else, nested if)
Loops in Python
These are usually the next topics in 1st year Python syllabus.
flow of execution,
When a Python program runs, the computer executes the program step by
step.
The order in which Python executes the statements in a program is
called the flow of execution.
In simple terms:
print("Start of program")
print("Learning Python")
print("End of program")
Output
Start of program
Learning Python
End of program
Explanation:
Example:
def greet():
print("Hello Students")
print("Program begins")
greet()
print("Program ends")
Output
Program begins
Hello Students
Program ends
Step 1
Python reads the function definition
def greet():
But the function does not execute yet.
It only stores the function for later use.
Step 2
Next line executes:
Program begins
Step 3
Python encounters the function call:
greet()
Now Python jumps to the function definition.
Step 4
The function executes:
Hello Students
Step 5
After the function finishes, Python returns to the next statement.
Step 6
Final statement executes:
Program ends
print("Start")
message()
print("Finish")
Output
Start
Welcome to Python
Finish
Summary
Today we learned:
def show():
print("Python")
print("Hello")
show()
print("Students")
Expected Output
Hello
Python
Students
parameters
Parameters in Python
Good morning students.
Syntax
def function_name(parameter1, parameter2):
statements
Example:
Here:
a and b → parameters
greet("Ravi")
Output
Hello Ravi
Explanation:
name → parameter
Ravi → argument
The parameter receives the value given during the function call.
add(5, 3)
Output
Sum = 8
Explanation:
a = 5
b = 3
Parameters vs Arguments
Students often confuse these two terms.
Parameters Arguments
Example:
Output
24
Output
Name: Arun
Age: 18
Department: CSE
Advantages of Using Parameters
1. Makes functions flexible
2. Allows functions to work with different inputs
3. Reduces code repetition
4. Makes programs more reusable
square(5)
square(7)
Output
Square = 25
Square = 49
Summary
Today we learned:
If you want, I can also prepare the next topic explanation in teaching
style:
Return values in functions
Local and Global variables
Conditional statements in Python
Loops in Python
These are usually the next topics after parameters in functions for 1st
year engineering Python syllabus.
arguments;
Arguments in Python
Good morning students.
In simple terms:
add(5, 3)
Explanation:
Part Meaning
a, b Parameters
5, 3 Arguments
Output
8
Here, the arguments 5 and 3 are passed to the function.
greet("Anu")
Output
Hello Anu
Explanation:
name → parameter
Anu → argument
The argument "Anu" is passed to the parameter name.
1. Positional Arguments
The arguments are passed in the same order as parameters.
Example:
student("Ravi", 19)
Output
Name: Ravi
Age: 19
Here the values are assigned based on position.
2. Keyword Arguments
Arguments are passed using parameter names.
Example:
student(age=19, name="Ravi")
Output
Name: Ravi
Age: 19
Here the order does not matter.
3. Default Arguments
A default value is assigned to a parameter.
Example:
def greet(name="Student"):
print("Hello", name)
greet()
greet("Meena")
Output
Hello Student
Hello Meena
If no argument is given, the default value is used.
Arguments vs Parameters
Parameters Arguments
Example:
multiply(4, 5) # arguments
Output
20
area(5, 4)
Output
Area = 20
Summary
Today we learned:
In simple words:
What is an Algorithm?
An algorithm is a step-by-step procedure used to solve a problem.
It describes how a problem should be solved logically before writing the
program.
Example:
Suppose we want to add two numbers.
Algorithm:
1. Start
2. Read two numbers
3. Add the numbers
4. Display the result
5. Stop
These steps form the algorithm.
1. Input
An algorithm should accept zero or more inputs.
2. Output
It should produce at least one output.
3. Definiteness
Each step must be clear and unambiguous.
4. Finiteness
The algorithm must finish after a finite number of steps.
5. Effectiveness
Steps must be simple and executable.
Steps in Algorithmic Problem Solving
When solving programming problems, we follow these steps:
3. Design an Algorithm
4. Convert to Program
Example Problem
Problem: Find the largest of two numbers.
Algorithm
1. Start
2. Read two numbers A and B
3. If A > B, display A as largest
4. Otherwise display B as largest
5. Stop
Example Problem 2
Problem: Find the area of a rectangle.
Algorithm
1. Start
2. Input length and width
3. Calculate area = length × width
4. Display area
5. Stop
Area = 20
Algorithm vs Program
Algorithm Program
If you want, I can also prepare the next teaching topic, which usually
comes after this in the syllabus:
Debugging
Program testing
Control flow statements (if, if-else)
Loops in Python
These are common next topics in 1st year engineering Python
syllabus.
I need ppt for each and every topic with topic, syntax and example coding
I need ppt for each and every topic with topic, syntax and example coding Create
separate PPT for each unit 1-5
[Link]
👉
[Link]
👉
[Link]
👉
[Link]
👉
[Link]
Definition:
Code development is the process of writing, testing, and improving a
computer program to solve a problem.
In simple words:
For example:
If we want a program to calculate the average marks of students, we
must develop code that performs that task.
Example Problem
Input:
Number1
Number2
Output:
Tell students:
We decide:
Inputs
Processing steps
Outputs
Example:
IPO Model
Example:
Input: 5, 10
Process: 5 + 10
Output: 15
Definition:
Step 1: Start
Step 2: Read number1 and number2
Step 3: sum = number1 + number2
Step 4: Display sum
Step 5: Stop
Explain to students:
Symbol Meaning
Oval Start/Stop
Parallelogram Input/Output
Rectangle Process
Diamond Decision
Start
↓
Input A, B
↓
Sum = A + B
↓
Print Sum
↓
Stop
After designing the algorithm and flowchart, we write the actual program
code using a programming language such as Python or C.
num1 = int(input())
→ Reads the first number from the user.
num2 = int(input())
→ Reads the second number.
sum = num1 + num2
→ Adds the numbers.
print()
→ Displays the result.
Students must understand how to run the program and observe output.
Example Output
Sum = 30
Types of errors:
1. Syntax Error
Wrong grammar of programming language.
Example:
print("Hello"
2. Runtime Error
Occurs while running the program.
Example:
Division by zero.
3. Logical Error
Program runs but gives wrong result.
Example:
Using - instead of +.
Step 8: Documentation
It includes:
Program purpose
Algorithm
Code explanation
Input and output
Step 9: Maintenance
Fix bugs
Add new features
Improve performance
Example:
Updating a student result program to include grade calculation.
Algorithm
Step 1: Start
Step 2: Input length and width
Step 3: area = length × width
Step 4: Display area
Step 5: Stop
Python Code
1. Problem understanding
2. Analysis
3. Algorithm design
4. Flowchart
5. Coding
6. Testing
7. Documentation
8. Maintenance
Example:
If
A = 10
B = 20
After exchange:
A = 20
B = 10
Algorithm
Step 1: Start
Step 2: Read values of A and B
Step 3: Store A in temporary variable Temp
Step 4: Assign B to A
Step 5: Assign Temp to B
Step 6: Display A and B
Step 7: Stop
Explain to students:
A temporary variable is needed to store one value during swapping.
Python Program
# Exchange the values of two variables
temp = a
a = b
b = temp
print("After exchange:")
print("A =", a)
print("B =", b)
Example Output
Enter value of A: 10
Enter value of B: 20
After exchange
A = 20
B = 10
Example:
Before circulation
A = 10
B = 20
C = 30
After circulation
A = 30
B = 10
C = 20
Algorithm
Step 1: Start
Step 2: Read number of elements n
Step 3: Read n values into a list
Step 4: Store last value in temp
Step 5: Shift all values one position to the right
Step 6: Assign temp to first position
Step 7: Display circulated values
Step 8: Stop
Explain:
This process is called circular shifting.
Python Program
# Circulate the values of n variables
values = []
for i in range(n):
num = int(input("Enter value: "))
[Link](num)
temp = values[n-1]
values[0] = temp
Formula:
Example Points:
P1 (x1, y1)
P2 (x2, y2)
Algorithm
Step 1: Start
Step 2: Read x1, y1
Step 3: Read x2, y2
Step 4: Calculate distance using formula
Step 5: Display distance
Step 6: Stop
Python Program
import math
Example Output
Enter x1: 2
Enter y1: 3
Enter x2: 6
Enter y2: 7
Definition:
A conditional statement allows a program to execute different blocks of
code depending on whether a condition is true or false.
In simple words:
2. Real-Life Example
If it rains,
→ take an umbrella
else
→ do not take umbrella
Example 2:
If marks ≥ 50
→ student Pass
else
→ student Fail
1. If Statement
The if statement executes code only when the condition is true.
Syntax
if condition:
statement
Explain:
Example Program
if num > 0:
print("The number is positive")
Example Output
Enter a number: 5
The number is positive
2. If – Else Statement
Sometimes we need two possible actions.
If condition is true → one block executes
If condition is false → another block executes
Syntax
if condition:
statement1
else:
statement2
Example Program
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Explanation
If remainder is 0 → even
Else → odd
Syntax
if condition1:
statement1
elif condition2:
statement2
else:
statement3
Example Program
Example Output
Enter marks: 68
First Class
4. Nested If Statement
A nested if means if statement inside another if statement.
Syntax
if condition1:
if condition2:
statement
Example Program
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
== Equal
!= Not equal
Example:
Correct
if num > 0:
print("Positive")
Wrong
if num > 0:
print("Positive")
Types:
if
if – else
if – elif – else
nested if
1. Boolean Values
First explain the basic idea.
True
False
Example
5 > 3
Result → True
10 < 4
Result → False
Explain to students:
Whenever we compare two values, the result will always be True or False.
2. Boolean Operators
Boolean operators are used to combine or modify conditions.
Operator Meaning
Explanation:
10 > 5 → True
10 < 20 → True
Example 2: OR Operator
x = 5
Explanation:
5 > 10 → False
5 < 10 → True
Explanation:
5 > 10 → False
not False → True
Syntax
if condition:
statement
Example Program
if num > 0:
print("Number is positive")
Explanation:
Syntax
if condition:
statement1
else:
statement2
Example Program
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Explanation:
Syntax
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
statement4
Example Program
Explanation:
The program checks conditions one by one.
If marks ≥ 75 → Distinction
Else if marks ≥ 60 → First Class
Else if marks ≥ 50 → Second Class
Otherwise → Fail
Correct:
if num > 0:
print("Positive")
Incorrect:
if num > 0:
print("Positive")
Important concepts:
If you want, I can also prepare a simple 15-minute lecture flow for
teaching conditionals in class (with board explanation +
examples) which is very useful for first-year engineering teaching.
yes
Here is a simple 15-minute classroom teaching
plan for Conditionals suitable for 1st year engineering students. You
can follow this while teaching on the board or projector.
Ask students:
Explain:
Write on board:
True
False
5 > 3 → True
7 < 2 → False
10 == 10 → True
Explain:
Operator Meaning
Example:
x = 10
Write syntax:
if condition:
statement
Example Program:
if num > 0:
print("Positive number")
Explain:
Write syntax:
if condition:
statement1
else:
statement2
Example:
if num % 2 == 0:
print("Even")
else:
print("Odd")
Syntax:
if condition1:
statement
elif condition2:
statement
else:
statement
Example:
Solution:
if num >= 0:
print("Positive")
else:
print("Negative")
Important concepts:
If you want, I can also give 3 very simple classroom examples that
students understand instantly, such as:
Iteration (Looping)
1. Introduction
Definition:
Iteration is the process of executing a set of instructions repeatedly
until a condition becomes false.
In simple words:
2. Real-Life Example
Explain with daily activities.
Example 1
A teacher asks students to write a sentence 10 times.
Example 2
Counting numbers from 1 to 10.
Example 3
Printing multiplication tables.
1. while loop
2. for loop
1. While Loop
The while loop repeats a block of code as long as the condition is true.
Syntax
while condition:
statement
Example Program
i = 1
while i <= 5:
print(i)
i = i + 1
Step-by-Step Explanation
Initially
i=1
Check condition
1 ≤ 5 → True → Print 1
i becomes 2
2 ≤ 5 → Print 2
i becomes 3 → Print 3
i becomes 4 → Print 4
i becomes 5 → Print 5
i becomes 6
6 ≤ 5 → False → Loop stops
Output
1
2
3
4
5
2. For Loop
The for loop is used when the number of iterations is known in advance.
Syntax
for variable in range(start, stop):
statement
Example Program
for i in range(1,6):
print(i)
Explanation:
Output
1
2
3
4
5
Algorithm
Step 1: Start
Step 2: Read number n
Step 3: Set sum = 0
Step 4: Repeat from 1 to n
Step 5: sum = sum + i
Step 6: Display sum
Step 7: Stop
Python Program
n = int(input("Enter a number: "))
sum = 0
4. Infinite Loop
Explain an important concept.
Example:
while True:
print("Hello")
This is called an infinite loop.
break
Example
for i in range(1,10):
if i == 5:
break
print(i)
Output
1
2
3
4
continue
for i in range(1,6):
if i == 3:
continue
print(i)
Output
1
2
4
5
1. Print numbers 1 to 10
2. Print even numbers from 1 to 20
3. Print multiplication table of a number
4. Find factorial of a number
If you want, I can also prepare a very easy board explanation for
Iteration with diagrams and flowcharts, which makes first-year
students understand loops very quickly.
Iteration
1. Introduction
Example:
Printing numbers 1 to 10 requires repeating the print statement 10 times.
2. State
Before explaining loops, students should understand the concept of state.
Example:
x = 5
Example in iteration:
i = 1
while i <= 5:
print(i)
i = i + 1
1 1
2 2
3 3
4 4
5 5
3. While Loop
The while loop repeats a block of code as long as the condition is true.
Syntax
while condition:
statements
Example Program
while i <= 5:
print(i)
i = i + 1
Output
1
2
3
4
5
Explanation:
The variable i increases each time, changing the state of the program.
4. For Loop
The for loop is used when the number of repetitions is known.
Syntax
for variable in range(start, stop):
statements
Example Program
Print numbers from 1 to 5
for i in range(1,6):
print(i)
5. Break Statement
The break statement is used to terminate the loop immediately, even
if the condition is still true.
Example
for i in range(1,10):
if i == 5:
break
print(i)
Output
1
2
3
4
Explanation:
When i becomes 5, the loop stops.
6. Continue Statement
The continue statement skips the current iteration and moves to the next
iteration.
Example
for i in range(1,6):
if i == 3:
continue
print(i)
Output
1
2
4
5
Explanation:
When i = 3, that iteration is skipped.
7. Pass Statement
The pass statement does nothing.
It acts as a placeholder when a statement is required syntactically but no
action is needed.
Example
for i in range(1,5):
if i == 3:
pass
print(i)
Output
1
2
3
4
Explanation:
for i in range(1,11):
if i == 7:
break
print(i)
Output
1
2
3
4
5
6
Important Points to Tell Students
Iteration concepts include:
Python provides:
while loop
for loop
break
continue
pass
while
for
break
continue
pass
1. Code Development using While Loop
Problem
Algorithm
Step 1: Start
Step 2: Initialize i = 1
Step 3: Check if i ≤ 5
Step 4: Print i
Step 5: Increase i by 1
Step 6: Repeat steps 3–5 until condition becomes false
Step 7: Stop
Python Program
i = 1
while i <= 5:
print(i)
i = i + 1
Output
1
2
3
4
5
Explanation
The while loop keeps executing until the condition becomes false.
Step 1: Start
Step 2: Use loop variable i
Step 3: Generate numbers from 1 to 10
Step 4: Print each number
Step 5: Stop
Python Program
for i in range(1, 11):
print(i)
Output
1
2
3
4
5
6
7
8
9
10
Explanation
Print numbers from 1 to 10, but stop when the number becomes 6.
Algorithm
Step 1: Start
Step 2: Loop from 1 to 10
Step 3: If number equals 6, stop the loop
Step 4: Otherwise print the number
Step 5: Stop
Python Program
for i in range(1, 11):
if i == 6:
break
print(i)
Output
1
2
3
4
5
Explanation
Algorithm
Step 1: Start
Step 2: Loop from 1 to 5
Step 3: If number equals 3, skip that iteration
Step 4: Print remaining numbers
Step 5: Stop
Python Program
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1
2
4
5
Explanation
continue skips the current iteration and continues with the next one.
Algorithm
Step 1: Start
Step 2: Loop from 1 to 5
Step 3: If number equals 3, do nothing
Step 4: Print numbers
Step 5: Stop
Python Program
for i in range(1, 6):
if i == 3:
pass
print(i)
Output
1
2
3
4
5
Explanation
Statement Purpose
Fruitful functions: return values, parameters, local and global scope, function
composition, recursion; Need detail explanation with syntax and coding
1. Fruitful Functions
Introduction
Definition
Example:
2. Return Values
Concept
The return statement sends the result of a function back to the place
where the function was called.
Syntax
def function_name(parameters):
statements
return value
Output
Sum = 30
Explanation
1. Function add() receives values 10 and 20.
2. It calculates sum = 30.
3. return sum sends 30 back to the main program.
3. Parameters
Definition
Parameters are variables listed in the function definition that receive values
when the function is called.
Syntax
def function_name(parameter1, parameter2):
statements
Example
def multiply(x, y):
return x * y
result = multiply(5, 4)
Explanation
x and y → parameters
5 and 4 → arguments
def greet(name="Student"):
print("Hello", name)
greet()
greet("Ravi")
Output
Hello Student
Hello Ravi
4. Local Scope
Definition
A local variable is declared inside a function and can only be used within
that function.
Example
def display():
x = 10
print("Value of x:", x)
display()
5. Global Scope
Definition
Example
x = 50
def show():
print("Value of x:", x)
show()
Output
Value of x: 50
Example:
x = 10
def change():
global x
x = 20
change()
print(x)
Output
20
6. Function Composition
Definition
Example Program
def square(x):
return x * x
result = sum_of_squares(3, 4)
Output
Result = 25
Explanation
square(3) = 9
square(4) = 16
9 + 16 = 25
7. Recursion
Definition
Factorial formula:
n! = n × (n-1)!
Example:
5! = 5 × 4 × 3 × 2 × 1
Program
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
Output
Factorial = 120
Recursion Flow
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 120
Summary for Students
Fruitful functions return values after performing calculations.
Important concepts:
1. Strings in Python
Introduction
Example
name = "Python"
message = 'Hello Students'
Example:
P y t h o n
0 1 2 3 4 5
2. String Indexing
Indexing means accessing a specific character.
Syntax
string[index]
Example
text = "Python"
print(text[0])
print(text[3])
Output
P
h
3. String Slices
Slicing means extracting a part of a string.
Syntax
string[start : end]
Note:
print(text[0:4])
print(text[3:7])
print(text[:5])
print(text[5:])
Output
Prog
gram
Progr
amming
Explanation:
Programming
0123456789
4. String Immutability
Strings in Python are immutable.
Example:
word = "Python"
word[0] = 'J'
This produces an error because strings cannot be modified directly.
Correct method:
word = "Python"
print(new_word)
Output
Jython
5. String Functions
Python provides built-in functions for strings.
len()
text = "Python"
print(len(text))
Output
6
max() and min()
text = "Python"
print(max(text))
print(min(text))
6. String Methods
String methods are functions that operate on strings.
upper()
text = "python"
print([Link]())
Output
PYTHON
lower()
text = "PYTHON"
print([Link]())
Output
python
capitalize()
text = "python programming"
print([Link]())
Output
Python programming
replace()
text = "I like Java"
print([Link]("Java", "Python"))
Output
I like Python
find()
print([Link]("Pro"))
Output
split()
print([Link]())
Output
7. String Module
Python provides a string module containing useful constants and utilities.
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
Output
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
8. Lists as Arrays
Python lists work similar to arrays in other languages.
Example
numbers = [10, 20, 30, 40]
9. List Indexing
Just like strings, lists also use indexing.
Index:
0 1 2 3
Example
numbers = [10, 20, 30, 40]
print(numbers[0])
print(numbers[2])
Output
10
30
print(numbers[1:4])
Output
[Link](40)
print(numbers)
Output
Inserting Elements
[Link](1, 15)
Result
Removing Elements
[Link](20)
Result
[10, 30]
Length of List
numbers = [10, 20, 30]
print(len(numbers))
Output
total = 0
for i in numbers:
total = total + i
Output
Sum = 100
Summary for Students
Strings
Sequence of characters
Support indexing and slicing
Immutable (cannot change directly)
Provide many functions and methods
Lists
Used like arrays
Store multiple values
Support indexing, slicing, and operations
If you want, I can also prepare a very clear classroom explanation for
Lists (stacks, queues, list traversal, searching and sorting) which is
usually the next topic after lists in first-year engineering Python
syllabus.
y=xy=x
Problem
Algorithm
1. Start
2. Read number n
3. Calculate square root using sqrt()
4. Display the result
5. Stop
Python Program
import math
result = [Link](n)
Example Output
Enter a number: 25
Square root = 5.0
2. GCD (Greatest Common Divisor)
The GCD of two numbers is the largest number that divides both
numbers exactly.
Mathematically:
\gcd(a,b)
Problem
Python Program
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
while b != 0:
temp = b
b = a % b
a = temp
print("GCD =", a)
3. Exponentiation
Exponentiation means raising a number to a power.
a^b
Example:
23=2×2×2=823=2×2×2=8
Problem
Algorithm
1. Start
2. Read base a and exponent b
3. Initialize result = 1
4. Repeat multiplication b times
5. Display result
6. Stop
Python Program
a = int(input("Enter base: "))
b = int(input("Enter exponent: "))
result = 1
for i in range(b):
result = result * a
Example array:
Sum = 100
Algorithm
1. Start
2. Initialize list of numbers
3. Set sum = 0
4. Traverse each element in list
5. Add element to sum
6. Display sum
7. Stop
Python Program
numbers = [10, 20, 30, 40]
total = 0
Output
Sum = 100
5. Linear Search
Linear search checks each element sequentially until the element is found.
Problem
Example list
Search key = 20
Algorithm
1. Start
2. Read list and search element
3. Compare element with each item
4. If found → display position
5. If not found → display message
6. Stop
Python Program
numbers = [5, 12, 8, 20, 15]
for i in range(len(numbers)):
if numbers[i] == key:
print("Element found at position", i)
break
else:
print("Element not found")
6. Binary Search
Binary search works only on sorted arrays.
Algorithm
1. Start
2. Initialize low = 0, high = n-1
3. Find middle element
4. If key = middle → found
5. If key < middle → search left half
6. If key > middle → search right half
7. Repeat until found or list ends
8. Stop
Python Program
numbers = [2, 4, 6, 8, 10, 12]
low = 0
high = len(numbers) - 1
if numbers[mid] == key:
print("Element found at position", mid)
break
else:
high = mid - 1
else:
print("Element not found")
Concept Purpose
Lists
1. What is a List?
A List is a collection of items stored in a single variable.
Lists are ordered
Lists are changeable (mutable)
Lists can store different data types
Syntax
list_name = [item1, item2, item3, ...]
Example
numbers = [10, 20, 30, 40]
print(numbers)
Output
[10, 20, 30, 40]
2. List with Different Data Types
0 10
1 20
2 30
3 40
Example
numbers = [10, 20, 30, 40]
print(numbers[0])
print(numbers[2])
Output
10
30
4. Negative Indexing
Python also allows negative indexing.
Index Value
-1 40
-2 30
-3 20
-4 10
print(numbers[-1])
Output
40
numbers[1] = 50
print(numbers)
Output
[10, 50, 30]
6. List Length
We can find the number of elements using len().
numbers = [10, 20, 30, 40]
print(len(numbers))
Output
4
7. Traversing a List
Using for loop
numbers = [10, 20, 30, 40]
for i in numbers:
print(i)
Output
10
20
30
40
[Link](40)
print(numbers)
Output:
[Link](1, 15)
print(numbers)
Output:
[Link](20)
print(numbers)
Output:
[10, 30]
[Link](1)
print(numbers)
Output:
[10, 30]
total = 0
for i in numbers:
total = total + i
Output:
Sum = 100
10. Advantages of Lists
1. Stores multiple values in one variable
2. Dynamic size (can grow or shrink)
3. Supports different data types
4. Easy to traverse using loops
1 Arun
2 Priya
3 Ravi
In Python:
List slicing
List functions
Lists as arrays
List programs for exams
2 mark / 5 mark questions for students.
list operations,
Syntax
list_name[index]
Example
numbers = [10, 20, 30, 40]
print(numbers[0])
print(numbers[2])
Output
10
30
2. List Slicing
Slicing is used to access multiple elements from a list.
Syntax
list_name[start : end]
start → starting index
end → ending index (not included)
Example
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
Output
[20, 30, 40]
Example
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(result)
Output
[1, 2, 3, 4, 5, 6]
4. Repetition (Multiplication)
A list can be repeated multiple times using the * operator.
Example
numbers = [1, 2, 3]
print(numbers * 3)
Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]
5. Membership Operation
Used to check whether an element exists in a list.
Operators:
in
not in
Example
numbers = [10, 20, 30]
print(20 in numbers)
print(50 in numbers)
Output
True
False
6. Updating Elements
Lists are mutable, so we can change values.
Example
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)
Output
[10, 50, 30]
7. Deleting Elements
We can remove elements using del.
Example
numbers = [10, 20, 30, 40]
del numbers[1]
print(numbers)
Output
[10, 30, 40]
8. Finding Length of List
The len() function returns the number of elements.
Example
numbers = [10, 20, 30, 40]
print(len(numbers))
Output
4
Example
numbers = [10, 20, 30, 40]
for i in numbers:
print(i)
Output
10
20
30
40
10. Useful Built-in Functions for Lists
Function Purpose
Example
numbers = [10, 20, 30]
print(max(numbers))
print(min(numbers))
print(sum(numbers))
largest = numbers[0]
for i in numbers:
if i > largest:
largest = i
If you want, I can also give the next topic explanation like classroom
teaching:
List methods (append, extend, insert, remove, pop, sort, reverse)
Lists as arrays
Important list programs for exams
Linear search and binary search using lists.
list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters;
Syntax
list_name[start : end : step]
start → starting index
end → ending index (not included)
step → increment value
Example
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
Output
print(numbers[0:6:2])
Output
Negative Slicing
numbers = [10, 20, 30, 40, 50]
print(numbers[-3:])
Output
2. List Methods
Python provides several built-in list methods.
Method Description
Example
numbers = [10, 20, 30]
[Link](40)
print(numbers)
[Link](1, 15)
print(numbers)
[Link](20)
print(numbers)
Output
for i in numbers:
print(i)
Output
10
20
30
40
Using index
numbers = [10, 20, 30]
for i in range(len(numbers)):
print(numbers[i])
4. Mutability
Lists in Python are mutable.
Mutable means the value of elements can be changed after creation.
Example
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)
Output
Example
list1 = [10, 20, 30]
list2 = list1
list2[1] = 100
print(list1)
print(list2)
Output
6. Cloning Lists
To avoid aliasing, we create a copy of the list.
list2 = list1[:]
list2[1] = 100
print(list1)
print(list2)
Output
[10, 20, 30]
[10, 100, 30]
Example
def print_list(items):
for i in items:
print(i)
print_list(numbers)
Output
10
20
30
Output
60
Summary
Concept Meaning
Tuples
Tuples in Python
1. Introduction to Tuples
A Tuple is a collection of elements stored in a single variable, similar
to a list.
Syntax
tuple_name = (item1, item2, item3, ...)
Example
numbers = (10, 20, 30, 40)
print(numbers)
Output
2. Characteristics of Tuples
1. Ordered collection
2. Immutable (cannot be changed)
3. Allows duplicate values
4. Can store different data types
Example
Output
print(numbers[0])
print(numbers[2])
Output
10
30
4. Negative Indexing
Python allows negative indexing.
Index Value
-1 Last element
Example
print(numbers[-1])
Output
40
5. Tuple Slicing
Slicing extracts a portion of a tuple.
Syntax
tuple[start:end]
Example
print(numbers[1:4])
Output
6. Tuple Operations
Concatenation
Joining two tuples using + operator
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print(t1 + t2)
Output
(1, 2, 3, 4, 5, 6)
Repetition
Repeating tuple elements using *
t = (1, 2)
print(t * 3)
Output
(1, 2, 1, 2, 1, 2)
7. Tuple Methods
Tuples have only two built-in methods because they are immutable.
Method Purpose
Example
print([Link](20))
print([Link](30))
Output
2
2
Example
numbers = (10, 20, 30, 40)
for i in numbers:
print(i)
Output
10
20
30
40
Unpacking
Assigning tuple values to variables.
print(a)
print(b)
print(c)
Output
10
20
30
Symbol [] ()
Mutable Yes No
total = 0
for i in numbers:
total = total + i
Output
Sum = 100
Example:
If you want, I can also explain the next Python topics clearly for
teaching students, such as:
Dictionaries
Strings (slicing, immutability, methods)
Sets
Important Python programs for exams.
tuple assignment,
Syntax
variable1, variable2, variable3 = value1, value2, value3
Example
a, b, c = 10, 20, 30
print(a)
print(b)
print(c)
Output
10
20
30
Here Python automatically creates a tuple (10, 20, 30) and assigns the
values to variables.
Example
data = (1, 2, 3)
x, y, z = data
print(x)
print(y)
print(z)
Output
1
2
3
This process is also called tuple unpacking.
Traditional Method
a = 10
b = 20
temp = a
a = b
b = temp
a, b = b, a
print(a, b)
Output
20 10
(a, b) = (b, a)
Example
numbers = [10, 20]
a, b = numbers
print(a)
print(b)
Output
10
20
Example
pairs = [(1,2), (3,4), (5,6)]
for a, b in pairs:
print(a, b)
Output
1 2
3 4
5 6
print("Quotient:", quotient)
print("Remainder:", remainder)
Output
Quotient: 3
Remainder: 1
Here the function returns two values using a tuple.
Summary
Concept Description
If you want, I can also explain the next topic for Python syllabus teaching:
Dictionaries (very important topic)
Sets in Python
Strings – slicing, immutability, methods
Important Python programs for university exams.
def square(n):
return n * n
But sometimes we need to return multiple results from a function.
In Python, this is done using tuples.
2. Syntax
def function_name():
return value1, value2, value3
Python automatically converts this into a tuple:
(value1, value2, value3)
3. Example Program
Function returning two values
def add_sub(a, b):
add = a + b
sub = a - b
return add, sub
result = add_sub(10, 5)
print(result)
Output
(15, 5)
The returned values are stored as a tuple.
4. Tuple Unpacking
We can also store the returned values in separate variables.
def add_sub(a, b):
add = a + b
sub = a - b
return add, sub
x, y = add_sub(10, 5)
print("Addition:", x)
print("Subtraction:", y)
Output
Addition: 15
Subtraction: 5
This process is called tuple unpacking.
Output
Quotient = 3
Remainder = 2
print("Minimum:", minimum)
print("Maximum:", maximum)
Output
Minimum: 10
Maximum: 67
8. Summary
Concept Explanation
Example:
def test():
return 1, 2, 3
a, b, c = test()
Returned tuple → (1, 2, 3)
If you want, I can also explain the next Python topic clearly for teaching
students:
Dictionaries in Python
Sets in Python
Strings (slicing, immutability, methods)
10 important Python programs asked in exams.
1. Introduction to Dictionaries
A Dictionary in Python is a collection of key–value pairs.
Each key is unique
Each key is associated with a value
Dictionaries are mutable (changeable)
Written using curly braces {}
Syntax
dictionary_name = {key1:value1, key2:value2, key3:value3}
Example
student = {"name":"Arun", "age":20, "course":"CSE"}
print(student)
Output
Example
student = {"name":"Arun", "age":20, "course":"CSE"}
print(student["name"])
print(student["age"])
Output
Arun
20
Example
student = {"name":"Arun", "age":20}
student["course"] = "CSE"
print(student)
Output
Example
student = {"name":"Arun", "age":20}
student["age"] = 21
print(student)
Output
5. Deleting Elements
Using del
student = {"name":"Arun", "age":20, "course":"CSE"}
del student["age"]
print(student)
Output
6. Dictionary Operations
1. Membership Operation
Checks whether a key exists.
student = {"name":"Arun", "age":20}
print("name" in student)
print("course" in student)
Output
True
False
2. Length Operation
print(len(student))
Output
Output
name Arun
age 20
course CSE
1. keys()
student = {"name":"Arun", "age":20}
print([Link]())
Output
dict_keys(['name', 'age'])
2. values()
print([Link]())
Output
dict_values(['Arun', 20])
3. items()
print([Link]())
Output
dict_items([('name','Arun'), ('age',20)])
4. get()
print([Link]("name"))
Output
Arun
5. pop()
[Link]("age")
print(student)
Output
{'name': 'Arun'}
6. update()
student = {"name":"Arun"}
[Link]({"age":20})
print(student)
Output
Output
name : Arun
age : 20
course : CSE
9. Real-Life Example
Dictionary is similar to a phone directory.
Name Phone Number
Ravi 9876543210
Priya 9876541230
In Python:
phone = {
"Ravi":9876543210,
"Priya":9876541230
}
Here:
Name → Key
Phone number → Value
Summary
Concept Explanation
If you want, I can also explain the next Python topic clearly for teaching
students:
Dictionary programs (very important for exams)
Sets in Python
Strings – slicing, immutability, methods
10 important Python programs asked in university exams.
Code Developments: word count, copy file.
Algorithm
1. Read the sentence or text.
2. Split the sentence into words.
3. Create an empty dictionary.
4. For each word:
If the word already exists, increase the count.
Otherwise add it with count = 1.
5. Display the result.
Program
text = input("Enter a sentence: ")
words = [Link]()
word_count = {}
print("Word Frequency:")
Example Output
Enter a sentence: python is easy python is powerful
Word Frequency:
python : 2
is : 2
easy : 1
powerful : 1
Explanation
Step Description
open()
read()
write()
close()
Algorithm
1. Open the source file in read mode.
2. Open the destination file in write mode.
3. Read content from the source file.
4. Write content to the destination file.
5. Close both files.
Program
source = open("[Link]", "r")
data = [Link]()
[Link](data)
[Link]()
[Link]()
Example
If [Link] contains:
Python Programming
File Handling Example
After running the program, [Link] will contain:
Python Programming
File Handling Example
Improved Method (Using with Statement)
This method automatically closes files.
Summary
Program Concept Used
Data types and objects, loading packages, namespaces, reading and writing data,
Simple plotting, Control flow, Debugging, Code profiling
Example
a = 10
b = 3.5
c = "Python"
d = True
print(type(a))
print(type(c))
Output
<class 'int'>
<class 'str'>
Objects
In Python everything is an object.
Example objects:
numbers
strings
lists
dictionaries
functions
Example
x = 5
print(type(x))
Here 5 is an object of type int.
Importing a module
import math
Example
import math
print([Link](16))
Output
4.0
print(sqrt(25))
3. Namespaces
A namespace is a container that stores names of variables and their
values.
It avoids name conflicts.
Types of namespaces:
Type Description
Example
x = 10
def test():
y = 5
print(y)
test()
print(x)
Here:
x → global namespace
y → local namespace
4. Reading and Writing Data (File Handling)
Python can read and write files using open() function.
Syntax
file = open("filename", "mode")
Modes:
Mode Purpose
r Read
w Write
a Append
Reading Data
file = open("[Link]","r")
content = [Link]()
print(content)
[Link]()
Writing Data
file = open("[Link]","w")
[Link]("Hello Python")
[Link]()
5. Simple Plotting
Plotting means displaying data visually using graphs.
Python commonly uses matplotlib.
Example
import [Link] as plt
x = [1,2,3,4]
y = [10,20,25,30]
[Link](x,y)
[Link]("Simple Plot")
[Link]("X values")
[Link]("Y values")
[Link]()
This produces a line graph.
6. Control Flow
Control flow determines how program statements execute.
Main control statements:
Type Example
Example – if statement
x = 10
if x > 5:
print("Greater than 5")
Example – Loop
for i in range(5):
print(i)
Output
0
1
2
3
4
7. Debugging
Debugging means finding and fixing errors in a program.
if x > 5
print(x)
Correct form
if x > 5:
print(x)
Debugging tools:
print() statements
Python debugger (pdb)
IDE debugging tools
8. Code Profiling
Code profiling measures performance of a program.
It helps to know:
Example
import cProfile
def sum_numbers():
total = 0
for i in range(10000):
total = total + i
return total
[Link]("sum_numbers()")
Summary
Topic Explanation
Files and exceptions:
Example:
Example:
File Modes
Mode Meaning
r Read file
a Append data
b Binary mode
Example:
f = open("[Link]", "r")
This opens [Link] for reading.
4. Reading from a File 📖
Method 1: read()
f = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()
Method 2: readline()
f = open("[Link]", "r")
print([Link]())
[Link]()
Method 3: readlines()
f = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
5. Writing to a File ✍️
Using write()
f = open("[Link]", "w")
[Link]("Hello Students")
[Link]()
⚠ If the file exists, old content will be erased.
Appending Data
f = open("[Link]", "a")
[Link]("\nWelcome to Python class")
[Link]()
This adds new data without deleting old data.
6. Closing a File
Syntax:
[Link]()
Example:
f = open("[Link]", "r")
print([Link]())
[Link]()
Closing a file frees system resources.
8. Exceptions in Python ⚠️
What is an Exception?
An exception is an error that occurs during program execution.
Example:
Dividing by zero
File not found
Invalid input
Example error:
print(10/0)
Output:
ZeroDivisionError
9. Exception Handling
Python uses try – except to handle errors.
Syntax:
try:
risky_code
except:
error_handling_code
Example:
try:
a = 10
b = 0
print(a/b)
except:
print("Cannot divide by zero")
Output:
try:
f = open("[Link]", "r")
except FileNotFoundError:
print("File not found")
Used for:
Closing files
Cleaning resources
✅ Summary
Concept Purpose
Common examples:
.txt → [Link]
.csv → [Link]
.py → Python program files
Example uses:
Student records
Log files
Configuration files
Data storage
Basic steps:
Example:
f = open("[Link]", "r")
Here:
4. File Modes
Mode Meaning
r Read file
b Binary mode
Example:
f = open("[Link]", "w")
5. Reading Files 📖
Reading means getting data from a file into a program.
Method 1: read()
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Example output:
Name: Ravi
Marks: 90
Method 2: readline()
Reads one line at a time.
f = open("[Link]", "r")
print([Link]())
print([Link]())
[Link]()
Output:
Name: Ravi
Marks: 90
Method 3: readlines()
Reads all lines and stores them in a list.
f = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
Output:
6. Writing to a File ✍️
Writing means storing data from a program into a file.
Using write()
f = open("[Link]", "w")
[Link]("Welcome to Python Programming")
[Link]()
⚠ Important:
If the file already exists, old content will be erased.
7. Appending Data to File
Append means adding new data without deleting old data.
Example:
f = open("[Link]", "a")
[Link]("\nThis is appended text")
[Link]()
Output in file:
8. Closing a File
After finishing file operations, the file should be closed.
Syntax:
[Link]()
Example:
f = open("[Link]", "r")
print([Link]())
[Link]()
Example:
Output:
Name: Anu
Marks: 95
11. Real-Life Example for Students 🎓
Example: Saving student marks
Ravi 85
Meena 92
Kumar 78
Later the program reads the file to display student results.
✅ Summary
Concept Description
Format operator; command line arguments, errors, and exceptions, questions based
on today’s lesson; clarify final doubts
Syntax
"format string" % values
Output:
Age is 20
%d → integer
Output
Price is 45.750000
Price is 45.75
Output
Hello Anu
%s → string
Multiple Values
name = "Ravi"
marks = 90
print("Student %s scored %d marks" % (name, marks))
Output
[Link]
argv means argument vector
It stores arguments as a list
Example Program
import sys
Output:
Types of errors:
1. Syntax errors
2. Runtime errors (Exceptions)
3. Logical errors
1. Syntax Error
Example:
print("Hello
Error:
SyntaxError
Example:
print(10/0)
Error:
ZeroDivisionError
3. Logical Error
Program runs but gives wrong output.
Example:
a = 5
b = 3
print(a-b) # wrong operation
4. Exceptions
An exception is an error that occurs during program execution.
Examples of exceptions:
ZeroDivisionError
FileNotFoundError
TypeError
ValueError
5. Exception Handling
Python uses try and except to handle exceptions.
Syntax
try:
risky code
except:
handling code
Example
try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print(a/b)
except:
print("Error occurred")
If user enters 0, the program does not crash.
Handling Specific Exceptions
try:
f = open("[Link]")
except FileNotFoundError:
print("File not found")
Programming Questions
1. Write a Python program using format operator to print student name
and marks.
Example:
name = "Meena"
marks = 85
print("Student %s scored %d marks" % (name, marks))
for i in [Link]:
print(i)
Loading from CSV files, Accessing SQL databases, and Cleansing. Read a sample
sales CSV file, display first 5 rows, modify a column, and save it to a new file
df = pd.read_csv("[Link]")
print(df)
3. Modify a Column ✍️
Example: Create a new column Total = Price × Quantity
df["Total"] = df["Price"] * df["Quantity"]
print(df)
MySQL
SQLite
PostgreSQL
conn = [Link]("[Link]")
[Link]()
6. Data Cleansing 🧹
What is Data Cleansing?
It means removing errors or inconsistencies in data.
Common Cleaning Tasks
✔ Remove missing values
✔ Remove duplicates
✔ Fix data types
✔ Filter incorrect values
Example
# Remove missing values
df = [Link]()
# Remove duplicates
df = df.drop_duplicates()
import pandas as pd
Updated Data:
OrderID Product Price Quantity Total
0 101 Pen 10 2 20
1 102 Book 50 1 50
2 103 Pencil 5 10 50
3 104 Eraser 3 5 15
4 105 Notebook 40 2 80
5-Mark
1. Explain how to read and write CSV files using pandas
2. Explain data cleaning techniques
Programming
1. Read a CSV file and print first 3 rows
2. Add a column Discount = Price × 0.1
3. Remove duplicate rows and save file
✅ Final Summary
Topic Key Idea
Examples:
Division by zero
File not found
Invalid input
Basic Syntax
try:
risky_code
except:
handling_code
Example
try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print(a / b)
except:
print("Error occurred")
Handling Specific Exceptions
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
2. Modules in Python 📦
What is a Module?
A module is a file containing Python code (functions, variables).
Example:
math
random
Importing a Module
import math
print([Link](16))
print(sqrt(25))
Use it:
import mymodule
print([Link]("Anu"))
3. Packages in Python 📚
What is a Package?
A package is a collection of modules organized in folders.
Structure:
mypackage/
[Link]
[Link]
Real-Life Example
Think of:
Package → Library 📚
Module → Book 📖
Function → Chapter 📄
4. Introduction to AI 🤖
AI = Artificial Intelligence
Understand language
Analyze data
Make decisions
5. Text Summarization 📝
What is it?
Converting long text into short summary
Real AI Tools
transformers
gensim
6. Sentiment Analysis 😊😡
What is it?
Positive 😊
Negative 😡
Neutral 😐
analysis = TextBlob(text)
print([Link])
Output:
Polarity: Positive
7. Basic Chatbot 🤖
What is a Chatbot?
A program that can talk with users.
if [Link]() == "hello":
print("Bot: Hi!")
elif [Link]() == "how are you":
print("Bot: I am fine")
elif [Link]() == "bye":
print("Bot: Goodbye!")
break
else:
print("Bot: I don't understand")
How it Works
✔ Takes user input
✔ Matches conditions
✔ Gives response
if "good" in user:
print("Positive sentiment")
else:
print("Neutral/Negative")
except Exception as e:
print("Error:", e)
5-Mark Questions
1. Explain exception handling with example
2. Differentiate module and package
3. Explain sentiment analysis
Programming Questions
1. Write a program using try–except
2. Create your own module and use it
3. Write a simple chatbot program
✅ Final Summary
Topic Key Idea
print(clean_name)
Output:
Ravi Kumar
print(clean_text)
Output:
Price 100
Using pandas
import pandas as pd
df["Name"] = df["Name"].[Link]()
3. Normalizing Data ⚖️
What is Normalization?
Making data consistent and uniform.
Types of Normalization
1. Case Normalization
text = "PYTHON programming"
2. Standardizing Values
Example problem:
Solution:
df["Gender"] = df["Gender"].[Link]()
3. Scaling Numbers
4. Date Normalization
df["Date"] = pd.to_datetime(df["Date"])
4. Formatting Data 🧾
What is Formatting?
Changing data into a required structure or display format.
print("%.2f" % price)
Output:
45.68
print("{:.2f}".format(value))
Example 3: f-strings (Modern way)
name = "Ravi"
marks = 95
# Sample data
data = {
"Name": [" Ravi ", "ANU", "kumar "],
"Marks": [85, 90, 78]
}
df = [Link](data)
print(df)
Output:
Name Marks
0 ravi 85.00
1 anu 90.00
2 kumar 78.00
Before cleaning:
After cleaning:
"ravi"
✔ Easier searching
✔ Accurate results
✔ Better analysis
7. Questions for Students 📘
2-Mark Questions
1. What is data normalization?
2. What is data formatting?
3. What is stripping in Python?
5-Mark Questions
1. Explain data cleaning techniques with examples
2. Differentiate normalization and formatting
3. Explain how to remove unwanted data
Programming Questions
1. Remove spaces from a string
2. Convert all names to lowercase
3. Format numbers to 2 decimal places
✅ Final Summary
Topic Purpose
Stripping
Normalization
Formatting
print(clean_name)
✔ Output:
Ravi Kumar
print(clean_text)
✔ Output:
Price 100
3. Normalizing Data ⚖️
Meaning
Making data consistent and uniform.
Before:
Male, male, M
After:
df["Gender"] = df["Gender"].[Link]()
df["Date"] = pd.to_datetime(df["Date"])
4. Formatting Data 🧾
Meaning
Changing data into a proper display format.
✔ Output:
45.68
# Sample data
data = {
"Name": [" Ravi ", "ANU", "kumar "],
"Marks": [85, 90, 78]
}
df = [Link](data)
# 1. Strip spaces
df["Name"] = df["Name"].[Link]()
# 2. Normalize (lowercase)
df["Name"] = df["Name"].[Link]()
# 3. Format numbers
df["Marks"] = df["Marks"].map("{:.2f}".format)
print(df)
✔ Output:
Name Marks
0 ravi 85.00
1 anu 90.00
2 kumar 78.00
6. Real-Life Explanation 🎓
Imagine a student database:
Before cleaning:
After cleaning:
"ravi"
✔ Accurate search
✔ No duplication
✔ Better results
5-Mark
1. Explain data cleaning techniques
2. Differentiate normalization and formatting
3. Explain stripping with examples
Programs
1. Remove spaces from a string
2. Convert names to lowercase
3. Format numbers to 2 decimal places
✅ Final Summary
Step Purpose
Normalize Standardize