0% found this document useful (0 votes)
4 views24 pages

Python Complete Study Notes

This document provides comprehensive study notes on Python programming, covering topics such as the introduction to Python, variables, operators, conditional statements, loops, lists, and tuples. Each chapter includes explanations, code examples, and key features of the language. The notes are designed for students of EACCS102 / ESCCS202 and serve as a guide for understanding Python programming concepts.

Uploaded by

kritish2803
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

Python Complete Study Notes

This document provides comprehensive study notes on Python programming, covering topics such as the introduction to Python, variables, operators, conditional statements, loops, lists, and tuples. Each chapter includes explanations, code examples, and key features of the language. The notes are designed for students of EACCS102 / ESCCS202 and serve as a guide for understanding Python programming concepts.

Uploaded by

kritish2803
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming

Complete Study Notes


EACCS102 / ESCCS202 | Theory, Programs & Explanations

Chapter 1: Introduction to Python


1.1 What is Python?
Python is a high-level, interpreted programming language created by Guido van Rossum. It is open-
source, beginner-friendly, and widely used across domains like web development, data science,
artificial intelligence, and automation.

Key Features:
• Easy to understand — reads almost like plain English
• Interpreted language — code runs line by line without compilation
• Portable — runs on Windows, macOS, Linux
• Object-Oriented — supports classes and objects
• Large community support and standard library

1.2 First Python Program


The print() function displays output on the screen.

# Hello World Program


print("Hello, World!")

# Output: Hello, World!

1.3 Variables
Variables are containers for storing data. In Python, you do not need to declare a variable type —
Python assigns it automatically.

# Assigning a string to a variable


a = "Hello World!"
print(a)
# Output: Hello World!

# Reassigning the same variable


a = "and goodbye.."
print(a)
# Output: and goodbye..

1.4 Python Keywords


Keywords are reserved words with special meaning in Python. They cannot be used as variable names.

Category Keywords
Control & Decision if, else, elif, for, while, break, continue, pass
Function & Class def, return, class, lambda
Logical and, or, not
Boolean & Special True, False, None
Exception Handling try, except, finally, raise, assert
Import & Modules import, from, as
Scope & Variables global, nonlocal, del
Identity & Membership is, in

Chapter 2: Operators in Python


An operator is a symbol used to perform operations on values (called operands). Python has 7 types of
operators.

2.1 Arithmetic Operators


Used for mathematical calculations.

Operator Meaning Example Result


+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2.5
% Modulus (remainder) 5 % 2 1
** Power (exponent) 2 ** 3 8
// Floor Division 5 // 2 2

2.2 Relational (Comparison) Operators


Used to compare two values. Always return True or False.
a = 10
b = 5
print(a > b) # True
print(a == b) # False
print(a != b) # True
print(a >= b) # True
print(a <= b) # False

2.3 Logical Operators


Used to combine multiple conditions.

a = 10
b = 5
print(a > 5 and b < 10) # True (both conditions true)
print(a < 5 or b < 10) # True (at least one condition true)
print(not (a > 5)) # False (reverses the result)

2.4 Assignment Operators


Used to assign values to variables. Shorthand forms also update the variable.

Operator Equivalent To Example


= Assign a = 5
+= a = a + 3 a += 3 → a becomes 8
-= a = a - 3 a -= 3 → a becomes 2
*= a = a * 3 a *= 3 → a becomes 15
/= a = a / 3 a /= 3 → a becomes 1.67

2.5 Bitwise Operators


Operate on binary representations of numbers.

a = 5 # binary: 0101
b = 3 # binary: 0011

print(a & b) # AND → 0001 → 1


print(a | b) # OR → 0111 → 7
print(a ^ b) # XOR → 0110 → 6
print(~a) # NOT → -(5+1) → -6
print(a << 1) # Left shift → 1010 → 10
print(a >> 1) # Right shift → 0010 → 2
2.6 Membership & Identity Operators
# Membership: check if value exists in a sequence
x = [1, 2, 3]
print(2 in x) # True
print(5 not in x) # True

# Identity: check if two variables point to same object


