Python Note
Python Note
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
TRAINER GUIDE
LISTS
• List values
• Create, Accessing elements
• List length, membership
• List & for loops
• List operations
• List slices [Start:end]
• List deletion
• Object & values
• Passing list to a function
• Cloning lists
• Nested list
G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
TRAINER GUIDE
STRING MANIPULATION
• Built-in string functions
• Pattern Searching
• Replacing and removing substrings
• Working with Slice Operator
• Applying Slice Operatorsin Lists and Tuples
FUNCTIONS
• Introduction to Functions
• Parameters& argumentsin a function
❖ Arguments
❖ Positional arguments
❖ Arguments with default values
• Function with return values
• Lambda Keyword
• Custom Libraries
• Custom Packages
EXCEPTIONS
• Introduction
• Try .. Except Blocks
• Try .. Except .. Else Blocks
• Try .. Except .. Finally Blocks
• Multiple Exception Handlers
• Nested Exception Handlers
• Raising Exceptions
FILES MANIPULATION
• Introduction
• Writing & Reading Text Files
• Writing & Reading Data Files
• Writing and Reading objectsinto binary files using pickle
• Directory Manipulation
1. Machine Language
2. Assembly Language
• A step above machine language, using short codes (mnemonics) instead of binary.
• Needs an assembler to convert into machine language.
• Easier to read than machine language but still complex.
• Example: MOV A, B (Moves data from B to A).
3. High-Level Language
• Designed to be human-friendly.
• Uses simple syntax (English-like words).
• Needs a compiler or interpreter to convert it into machine code.
• Examples: Python, Java, C++, JavaScript.
Features of Python
• Simple & Readable: Uses English-like syntax.
• Interpreted: Executes line by line.
• Portable: Runs on different operating systems (Windows, Mac, Linux).
• Object-Oriented: Supports object-based programming.
• Huge Libraries: Many pre-built modules for different tasks (e.g., math, web development, AI).
Applications of Python
• Web Development: Django, Flask frameworks.
• Data Science & AI: Used in machine learning and data analysis (Pandas, NumPy, TensorFlow).
• Automation & Scripting: Automates repetitive tasks.
• Game Development: Used in creating games (Pygame).
• Cybersecurity: Ethical hacking and penetration testing.
Example:
python
CopyEdit
print("Welcome to Python Programming!")
Output:
css
CopyEdit
Welcome to Python Programming!
Python is case-sensitive, meaning Print("Hello") will give an error, while print("Hello") works.
Example:
python
CopyEdit
# This is a comment using special characters like # and "
print("Python supports special characters like @, #, &, %")
Output:
nginx
CopyEdit
Python supports special characters like @, #, &, %
3. Tokens in Python
Tokens are the smallest building blocks of a Python program.
Types of Tokens:
1. Keywords (reserved words): if, else, while, for, break, return, True, False
2. Identifiers (variable & function names): name, age, sum1
3. Literals (constant values): 123, "hello", 3.14
4. Operators (+ - * / == != > <)
5. Punctuators (brackets {}, [], (), ,, :)
Example:
python
CopyEdit
if True:
print("Tokens are important!")
Output:
sql
CopyEdit
Tokens are important!
Example:
python
CopyEdit
print(type(10)) # int
print(type(3.14)) # float
print(type(2 + 3j)) # complex
print(type(True)) # bool
print(type("Hello")) # str
Output:
kotlin
CopyEdit
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'str'>
5. Variables in Python
A variable is a container for storing values.
Example:
python
CopyEdit
name = "Alice"
age = 25
PI = 3.14
Output:
nginx
CopyEdit
Alice 25 3.14
python
CopyEdit
# Valid variable names
my_name = "Bob"
_age = 30
score1 = 95
Example:
python
CopyEdit
num1 = 10
num2 = 3.5
num3 = 2 + 4j
flag = True
text = "Python"
Output:
kotlin
CopyEdit
<class 'int'> <class 'float'> <class 'complex'> <class 'bool'> <class 'str'>
Example:
python
CopyEdit
a = 10
b = 3.5
c = "15"
Example:
python
CopyEdit
x, y, z = 10, 20, 30
print(x, y, z)
Output:
CopyEdit
10 20 30
python
CopyEdit
a = b = c = 100
print(a, b, c)
Output:
CopyEdit
100 100 100
Example:
python
CopyEdit
name = input("Enter your name: ")
print("Hello,", name)
CopyEdit
Hello, John
Example:
python
CopyEdit
age = 25
print("Your age is:", age)
Output:
csharp
CopyEdit
Your age is: 25
python
CopyEdit
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
pgsql
CopyEdit
My name is Alice and I am 25 years old.
python
CopyEdit
name = "Bob"
salary = 5000.50
print(f"{name} earns ${salary:.2f} per month.")
Output:
nginx
CopyEdit
Bob earns $5000.50 per month.
1. Write a program to input your name and age and print them.
2. Convert an integer to float and print it.
3. Swap two variables without using a third variable.
4. Print "The sum of 10 and 5 is: 15" using format().
Example:
python
CopyEdit
a = 10
b = 5
sum_value = a + b # '+' is the operator, 'a' & 'b' are operands
print(sum_value)
Output:
CopyEdit
15
3. Arithmetic Operators
Used to perform mathematical operations.
python
CopyEdit
x = 5
print(-x) # Unary operator (-) changes sign → Output: -5
a, b = 10, 3
print(a + b) # Binary operator → Output: 13
4. Comparison Operators
Used to compare two values and return True or False.
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Example:
python
CopyEdit
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
5. Logical Operators
Used to combine multiple conditions.
Example:
python
CopyEdit
x, y = 10, 20
6. Membership Operators
Used to check if a value is present in a sequence (list, string, tuple, etc.).
Operator Meaning
in Returns True if value is found
not in Returns True if value is NOT found
Example:
python
CopyEdit
text = "Python is fun"
print("Python" in text) # True
print("Java" not in text) # True
python
CopyEdit
numbers = [1, 2, 3, 4, 5]
Exercise Questions
A Boolean expression is an expression that evaluates to True or False. It is used in decision-making and
loops to control program flow.
Example:
python
CopyEdit
a = 10
b = 20
print(a < b) # True
print(a == b) # False
Output:
graphql
CopyEdit
True
False
(a) if Statement
Example:
python
CopyEdit
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
css
CopyEdit
You are eligible to vote.
Example:
python
CopyEdit
num = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
typescript
CopyEdit
Even number
Example:
python
CopyEdit
num = 10
if num > 0:
print("Positive number")
if num % 2 == 0:
print("Even number")
Output:
typescript
CopyEdit
Positive number
Even number
Example:
python
CopyEdit
marks = 85
makefile
CopyEdit
Grade: B
• When you need to choose one option from many (e.g., assigning grades).
Example:
python
CopyEdit
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Output:
nginx
CopyEdit
Adult
4. Loops in Python
Loops allow repeating a block of code multiple times, saving time and effort.
Example:
python
CopyEdit
count = 1
while count <= 5:
print("Count:", count)
count += 1
Output:
makefile
CopyEdit
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
• When we don't know the number of iterations in advance (e.g., waiting for user input).
5. break Statement
Used to exit a loop immediately.
Example:
python
CopyEdit
num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1
Output:
CopyEdit
1
2
3
4
• To stop loops when a certain condition is met (e.g., stopping search after finding an item).
6. continue Statement
Skips the current iteration and continues the loop.
Example:
python
CopyEdit
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)
Output:
CopyEdit
1
2
4
5
7. Nested Loops
A loop inside another loop.
Example:
python
CopyEdit
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"({i}, {j})", end=" ")
print()
Output:
scss
CopyEdit
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
8. for Loop
A for loop repeats a block a fixed number of times.
Example:
python
CopyEdit
for i in range(1, 6):
print("Iteration:", i)
Output:
makefile
CopyEdit
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
9. range() Function
The range() function is used in for loops to generate sequences.
Syntax:
python
CopyEdit
range(start, stop, step)
Example:
python
CopyEdit
for i in range(1, 10, 2):
print(i, end=" ")
Output:
CopyEdit
1 3 5 7 9
Summary
✅ Decision-making (if, if-else, if-elif-else) controls which part of the code runs.
✅ Loops (while, for) help repeat tasks efficiently.
✅ Control statements (break, continue) modify loop behavior.
✅ range() helps control loop sequences.
Practice Questions
1. What is a List?
A list is an ordered, mutable collection of elements that can hold items of different data types, such as
numbers, strings, or even other lists.
Example of a List
python
CopyEdit
fruits = ["apple", "banana", "cherry", "date"]
print(fruits)
Output:
css
CopyEdit
['apple', 'banana', 'cherry', 'date']
2. Creating a List
Lists are created using square brackets [ ].
# List of strings
names = ["Alice", "Bob", "Charlie"]
# Empty list
empty_list = []
Indexing in Lists
List Elements A B C D E
Index Numbers 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
Examples
python
CopyEdit
letters = ["A", "B", "C", "D", "E"]
Examples
python
CopyEdit
colors = ["red", "blue", "green"]
# List length
print(len(colors)) # Output: 3
# Membership check
print("blue" in colors) # Output: True
print("yellow" in colors) # Output: False
nginx
CopyEdit
apple
banana
cherry
6. List Operations
Python supports various operations on lists.
Examples
python
CopyEdit
list1 = [1, 2, 3]
list2 = [4, 5]
# Concatenation
print(list1 + list2) # [1, 2, 3, 4, 5]
# Repetition
print(["Hello"] * 3) # ['Hello', 'Hello', 'Hello']
# Membership
print(3 in list1) # True
Syntax
python
CopyEdit
list[start:end] # Includes 'start' but excludes 'end'
Examples
python
CopyEdit
numbers = [10, 20, 30, 40, 50]
Examples
python
CopyEdit
numbers = [10, 20, 30, 40, 50]
list2.append(4)
print(list1) # [1, 2, 3, 4] (list1 is also affected!)
Example
python
CopyEdit
def modify_list(lst):
lst.append("New Item")
# Using slicing
copy1 = original[:]
copy1.append(4)
print(original) # [1, 2, 3] (original remains unchanged)
Example
python
CopyEdit
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing elements
print(matrix[0]) # [1, 2, 3]
print(matrix[1][2]) # 6
Summary
✅ Lists are ordered, mutable collections that allow storage of multiple values.
✅ You can access, modify, and delete elements efficiently.
✅ Lists support loops, slicing, copying, and nesting.
✅ They are commonly used in data processing, sorting, and dynamic storage.
Practice Questions
1. Create a list of your favorite movies and print each one.
2. Write a program to find the largest number in a list.
3. Use list slicing to print the first 3 elements of a list.
4. Implement a nested list to store students' names and their scores.
A tuple is an ordered, immutable collection of elements in Python. It is similar to a list, but cannot be
modified after creation.
Tuples are created using parentheses () or simply by separating values with commas.
python
CopyEdit
# Creating Tuples
empty_tuple = () # Empty tuple
single_element_tuple = (5,) # Note the comma (without it, it's just an integer)
numbers = (10, 20, 30, 40)
mixed_tuple = (1, "hello", 3.14, True)
python
CopyEdit
# Assigning values using a tuple
(a, b, c) = (10, 20, 30)
print(a) # 10
print(b) # 20
print(c) # 30
python
CopyEdit
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # apple
print(fruits[-1]) # cherry
# Concatenation
print(tuple1 + tuple2) # (1, 2, 3, 4, 5)
# Repetition
print(("Python",) * 3) # ('Python', 'Python', 'Python')
# Membership Test
print(2 in tuple1) # True
python
CopyEdit
t = (1, 2, 3)
# t[0] = 10 # ❌ TypeError: 'tuple' object does not support item assignment
print(name) # John
print(age) # 25
print(job) # Developer
python
CopyEdit
# Creating Sets
empty_set = set() # Empty set
numbers = {1, 2, 3, 4, 5}
mixed_set = {1, "hello", 3.14}
print(numbers) # {1, 2, 3, 4, 5}
# Union
print(A | B) # {1, 2, 3, 4}
# Intersection
print(A & B) # {2, 3}
# Difference
print(A - B) # {1}
# Symmetric Difference
print(A ^ B) # {1, 4}
# Add an element
fruits.add("mango")
# Remove an element
fruits.remove("banana")
python
CopyEdit
# Creating a Dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person)
python
CopyEdit
print(person["name"]) # Alice
print(person.get("age")) # 25
print(person)
# Using pop()
age = person.pop("age")
# Clearing dictionary
person.clear()
Summary
Tuples
Sets
Dictionaries
Practice Questions
1. Create a tuple with 5 elements and access the 3rd element.
2. Write a program to find common elements in two sets.
3. Create a dictionary of student names and marks, then print the student with the highest mark.
python
CopyEdit
# Different ways to define strings
str1 = 'Hello'
str2 = "Python"
str3 = """This is a multi-line string."""
python
CopyEdit
text = " Hello Python! "
print(text.strip()) # Removes spaces: "Hello Python!"
print(text.upper()) # Converts to uppercase: "HELLO PYTHON!"
print(text.replace("Hello", "Hi")) # " Hi Python! "
The find() method returns the index of the first occurrence of a substring, or -1 if not found.
python
CopyEdit
sentence = "Python is powerful and easy to learn."
index = sentence.find("powerful")
print(index) # Output: 10
Using in Operator
python
CopyEdit
text = "Python is amazing!"
print("Python" in text) # True
print("Java" in text) # False
python
CopyEdit
text = "I love Java."
new_text = text.replace("Java", "Python")
Removing Substrings
python
CopyEdit
sentence = "Hello, how are you?"
sentence = sentence.replace("Hello, ", "")
# Extract "Python"
print(text[0:6]) # Python
# Extract "Programming"
print(text[6:]) # Programming
Examples:
python
CopyEdit
text = "abcdef"
print(text[1:4]) # "bcd"
print(text[:4]) # "abcd"
print(text[::2]) # "ace" (every second character)
print(text[::-1]) # "fedcba" (reverse string)
Summary
✅ Built-in String Functions
Practice Questions
1️⃣ Write a program to count occurrences of a word in a sentence.
2️⃣ Create a function to remove spaces from a given string.
3️⃣ Given "hello world", extract "world" using slicing.
4️⃣ Write a function to check if a string is a palindrome (same forward & backward).
FUNCTIONS in Python
Functions are blocks of reusable code that perform a specific task. They improve code reusability, readability, and
modularity.
A function is a named block of code that executes when called. Functions help break down complex problems into
smaller, manageable parts.
# Function Call
greet()
Output:
css
CopyEdit
Hello, Welcome to Python!
python
CopyEdit
# Function with Parameters
def greet(name): # 'name' is a parameter
print("Hello,", name)
Output:
CopyEdit
Hello, Alice
python
CopyEdit
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
Output:
yaml
CopyEdit
Name: John, Age: 21
Output:
CopyEdit
Hello, Guest!
Hello, Alice!
python
CopyEdit
def square(num):
return num * num # Function returns num^2
result = square(5)
print("Square:", result)
Output:
makefile
CopyEdit
Square: 25
python
CopyEdit
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(3, 5))
Output:
CopyEdit
8
python
CopyEdit
students = [("Alice", 85), ("Bob", 75), ("Charlie", 95)]
students.sort(key=lambda x: x[1]) # Sort by marks
print(students)
Filtering Data:
python
CopyEdit
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6]
python
CopyEdit
# mymath.py
def add(a, b):
return a + b
python
CopyEdit
import mymath
print(mymath.add(3, 5)) # 8
print(mymath.multiply(4, 2)) # 8
python
CopyEdit
# mathutils.py
def square(n):
return n * n
python
CopyEdit
from mypackage import mathutils
print(mathutils.square(4)) # 16
Summary
✅ Functions allow code reuse and improve readability.
✅ Parameters & Arguments allow functions to accept inputs.
✅ Lambda Functions are useful for short operations.
✅ Libraries & Packages allow creating reusable modules.
Practice Questions
1️⃣ Write a function that returns the factorial of a number.
2️⃣ Create a lambda function to check if a number is even.
3️⃣ Write a custom library with a function to calculate area of a circle.
4️⃣ Create a package with multiple math functions (addition, multiplication, square).
EXCEPTIONS in Python
An exception is an error that occurs during program execution, causing it to stop unless handled properly.
An exception is an unwanted event that disrupts the normal flow of execution in a program.
python
CopyEdit
try:
num = int(input("Enter a number: ")) # User input
print(10 / num) # Division operation
except ZeroDivisionError: # Handling division by zero
print("Error! Cannot divide by zero.")
except ValueError: # Handling invalid input
print("Invalid input! Please enter a number.")
Example Runs:
Input: 2 → Output: 5.0
Input: 0 → Output: "Error! Cannot divide by zero."
Input: "abc" → Output: "Invalid input! Please enter a number."
python
CopyEdit
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Success! Result:", result)
python
CopyEdit
try:
file = open("data.txt", "r") # Trying to open a file
print(file.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Execution completed!") # Always runs
python
CopyEdit
try:
num = int(input("Enter a number: "))
print(10 / num)
except (ZeroDivisionError, ValueError) as e:
print("Error:", e) # Prints error message
6️⃣ Nested Exception Handlers
Exception handlers can be nested inside each other.
python
CopyEdit
try:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter a number.")
python
CopyEdit
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above")
else:
print("Access granted!")
Output:
makefile
CopyEdit
ValueError: Age must be 18 or above
Summary
✅ try .. except handles exceptions.
✅ else runs if no exception occurs.
✅ finally always executes.
✅ Multiple exceptions can be handled together.
✅ raise manually triggers exceptions.
Practice Questions
1️⃣ Write a Python program to handle file-not-found exceptions.
2️⃣ Create a function that raises an exception if an input number is negative.
3️⃣ Write a program that asks for a number and handles zero-division errors.
4️⃣ Use finally to ensure a database connection is closed even if an error occurs.
A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions).
python
CopyEdit
# Defining a Class
class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand
self.model = model
# Creating an Object
my_car = Car("Toyota", "Camry")
my_car.show_info()
Output:
makefile
CopyEdit
Car: Toyota Camry
python
CopyEdit
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p1 = Person("Alice", 25)
p1.greet()
Output:
pgsql
CopyEdit
Hello, my name is Alice and I am 25 years old.
python
CopyEdit
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(2, 3)
p2 = Point(4, 5)
result = p1 + p2 # Uses overloaded `+` operator
print(f"({result.x}, {result.y})")
Output:
scss
CopyEdit
(6, 8)
4️⃣ Inheritance
Inheritance allows a child class to inherit attributes and methods from a parent class.
python
CopyEdit
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Animal sound!")
d = Dog("Buddy")
d.speak() # Calls overridden method
Output:
CopyEdit
Bark!
5️⃣ Multilevel & Multiple Inheritance
5.1 Multilevel Inheritance
A class inherits from another class, which itself is inherited from another.
python
CopyEdit
class Animal:
def eat(self):
print("Eating...")
class Mammal(Animal):
def walk(self):
print("Walking...")
class Dog(Mammal):
def bark(self):
print("Barking...")
d = Dog()
d.eat() # Inherited from Animal
d.walk() # Inherited from Mammal
d.bark() # Own method
Output:
CopyEdit
Eating...
Walking...
Barking...
python
CopyEdit
class Engine:
def start(self):
print("Engine started")
class Wheels:
def rotate(self):
print("Wheels moving")
c = Car()
c.start() # From Engine
c.rotate() # From Wheels
c.drive() # Own method
Output:
csharp
CopyEdit
Engine started
Wheels moving
Car is driving
python
CopyEdit
class Parent:
def show(self):
print("Parent class method")
class Child(Parent):
def show(self): # Overriding Parent's method
print("Child class method")
c = Child()
c.show() # Calls overridden method
Output:
kotlin
CopyEdit
Child class method
Summary
✅ Classes define the blueprint for objects.
✅ Objects are instances of classes.
✅ Constructors (__init__) initialize object properties.
✅ Operator Overloading allows custom behaviors for operators.
✅ Inheritance enables code reuse.
✅ Multilevel & Multiple Inheritance provide complex relationships.
✅ Method Overriding allows redefining parent class methods.
Practice Questions
1️⃣ Create a Student class with name, age, and marks attributes.
2️⃣ Implement operator overloading for subtraction (-) in a class.
3️⃣ Create an Employee class with Manager and Developer as subclasses.
4️⃣ Implement multiple inheritance in a program.
✅ Store data permanently (unlike variables, which lose data when the program ends).
✅ Read & write data without needing user input every time.
✅ Manage large amounts of data efficiently.
python
CopyEdit
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read file content
file.close() # Close file
python
CopyEdit
file = open("sample.txt", "w") # Open file in write mode
file.write("Hello, Python File Handling!\n")
file.close() # Always close file
python
CopyEdit
file = open("sample.txt", "r") # Open file in read mode
print(file.read()) # Print file content
file.close()
Output:
arduino
CopyEdit
Hello, Python File Handling!
python
CopyEdit
with open("sample.txt", "r") as file:
content = file.read()
print(content)
3️⃣ Writing & Reading Data Files (CSV, JSON)
Reading & Writing CSV Files
python
CopyEdit
import csv
# Writing to CSV
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "New York"])
writer.writerow(["Bob", 30, "London"])
Output:
css
CopyEdit
['Name', 'Age', 'City']
['Alice', '25', 'New York']
['Bob', '30', 'London']
python
CopyEdit
import json
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
Output:
bash
CopyEdit
{'name': 'Alice', 'age': 25, 'city': 'New York'}
4️⃣ Writing & Reading Objects in Binary Files using pickle
The pickle module is used for storing Python objects in binary format.
python
CopyEdit
import pickle
# Writing (Pickling)
data = {"name": "Alice", "age": 25, "city": "New York"}
# Reading (Unpickling)
with open("data.pkl", "rb") as file:
content = pickle.load(file)
print(content)
Output:
bash
CopyEdit
{'name': 'Alice', 'age': 25, 'city': 'New York'}
# Rename a directory
os.rename("NewFolder", "RenamedFolder")
# Delete a directory
os.rmdir("RenamedFolder")
Summary
✅ Text files store normal text data (.txt).
✅ CSV files store tabular data.
✅ JSON files store structured data (key-value).
✅ Pickle files store Python objects (binary format).
✅ Directory manipulation allows managing folders.
Practice Questions
1️⃣ Write a program to store student details in a text file and read it later.
2️⃣ Create a CSV file for employees and read the details.
3️⃣ Write a JSON file containing product details and retrieve it.
4️⃣ Store multiple student records in a binary file using pickle.
5️⃣ Create a Python program that creates, renames, and deletes a directory.