📘 PAPER 2: OBJECT ORIENTED PROGRAMMING WITH PYTHON UNIT 4 – Dictionaries, Functions, File Handling & Regular Expressions (university of allahabad)

 

🔴 UNIT 4 – Dictionaries, Functions, File Handling & Regular Expressions


1️⃣ Dictionaries in Python

✅ Definition

A dictionary is an unordered collection of data stored as key–value pairs.

Example:

student = { "name": "Amit", "age": 20, "course": "MCA" }

🔹 Characteristics

✔ Key-value based
Mutable
Keys must be unique
Fast access


🔹 Accessing Dictionary Elements

print(student["name"])

🔹 Adding & Updating Values

student["age"] = 21 student["city"] = "Delhi"

🔹 Deleting Elements

del student["age"]

2️⃣ Counting Frequency Using Dictionary

Example:

text = "banana" freq = {} for ch in text: if ch in freq: freq[ch] += 1 else: freq[ch] = 1 print(freq)

Output:

{'b':1, 'a':3, 'n':2}

3️⃣ Python Functions

✅ Definition

A function is a block of reusable code.


🔹 Function Syntax

def function_name(parameters): statements return value

🔹 Types of Arguments

  1. Positional

  2. Keyword

  3. Default

  4. Variable-length


Example:

def add(a, b=5): return a + b

4️⃣ Passing Function as Argument

def square(x): return x*x def fun(f, value): return f(value) print(fun(square, 5))

5️⃣ Lambda Function

Definition:

Anonymous function written in one line.

square = lambda x: x*x print(square(5))

6️⃣ Map Function

nums = [1,2,3] result = list(map(lambda x: x*2, nums))

7️⃣ List Comprehension

squares = [x*x for x in range(5)]

8️⃣ File Handling in Python


🔹 Opening a File

f = open("data.txt", "r")

File Modes:

ModeMeaning
rRead
wWrite
aAppend
r+Read + Write

🔹 Reading File

f.read()

🔹 Writing File

f.write("Hello Python")

🔹 Closing File

f.close()

9️⃣ String Processing

Common String Functions:

s.upper() s.lower() s.replace() s.split() s.strip()

🔟 Regular Expressions (RegEx)

Definition:

Regular expressions are used for pattern matching.


Common Symbols

SymbolMeaning
.Any character
^Start of string
$End of string
*Zero or more
+One or more
[a-z]Range

Example:

import re pattern = re.search("python", "I love python")

Comments

Popular Posts