a = 10
b = 10
print(a is b) # True (same object in memory)
print(a is not b) # False

Chapter 3: Conditional Statements


Conditional statements allow your program to make decisions and execute different code depending on
whether a condition is True or False.

3.1 if Statement
Executes a block of code only when the condition is True.

age = 18
if age >= 18:
print("You are eligible to vote")

# Output: You are eligible to vote

3.2 if-else Statement


Chooses between two blocks — one runs when the condition is True, the other when False.

age = 16
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

# Output: Not eligible to vote

3.3 if-elif-else Statement


Used when there are more than two possible choices. Python checks each condition in order and runs
the first matching block.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")

# Output: Grade B

3.4 Nested if
An if statement placed inside another if statement. Both conditions must be satisfied for the innermost
block to execute.

num = 10
if num >= 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Negative number")

# Output: Positive even number

3.5 Match-Case Statement (Python 3.10+)


An alternative to multiple if-elif chains. Similar to switch-case in other languages. Python evaluates the
expression and runs the matching case block.

day = 4
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")

# Output: Thursday
Chapter 4: Loops
Loops allow a block of code to execute repeatedly. This reduces code duplication and makes programs
efficient.

4.1 for Loop


Used when the number of iterations is known, or when iterating over a sequence (list, string, range,
etc.).

# Basic for loop with range


for i in range(5):
print(i)
# Output: 0 1 2 3 4

# Iterating over a list


fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# Output: apple banana mango

# range(start, stop, step)


for i in range(1, 10, 2):
print(i)
# Output: 1 3 5 7 9

4.2 while Loop


Repeats a block as long as the given condition is True. Used when the number of iterations is not
known in advance.

i = 1
while i <= 5:
print(i)
i += 1
# Output: 1 2 3 4 5

# IMPORTANT: Always update the variable inside the loop


# or it will loop forever (infinite loop)!

Infinite Loop Warning: If the while condition never becomes False, the loop runs forever. Always
make sure the condition will eventually be False.
4.3 Nested Loops
A loop inside another loop. The inner loop completes all its iterations for every single iteration of the
outer loop.

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

# Output:
# red apple red banana red cherry
# big apple big banana big cherry
# tasty apple tasty banana tasty cherry

4.4 Loop Control: break, continue, pass


# break: exits the loop immediately
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4

# continue: skips the current iteration and moves to next


for i in range(5):
if i == 2:
continue
print(i)
# Output: 0 1 3 4

# pass: does nothing; used as a placeholder to avoid errors


for x in [0, 1, 2]:
pass # Will be implemented later

Chapter 5: Lists
A list is an ordered, mutable (changeable) collection that allows duplicate values. Lists are one of the
most commonly used data structures in Python.

# Creating a list
thislist = ["apple", "banana", "cherry"]
print(thislist) # ["apple", "banana", "cherry"]
print(type(thislist)) # <class "list">
print(len(thislist)) # 3
5.1 Indexing and Slicing
List items are indexed starting at 0. Negative indexing counts from the end (-1 is the last item).

numbers = [10, 20, 30, 40, 50]

# Positive indexing
print(numbers[0]) # 10 (first item)
print(numbers[2]) # 30 (third item)

# Negative indexing
print(numbers[-1]) # 50 (last item)
print(numbers[-2]) # 40 (second last)

# Slicing: list[start:stop] (stop is exclusive)


mylist = ["apple","banana","cherry","orange","kiwi","melon","mango"]
print(mylist[2:5]) # ["cherry", "orange", "kiwi"]
print(mylist[:4]) # ["apple", "banana", "cherry", "orange"]
print(mylist[2:]) # ["cherry", "orange", "kiwi", "melon", "mango"]
print(mylist[-4:-1]) # ["orange", "kiwi", "melon"]

5.2 Modifying Lists


# Change a single item
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) # ["apple", "blackcurrant", "cherry"]

# Change a range of items


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist) # ["apple", "blackcurrant", "watermelon", "orange", "kiwi",
"mango"]

5.3 Adding Items


# append() - adds to the END of the list
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist) # ["apple", "banana", "cherry", "orange"]

# insert() - adds at a SPECIFIC position


