Chapter 2: Python Programming – Quick Revision
Notes
1. Introduction to Python Programming
Python is a high-level, interpreted, and easy-to-learn programming language.
Features
• Simple syntax
• Easy to read
• Free and open source
• Platform independent
• Large library support
Example
print("Hello World")
2. Basic Programming Concepts
Program
A set of instructions given to a computer to perform a specific task.
Algorithm
A step-by-step solution to a problem.
Variable
A memory location used to store data.
Data
Raw facts and figures.
3. Development Environment
A development environment is used to write and run Python programs.
1
Examples
• IDLE
• PyCharm
• VS Code
4. Basic Python Syntax
Print Statement
print("Welcome")
Comments
# This is a comment
Comments are used to explain code and are ignored by
Naming Rules
• Must start with a letter or underscore (_)
• Cannot start with a number
• Spaces are not allowed
• Python keywords cannot be used
Valid Names age1
Invalid Names
1name
my age is 98
6. Data Types
Integer
Whole numbers.
a = 10
2
Float
Decimal numbers.
b = 3.5
String
Text enclosed in quotes.
name = "Ali"
Boolean
Represents True or False.
True
False
7. Input and Output
Input
Used to take data from the user.
name = input("Enter name:")
Integer Input
age = int(input("Enter age:"))
Float Input
height = float(input("Enter height:"))
Output
Used to display information.
3
print(name)
8. Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
** Exponent (Power)
// Floor Division
Example
10 % 3 # 1
# Modulus (%) operator remainder return karta hai.
# 10 ko 3 se divide karne par quotient 3 aur remainder 1 aata hai,
# is liye answer 1 hai.
2 ** 3 # 8
# Exponent (**) operator power calculate karta hai.
# 2 ** 3 ka matlab 2 × 2 × 2 = 8.
10 // 3 # 3
# Floor Division (//) operator division ka integer part return karta hai.
# 10 ÷ 3 = 3.33..., lekin decimal part remove kar diya jata hai,
# is liye answer 3 hai.
9. Comparison Operators
Comparison operators are used to compare two values or variables. The result of a comparison is always
either True or False . These operators are commonly used in decision-making statements such as if ,
if-else , and loops.
4
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Examples
5 == 5 # True
10 != 5 # True
8 > 3 # True
2 < 1 # False
7 >= 7 # True
4 <= 2 # False
Example
5 > 3
Result
True
Explanation: Since 5 is greater than 3, Python returns True .
10. Assignment Operators
Assignment operators are used to assign values to variables. They can also perform calculations and update
the variable value at the same time.
Operator Example Meaning
= x=5 Assign 5 to x
+= x += 2 Add 2 to x
-= x -= 2 Subtract 2 from x
5
Operator Example Meaning
*= x *= 2 Multiply x by 2
/= x /= 2 Divide x by 2
Example
x = 5
x += 2
Result
Explanation
Initially, x contains 5. The statement x += 2 means:
x = x + 2
So the new value of x becomes 7.
11. Logical Operators
Logical operators are used to combine multiple conditions and return either True or False .
AND
The and operator returns True only when both conditions are true.
Example:
5 > 3 and 10 > 5
Result:
True
6
OR
The or operator returns True if at least one condition is true.
Example:
5 > 10 or 10 > 5
Result:
True
NOT
The not operator reverses the result.
Example:
not(True)
Result:
False
Example
True and False
Result
False
Explanation: Both conditions must be true for and to return True . Since one condition is false, the
result is False .
12. Expressions
An expression is a combination of variables, values, constants, and operators that produces a result.
7
Example
a + b * c
Explanation
Suppose:
a = 2
b = 3
c = 4
Then:
a + b * c
becomes:
2 + 3 * 4
Python first performs multiplication:
2 + 12
Then addition:
14
So the result is 14.
13. BMI Activity
BMI stands for Body Mass Index. It is used to determine whether a person's weight is healthy according to
their height.
Formula
BMI = Weight / Height²
8
Example
Weight = 60 kg
Height = 1.5 m
BMI = 60 / (1.5 × 1.5)
BMI = 26.67
Program
weight = float(input("Enter weight: "))
height = float(input("Enter height: "))
bmi = weight / (height ** 2)
print("BMI =", bmi)
Explanation
• float() is used because weight and height may contain decimal values.
• height ** 2 means height squared.
• The BMI formula is applied and stored in the variable bmi .
• The result is displayed using print() .
14. Operator Precedence
Operator precedence determines the order in which operations are performed in an expression.
Python follows this order:
1. Parentheses ()
2. Exponent **
3. Multiplication, Division, Modulus
4. Addition, Subtraction
Example
2 + 3 * 4
9
Answer
14
Explanation
Python first performs multiplication:
3 * 4 = 12
Then addition:
2 + 12 = 14
If parentheses are used:
(2 + 3) * 4
Result:
20
15. Control Structures and Decision Making in Python
Control Structures
A control structure is a mechanism that controls the flow of execution in a program. It helps determine the
order in which instructions are executed.
Types of Control Structures
1. Sequence (Statements are executed one after another)
2. Selection (Decision Making)
3. Iteration (Loops)
Decision Making
Decision making means choosing which block of code should execute based on a condition.
10
In Python, decision making is performed using:
• if statement
• if-else statement
• if-elif-else statement
If Statement
An if statement is used to execute a block of code only when a specified condition is true.
if x > 0:
print("Positive")
Explanation
If the value of x is greater than zero, the message "Positive" will be displayed.
If-Else Statement
The if-else statement is used when there are two possible outcomes.
if x > 0:
print("Positive")
else:
print("Negative")
If the condition is true, the code inside the if block is executed; otherwise, the code inside the else
block is executed.
Shorthand If-Else
Python provides a shorter way to write simple if-else statements.
print("Even") if num % 2 == 0 else print("Odd")
This is called the shorthand if-else statement or conditional expression. It allows you to write decision-
making code in a single line.
Example
age = 18
if age >= 18:
11
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
In this example, if the age is 18 or greater, the first message is displayed; otherwise, the second message is
displayed.
The if-else statement is used when there are two possible outcomes.
if x > 0:
print("Positive")
else:
print("Negative")
Explanation
• If the condition is true, the if block executes.
• Otherwise, the else block executes.
Even or Odd Activity
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Explanation
• % gives the remainder.
• If the remainder is 0, the number is even.
• Otherwise, the number is odd.
16. If-Elif-Else Statement
The if-elif-else statement is used when there are multiple conditions.
num = int(input("Enter number: "))
if num > 0:
print("Positive")
12
elif num < 0:
print("Negative")
else:
print("Zero")
Explanation
• If the number is greater than 0, it is positive.
• If the number is less than 0, it is negative.
• If neither condition is true, the number must be zero.
17. While Loop
A while loop repeats a block of code as long as the condition remains true.
i = 1
while i <= 5:
print(i)
i += 1
Explanation
The loop starts from 1 and continues until 5.
Output:
1
2
3
4
5
Activity: Print Even Numbers and Count Odd Numbers
i = 1
odd_count = 0
while i <= 20:
if i % 2 == 0:
print(i)
else:
13
odd_count += 1
i += 1
print("Odd Numbers =", odd_count)
Explanation
• The loop runs from 1 to 20.
• Even numbers are printed.
• Odd numbers are counted using odd_count .
• At the end, the total number of odd numbers is displayed.
Output
Even Numbers:
2 4 6 8 10 12 14 16 18 20
Odd Numbers = 10
18. For Loop
A for loop is used when the number of repetitions is known.
for i in range(1, 6):
print(i)
Explanation
range(1,6) generates numbers from 1 to 5.
Output:
1
2
3
4
5
Activity 1
Print even numbers from 2 to 10.
14
for i in range(2, 11, 2):
print(i)
Explanation
The third value 2 is the step size, so the loop skips every second number.
Output
2 4 6 8 10
Activity 2
Print the first 10 multiples of 3.
for i in range(1, 11):
print(i * 3)
Output
3 6 9 12 15 18 21 24 27 30
Explanation
The loop runs 10 times and multiplies each value by 3.
19. Functions
A function is a reusable block of code that performs a specific task. Functions help reduce repetition and
make programs easier to manage.
Defining a Function
def greet():
print("Hello")
Calling a Function
greet()
15
Output
Hello
Explanation
The function is defined using the def keyword and executed by calling its name.
20. Parameters and Return Value
Parameters allow information to be passed into a function.
def add(a, b):
return a + b
Explanation
• a and b are parameters.
• return sends the result back to the caller.
Example:
result = add(5, 3)
print(result)
Output:
21. Default Parameter
A default parameter has a predefined value that is used if no argument is provided.
def greet(name="Student"):
print("Hello", name)
greet()
16
Output
Hello Student
Explanation
Since no value is passed, Python uses the default value "Student" .
22. Maximum Value Activity
def maximum(numbers):
return max(numbers)
data = [5, 10, 15, 20]
print(maximum(data))
Output
20
Explanation
The built-in max() function finds the largest value in the list.
23. Libraries
Libraries are collections of pre-written code that provide useful functions and tools.
Random Library
Used for generating random values.
import random
Example:
print([Link](1,10))
17
Datetime Library
Used for working with dates and times.
import datetime
Example:
print([Link]())
Statistics Library
Used for statistical calculations.
import statistics
Example:
print([Link]([10,20,30]))
24. Package
A package is a collection of related modules organized in folders.
Example
A package named math_tools may contain:
• [Link]
• [Link]
• [Link]
Packages help organize large programs.
25. List
A list is a built-in data structure used to store multiple values in a single variable.
18
Creating a List
books = ["A", "B", "C"]
Accessing an Item
books[0]
Returns:
Modifying an Item
books[1] = "New Book"
Adding an Item
[Link]("Book")
Removing an Item
[Link]("Book")
Explanation
Lists are mutable, meaning their contents can be changed after creation.
26. Book List Activity
books = ["To Kill a Mockingbird",
"1984",
"The Great Gatsby",
"Pride and Prejudice"]
[Link]("Moby Dick")
books[1] = "Brave New World"
19
[Link]("The Great Gatsby")
other_books = ["War and Peace",
"Hamlet"]
[Link](other_books)
print(books)
Explanation
• append() adds a new book.
• Index 1 is replaced with "Brave New World".
• remove() deletes "The Great Gatsby".
• extend() merges another list.
Final List
['To Kill a Mockingbird',
'Brave New World',
'Pride and Prejudice',
'Moby Dick',
'War and Peace',
'Hamlet']
27. Tuple
A tuple is an immutable collection, meaning its values cannot be changed after creation.
t = (1, 2, 3)
Explanation
Unlike lists, tuples cannot be modified, added to, or deleted from.
28. Indexing
Indexing is used to access individual items in a sequence.
20
a[0]
Accesses the first item.
Negative Index
a[-1]
Accesses the last item.
Explanation
Positive indexing starts from 0, while negative indexing starts from the end.
29. Slicing
Slicing is used to access a range of items.
a[1:4]
Returns items from index 1 to 3.
Explanation
The starting index is included, but the ending index is excluded.
Example:
a = [10,20,30,40,50]
print(a[1:4])
Output:
[20,30,40]
30. Modular Programming
Modular programming means dividing a large program into smaller, manageable modules.
21
Advantages
• Easy maintenance
• Code reusability
• Better organization
• Easier debugging
31. Main Function
def main():
print("Hello")
main()
The main function is often used as the starting point of a program.
Explanation
When the program starts, the main() function is called first and controls the flow of execution.
32. Calculator Module Activity
[Link]
def add(a, b):
return a + b
def subtract(a, b):
return a - b
[Link]
import calculator
print([Link](15, 8))
print([Link](25, 10))
22
Output
23
15
Explanation
The calculator module contains reusable functions. The second file imports and uses those functions.
33. Testing
Testing is the process of checking whether a program works correctly and produces the expected output.
Types of Testing
Unit Testing
Tests individual functions or modules.
Integration Testing
Tests how different modules work together.
Functional Testing
Checks whether the program performs the required tasks.
Regression Testing
Ensures that new changes do not break existing functionality.
34. Debugging
Debugging is the process of finding and fixing errors in a program.
Common Debugging Techniques
Print Statements
Used to display variable values and track program execution.
23
Debugging Tools
Special tools provided by IDEs to inspect code step by step.
Error Messages
Python displays error messages that help identify the cause of problems.
Importance of Debugging
• Removes errors
• Improves program performance
• Ensures correct output
• Makes software more reliable
24