📘 Python Revision Tour – II
2️⃣ Lists in Python
What is a List?
A List is a collection of elements stored in ordered form.
Lists are:
✔ Ordered
✔ Mutable (can be changed)
✔ Allow duplicate values
Example:
marks = [85, 90, 78, 92]
Accessing List Elements
Each element has an index number.
Example:
print(marks[0])
Output
85
Negative Indexing
Python allows accessing elements from the end.
Example
print(marks[-1])
Output
92
List Operations
1. Adding Elements
Using append()
marks.append(95)
Using insert()
marks.insert(1,88)
2. Removing Elements
marks.remove(78)
Remove last element
marks.pop()
3. Updating Elements
marks[2] = 80
3️⃣ List Functions
Example:
numbers = [10,20,30]
print(len(numbers))
print(max(numbers))
print(sum(numbers))
4️⃣ Tuples
What is a Tuple?
A Tuple is a collection similar to list but cannot be modified.
It is immutable.
Example:
t = (10,20,30)
Important points:
✔ Ordered
✔ Allows duplicates
✔ Immutable
Accessing Tuple Elements
t = (5,10,15)
print(t[1])
Output
10
Tuple Functions
Example
t=(5,7,9)
print(len(t))
print(max(t))
5️⃣ Dictionaries
Dictionaries
1. Introduction to Dictionary
A Dictionary in Python is a collection of key–value pairs.
Each element has:
key : value
Example:
student = {
"name": "Rahul",
"age": 17,
"marks": 88
}
Here:
Important Points
✔ Dictionary is mutable (can be changed)
✔ Keys must be unique
✔ Values can be duplicate
✔ Keys must be immutable (string, number, tuple)
2. Creating Dictionaries
Method 1: Using Curly Braces
emp = {
"empid":101,
"name":"Amit",
"salary":45000
}
Method 2: Using dict()
student = dict(name="Riya", age=16, marks=90)
3. Accessing Dictionary Elements
Use key name.
print(student["name"])
Output
Riya
Another method:
print(student.get("marks"))
Difference:
4. Adding Elements to Dictionary
student["city"] = "Mumbai"
Dictionary becomes:
{
'name':'Riya',
'age':16,
'marks':90,
'city':'Mumbai'
}
5. Updating Dictionary Values
student["marks"] = 95
6. Deleting Elements
Using del
del student["age"]
Using pop()
student.pop("city")
Remove last item
student.popitem()
7. Dictionary Functions
len()
Returns number of items.
len(student)
keys()
Returns all keys.
student.keys()
Output
dict_keys(['name','age','marks'])
values()
Returns values.
student.values()
items()
Returns both keys and values.
student.items()
Output
('name','Riya')
('age',16)
('marks',90)
8. Traversing a Dictionary
Using for loop
student = {"name":"Riya","age":16,"marks":90}
for i in student:
print(i, student[i])
Output
name Riya
age 16
marks 90
9. Nested Dictionary
Dictionary inside another dictionary.
Example:
students = {
"101":{"name":"Amit","marks":85},
"102":{"name":"Riya","marks":92}
}
Accessing value:
print(students["101"]["name"])
Output
Amit
10. Applications of Dictionary
Used in:
Phone directory
Student database
Word meaning dictionary
Login systems
Example Phone Directory
phone = {
"Amit":9876543210,
"Riya":9876541234
}
6️⃣ Strings in Python
A String is a sequence of characters.
Example:
name = "Python"
String Operations
Concatenation
a="Hello"
b="World"
print(a+b)
Output
HelloWorld
Repetition
print("Hi"*3)
Output
HiHiHi
String Functions
Example:
name="Python"
print(len(name))
print(name.upper())
No 7️⃣ Python Libraries
A library is a collection of pre-written functions.
Example libraries:
Example: math Library
import math
print(math.sqrt(25))
Output
5.0
Example: random Library
import random
print(random.randint(1,10))
Output
Random number between 1 and 10
8️⃣ File Handling (Introduction)
File handling allows Python programs to store data permanently.
Example:
file = open("data.txt","w")
file.write("Hello Python")
file.close()
Modes used:
9️⃣ Sample Programs for Students
Program 1: Find Maximum Number in List
numbers = [10,45,23,67,12]
print("Maximum =",max(numbers))
Program 2: Count Characters in String
text = input("Enter a string:")
print("Length =",len(text))
Program 3: Dictionary Example
student = {"name":"Riya","marks":90}
print(student["marks"])
🔹 1. Functions in Python (Advanced)
📌 Types of Functions
Built-in functions →
len(),sum()User-defined functions
Recursive functions
Anonymous (Lambda) functions
📌 Function Arguments
➤ 1. Required Arguments
def add(a, b):return a + b
➤ 2. Default Arguments
def greet(name="Guest"):print("Hello", name)
➤ 3. Keyword Arguments
add(b=5, a=3)
➤ 4. Variable Length Arguments
def total(*args):return sum(args)
📌 Return Statement
Returns value to caller
Function ends after
return
📌 Recursive Function
A function calling itself:
def factorial(n):if n == 1:return 1return n * factorial(n-1)
📌 Lambda Function
Small anonymous function
square = lambda x: x*x
🔹 2. File Handling in Python
📌 Types of Files
Text file (
.txt)Binary file (
.dat,.bin)
📌 File Modes
Mode Description r Read w Write (overwrite) a Append rb Read binary wb Write binary
📌 Opening & Closing Files
f = open("file.txt", "r")f.close()
📌 Reading File
f.read()f.readline()f.readlines()
📌 Writing File
f.write("Hello")
📌 Append Data
f = open("file.txt", "a")f.write("New Data")
📌 Using with Statement (Best Practice)
with open("file.txt", "r") as f:data = f.read()
🔹 3. Working with Binary Files
📌 Using Pickle Module
Used to store Python objects in binary format
import picklef = open("data.dat", "wb")pickle.dump([1,2,3], f)f.close()
📌 Reading Binary File
f = open("data.dat", "rb")data = pickle.load(f)
🔹 4. Exception Handling
📌 What is Exception?
Runtime error that disrupts program flow
📌 try-except Block
try:x = int(input())except ValueError:print("Invalid input")
📌 Multiple Exceptions
try:passexcept (ValueError, ZeroDivisionError):pass
📌 finally Block
Always executes
finally:print("Done")
📌 else Block
Executes if no exception occurs
🔹 5. Modules in Python
📌 What is Module?
A file containing Python code
📌 Importing Modules
import mathmath.sqrt(25)from math import sqrt
📌 Important Modules
mathrandomdatetime
📌 Creating User Module
# mymodule.pydef add(a,b):return a+b
🔹 6. List Manipulation (Advanced)
📌 List Comprehension
squares = [x*x for x in range(5)]
📌 Nested Lists
matrix = [[1,2],[3,4]]
📌 Common Functions
len(),max(),min(),sum()
🔹 7. String Manipulation (Advanced)
📌 Important Methods
s.find("a")s.replace("a","b")s.split()s.join()
📌 String Formatting
name = "Bhav"print(f"Hello {name}")
🔹 8. Python Libraries (Intro)
Library = collection of modules
Examples:
matplotlib→ graphspandas→ data analysistkinter→ GUI
🔹 9. CSV File Handling
📌 Writing CSV
import csvf = open("data.csv", "w", newline='')writer = csv.writer(f)writer.writerow(["Name", "Age"])
📌 Reading CSV
reader = csv.reader(f)for row in reader:print(row)
🔹 10. MySQL Connectivity (Important for CBSE)
📌 Steps:
Install connector
Connect database
Execute query
import mysql.connectorcon = mysql.connector.connect(host="localhost",user="root",password="1234",database="school")
📌 Execute Query
cursor = con.cursor()cursor.execute("SELECT * FROM student")
📌 Fetch Data
data = cursor.fetchall()
📌 Commit Changes
con.commit()
🔹 11. Important Differences
Concept | Difference |
|---|---|
List vs Tuple | Mutable vs Immutable |
Text vs Binary File | Readable vs Non-readable |
Error vs Exception | Compile vs Runtime |
🧠 Important Viva Questions
What is recursion?
Difference between
read()andreadline()?What is pickle module?
What is exception handling?
Difference between
appendandwrite?What is CSV file?
What is module?
What is MySQL connector?
📌 Conclusion
Python Revision Tour – II strengthens:
File handling
Database connectivity
Error handling
Advanced programming concepts
No comments:
Post a Comment