[Link](2, "watermelon")
print(thislist) # ["apple", "banana", "watermelon", "cherry", "orange"]

# extend() - adds ALL items from another list


list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
[Link](list2)
print(list1) # ["a", "b", "c", 1, 2, 3]

5.4 Removing Items


# remove() - removes by VALUE (first occurrence)
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist) # ["apple", "cherry"]

# pop() - removes by INDEX (default: last item)


thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist) # ["apple", "cherry"]

# del - removes by index or deletes entire list


del thislist[0]
print(thislist) # ["cherry"]

# clear() - empties the list


[Link]()
print(thislist) # []

5.5 Sorting Lists


# sort() - sorts in ascending order (in-place)
thislist = ["orange", "mango", "kiwi", "banana"]
[Link]()
print(thislist) # ["banana", "kiwi", "mango", "orange"]

# Descending sort
[Link](reverse=True)
print(thislist) # ["orange", "mango", "kiwi", "banana"]

# Note: sort() is case-sensitive!


# Uppercase letters come BEFORE lowercase
mixed = ["banana", "Orange", "Kiwi", "cherry"]
[Link]()
print(mixed) # ["Kiwi", "Orange", "banana", "cherry"]

5.6 List Comprehension


A concise way to create a new list from an existing one, with optional filtering.
# Traditional way (with for loop + if condition)
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
[Link](x)
print(newlist) # ["apple", "banana", "mango"]

# List comprehension (shorter syntax)


newlist = [x for x in fruits if "a" in x]
print(newlist) # ["apple", "banana", "mango"]

5.7 List Methods Summary

Method Syntax Description


append() [Link](x) Add x to end
extend() [Link](iter) Add all items of another iterable
insert() [Link](i, x) Insert x at index i
remove() [Link](x) Remove first occurrence of x
pop() [Link]([i]) Remove & return item at index i
clear() [Link]() Remove all items
index() [Link](x) Return index of first x
count() [Link](x) Count occurrences of x
sort() [Link]() Sort in ascending order
reverse() [Link]() Reverse the list
copy() [Link]() Return shallow copy

Chapter 6: Tuples
A tuple is an ordered, immutable (unchangeable) collection. Once created, its values cannot be
modified. Tuples are written with round brackets.

# Creating a tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple) # ("apple", "banana", "cherry")
print(thistuple[1]) # banana
print(thistuple[-1]) # cherry
print(len(thistuple)) # 3

# Duplicates are allowed


thistuple = ("apple", "banana", "cherry", "apple")
print(thistuple) # ("apple", "banana", "cherry", "apple")
6.1 Accessing Tuple Items
# Access by index
thistuple = ("apple", "banana", "cherry")
print(thistuple[0]) # apple
print(thistuple[-1]) # cherry (last item)

# Slicing
print(thistuple[0:2]) # ("apple", "banana")

6.2 Tuples are Immutable — Workaround


Tuples cannot be changed directly. The workaround is to convert to a list, modify, then convert back.

# Tuples are immutable — this would cause an error:


# thistuple[1] = "kiwi" ← TypeError!

# Workaround: convert to list → change → convert back


x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) # ("apple", "kiwi", "cherry")

# Adding an item using concatenation


thistuple = ("apple", "banana", "cherry")
thistuple += ("orange",) # Note the trailing comma!
print(thistuple) # ("apple", "banana", "cherry", "orange")

6.3 Tuple Packing & Unpacking


# Packing: creating a tuple
fruits = ("apple", "banana", "cherry")

# Unpacking: extracting values back into variables


(green, yellow, red) = fruits
print(green) # apple
print(yellow) # banana
print(red) # cherry

# Using * to collect remaining items


fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green) # apple
print(yellow) # banana
print(red) # ["cherry", "strawberry", "raspberry"]
6.4 Joining & Multiplying Tuples
# Join with + operator
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3) # ("a", "b", "c", 1, 2, 3)

# Multiply with * operator


fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple) # ("apple","banana","cherry","apple","banana","cherry")

6.5 Tuple Methods


# count() - how many times a value appears
T = (10, 20, 20, 30)
print([Link](20)) # 2

