Class 11 Computer Science – Chapter 2:
Python Programming (Detailed Notes)
1. Introduction to Python
Python is a high-level, general-purpose programming language known for its simplicity and
readability. Created by Guido van Rossum and first released in 1991.
Used in: Web development, AI, data science, automation.
Example:
print("Hello, World!")
2. Setting Up Python
Download Python from https://python.org. Use IDEs like IDLE, PyCharm, or VS Code.
Always select 'Add Python to PATH' during installation.
Verify installation:
python --version
3. Variables and Data Types
Variables store data. Python is dynamically typed.
Types:
- int: 10
- float: 3.14
- str: "Ali"
- bool: True
- complex: 3+2j
4. Definition of 'if' statement
The 'if' statement checks a condition and executes code if it’s True.
Syntax:
if condition:
# code block
5. Operators
Arithmetic: +, -, *, /, %, //
Comparison: ==, !=, >, <
Logical: and, or, not
6. Control Structures – if, loops
if-elif-else makes decisions.
Loops:
- for: Iterates over a sequence.
- while: Runs while a condition is True.
Example:
for i in range(5):
print(i)
7. Definition of 'function'
A function is a reusable block of code defined using 'def'.
Syntax:
def function_name(parameters):
return value
8. Data Structures
List: Mutable → [1,2,3]
Tuple: Immutable → (1,2,3)
Set: Unordered, no duplicates → {1,2}
Dict: Key-value → {"name": "Ali"}
9. Object-Oriented Programming
Classes create user-defined data types.
class Student:
def __init__(self, name):
self.name = name
s1 = Student("Ali")
10. File Handling
Read/Write files using:
open(), read(), write(), with open()
with open("file.txt", "w") as f:
f.write("Hello")
11. Exception Handling
Manage errors using try-except.
try:
x=5/0
except ZeroDivisionError:
print("Error")
12. Testing and Debugging
Use unittest module and print() to debug.
import unittest
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 2, 4)
Self-Test Questions
1. Define a variable with your name.
2. Write a program using an if-else condition.
3. Create a function to calculate square.
4. Write a class for 'Car' with brand and model.
5. Open a file and write 'Hello' to it.
6. Handle divide by zero exception.
7. Create a list of 5 numbers and print the second.
8. Write a for loop from 1 to 10.
9. What is the difference between list and tuple?
10. Explain the role of '__init__' in a class.