# index() - find the position of a value


T = (10, 20, 30)
print([Link](30)) # 2

# Note: Tuples do NOT support append(), remove(), pop(),


# insert(), clear() because they are immutable.

Chapter 7: Sets
A set is an unordered, unindexed collection that does not allow duplicate values. Sets are written with
curly braces.

# Creating a set
thisset = {"apple", "banana", "cherry"}
print(thisset) # e.g. {"cherry", "banana", "apple"} (order varies!)

# Duplicates are automatically removed


thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) # {"apple", "banana", "cherry"}

# True and 1 are considered the same value


thisset = {"apple", True, 1, 2}
print(thisset) # {True, 2, "apple"}
7.1 Adding & Removing Items
# add() - adds one item
thisset = {"apple", "banana", "cherry"}
[Link]("orange")

# update() - adds items from another set/list


[Link](["kiwi", "mango"])

# remove() - removes item; raises error if not found


[Link]("banana")

# discard() - removes item; NO error if not found (safer!)


[Link]("banana")

# pop() - removes a RANDOM item (sets are unordered)


x = [Link]()

# clear() - empties the set


[Link]()

7.2 Set Operations


Sets support mathematical operations like union, intersection, difference, and symmetric difference.

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

# Union: all items from BOTH sets (no duplicates)


print([Link](set2)) # or set1 | set2
# {"apple", "banana", "cherry", "google", "microsoft"}

# Intersection: items present in BOTH sets


print([Link](set2)) # or set1 & set2
# {"apple"}

# Difference: items in set1 that are NOT in set2


print([Link](set2)) # or set1 - set2
# {"banana", "cherry"}

# Symmetric Difference: items in EITHER but NOT BOTH


print(set1.symmetric_difference(set2)) # or set1 ^ set2
# {"banana", "cherry", "google", "microsoft"}
Chapter 8: Dictionaries
A dictionary stores data as key-value pairs. Keys must be unique; values can be of any data type. As of
Python 3.7, dictionaries maintain insertion order.

# Creating a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict) # {"brand": "Ford", ...}
print(thisdict["brand"]) # Ford
print(len(thisdict)) # 3
print(type(thisdict)) # <class "dict">

8.1 Accessing, Adding & Updating


# Access using key name
print(thisdict["model"]) # Mustang
print([Link]("model")) # Mustang (safer — no error if key missing)

# Get all keys / values


print([Link]()) # dict_keys(["brand", "model", "year"])
print([Link]()) # dict_values(["Ford", "Mustang", 1964])
print([Link]()) # dict_items([("brand","Ford"), ...])

# Add a new key-value pair


thisdict["color"] = "red"

# Update an existing value


thisdict["year"] = 2020
[Link]({"year": 2020}) # Same effect using update()

8.2 Removing Items


# pop("key") - removes item with specified key
[Link]("model")

# popitem() - removes the LAST inserted item


[Link]()

# del - removes by key, or deletes entire dictionary


del thisdict["model"]
# del thisdict ← deletes whole dictionary

# clear() - empties the dictionary


[Link]() # {}

8.3 Looping Through a Dictionary


thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Loop through keys (default)


for x in thisdict:
print(x) # brand model year

# Loop through values


for x in [Link]():
print(x) # Ford Mustang 1964

# Loop through both keys AND values


for x, y in [Link]():
print(x, y) # brand Ford / model Mustang / year 1964

8.4 Nested Dictionaries


A dictionary can contain other dictionaries as values.

myfamily = {
"child1": {"name": "Emil", "year": 2004},
"child2": {"name": "Tobias", "year": 2007},
"child3": {"name": "Linus", "year": 2011}
}

# Accessing nested data


print(myfamily["child2"]["name"]) # Tobias

# Looping through nested dictionary


for x, obj in [Link]():
print(x)
for y in obj:
print(y + ":", obj[y])

Chapter 9: Functions
A function is a reusable block of code that runs only when it is called. Functions help avoid repetition,
improve readability, and make code easier to maintain.

# Defining a function
def my_function():
print("Hello from a function")
# Calling a function
my_function()
# Output: Hello from a function

9.1 Why Use Functions? (Reusability)


# Without functions — repetitive code
celsius1 = (77 - 32) * 5 / 9 # 25.0
celsius2 = (95 - 32) * 5 / 9 # 35.0

# With functions — reusable code


def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9

print(fahrenheit_to_celsius(77)) # 25.0
print(fahrenheit_to_celsius(95)) # 35.0
print(fahrenheit_to_celsius(50)) # 10.0

9.2 Function Arguments


# Regular argument
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil") # Emil Refsnes


my_function("Tobias") # Tobias Refsnes

9.3 *args — Variable Positional Arguments


*args allows a function to accept any number of positional arguments. Inside the function, args is a
tuple.

def add_numbers(*args):
total = 0
for num in args:
total += num
return total

print(add_numbers(1, 2, 3)) # 6
print(add_numbers(5, 10)) # 15
print(add_numbers(1,2,3,4,5)) # 15
9.4 **kwargs — Variable Keyword Arguments
**kwargs allows any number of keyword arguments. Inside the function, kwargs is a dictionary.

def my_function(**myvar):
print("Name:", myvar["name"])
print("Age:", myvar["age"])
print("All data:", myvar)

my_function(name="Amit", age=30, city="Kolkata")


# Output:
# Name: Amit
# Age: 30
# All data: {"name": "Amit", "age": 30, "city": "Kolkata"}

9.5 Scope — Local vs Global Variables


# Local scope: variable created inside a function
def myfunc():
x = 300 # local — only accessible inside myfunc
print(x) # 300

myfunc()
# print(x) ← This would raise NameError!

# Global scope: variable created outside any function


x = 300
def myfunc():
print(x) # Can access global x

myfunc() # 300
print(x) # 300

# global keyword: modify global variable inside a function


def myfunc():
global x
x = 300
myfunc()
print(x) # 300

# nonlocal keyword: modify enclosing (nested) function variable


def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1()) # hello
9.6 Lambda Functions
A lambda is a small, anonymous (nameless) function written in a single line. It can have any number of
arguments but only one expression.

# Syntax: lambda arguments : expression

# Single argument
x = lambda a: a + 10
print(x(5)) # 15

# Multiple arguments
x = lambda a, b: a * b
print(x(5, 6)) # 30

# Three arguments
x = lambda a, b, c: a + b + c
print(x(5, 6, 2)) # 13

# Lambda with **kwargs


show = lambda **kwargs: kwargs
print(show(name="Ravi", age=20))
# {"name": "Ravi", "age": 20}

9.7 Recursion
Recursion is when a function calls itself. It is used to solve problems that can be broken into smaller
sub-problems of the same type. Always include a base case (stopping condition) to prevent infinite
recursion.

# Countdown using recursion


def countdown(n):
if n <= 0: # base case
print("Done!")
else:
print(n)
countdown(n - 1) # recursive call

countdown(5)
# Output: 5 4 3 2 1 Done!

# Factorial using recursion


def factorial(n):
if n == 0 or n == 1: # base case
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120 (5 x 4 x 3 x 2 x 1)

# Python default recursion limit


import sys
print([Link]()) # 1000

9.8 Generators
Generators are special functions that can pause their execution and resume from where they left off.
They use the yield keyword instead of return. Generators are memory-efficient for large data
sequences.

# Simple generator
def my_generator():
yield 1
yield 2
yield 3

for value in my_generator():


print(value)
# Output: 1 2 3

# Generator with next() — step by step control


def numbers():
print("Start")
yield 1
print("Middle")
yield 2

g = numbers()
print(next(g)) # Start → 1
print(next(g)) # Middle → 2
# next(g) after all yields → StopIteration error

# Fibonacci generator (infinite sequence, memory-efficient)


def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

gen = fibonacci()
for _ in range(10):
print(next(gen), end=" ")
# Output: 0 1 1 2 3 5 8 13 21 34
Chapter 10: File Handling
File handling enables Python programs to create, read, write, and delete files — allowing data to be
stored permanently beyond program execution.

10.1 Why File Handling?


• Permanent Data Storage — variables are lost when a program ends; files store data
permanently
• Data Processing — read CSV files, log files, configuration files
• Large Data Handling — read file line by line rather than loading everything into memory
• Real-World Applications — banking systems, student records, report generation, logging

10.2 File Modes

Mode Description If file doesn't exist?


"r" Read (default) — error if file Error
missing
"w" Write — overwrites existing Creates new file
content
"a" Append — adds to end of file Creates new file
"x" Create — error if file exists Creates new file
"t" Text mode (default) —
"b" Binary mode (images, etc.) —

10.3 Opening and Reading Files


# Basic file open (read mode is default)
f = open("[Link]")
f = open("[Link]", "r") # Same as above

# Read entire file content


f = open("[Link]")
print([Link]())
# Output:
# Hello! Welcome to [Link]
# This file is for testing purposes.
# Good Luck!
[Link]() # Always close the file!

# Read only first N characters


with open("[Link]", "r") as f:
print([Link](5)) # Hello
# Read one line at a time
with open("[Link]") as f:
print([Link]()) # Hello! Welcome to [Link]

# Read two lines


with open("[Link]") as f:
print([Link]())
print([Link]())

Best Practice: Always use the with statement when opening files. It automatically closes the file
after the block, even if an error occurs. This is safer than manually calling [Link]().

10.4 Writing to Files


# Append mode — adds content to the END of file
with open("[Link]", "a") as f:
[Link]("Now the file has more content!")

# Read to verify
with open("[Link]") as f:
print([Link]())
# Output: (original content) + "Now the file has more content!"

# Write mode — OVERWRITES all existing content


with open("[Link]", "w") as f:
[Link]("Woops! I have deleted the content!")

with open("[Link]") as f:
print([Link]())
# Output: Woops! I have deleted the content!

10.5 Creating & Deleting Files


# Create new file (error if already exists)
f = open("[Link]", "x")

# Delete a file safely


import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")

# Delete an empty folder


[Link]("myfolder")
10.6 Common File Programs
Count Lines in a File
with open("[Link]", "r") as f:
lines = [Link]()
print("Number of lines:", len(lines))

Count Words in a File


count = 0
with open("[Link]", "r") as f:
for line in f:
words = [Link]()
count += len(words)
print("Number of words:", count)

Copy Contents from One File to Another


with open("[Link]", "r") as src:
content = [Link]()

with open("[Link]", "w") as dest:


[Link](content)

print("File copied successfully!")

Search for a Word in a File


search_word = "Python"
found = False

with open("[Link]", "r") as f:


for line in f:
if search_word in line:
print("Found:", [Link]())
found = True

if not found:
print(search_word, "not found in file")

10.7 Exception Handling in File Handling


Always handle file errors using try-except to prevent program crashes.
try:
with open("[Link]", "r") as f:
print([Link]())
except FileNotFoundError:
print("Error: The file does not exist!")
except PermissionError:
print("Error: No permission to read this file!")
finally:
print("File operation attempted.") # Always runs

Concept Description
read() Reads the entire file as one string
readline() Reads one line at a time
readlines() Reads all lines and returns a list
write() Writes a string to a file
writelines() Writes a list of strings to a file
close() Closes the file (frees resources)
with open() Context manager — auto-closes file
FileNotFoundError Raised when file doesn't exist in 'r' mode

Quick Reference: List vs Tuple vs Set vs Dictionary

Feature List Tuple Set Dictionary


Syntax [ ] ( ) { } { key: value
}
Ordered? Yes Yes No Yes (3.7+)
Mutable? Yes No Yes* Yes
Duplicates? Yes Yes No No (keys)
Indexed? Yes Yes No By key
Use case General list Fixed data Unique items Key-value
pairs

Exam Preparation Tips

For 2-mark questions: Define the term clearly, then give one example.

For 5-mark questions: Explain the concept with theory, then show a complete working program
with output.
Always mention the output of every program you write in exams.

Key differences to remember: list vs tuple (mutable vs immutable), remove() vs discard() in sets
(error vs no error), append() vs extend() in lists (one item vs multiple).

— End of Study Notes —

You might also like