0% found this document useful (0 votes)
5 views14 pages

Unit 4 Python

The document provides an overview of file handling modes in Python, including reading, writing, appending, and checking if a file exists. It also covers string formatting methods, command line arguments, creating packages, and using the itertools and functools modules for efficient programming. Key functions and examples are provided for each topic to illustrate their usage.
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)
5 views14 pages

Unit 4 Python

The document provides an overview of file handling modes in Python, including reading, writing, appending, and checking if a file exists. It also covers string formatting methods, command line arguments, creating packages, and using the itertools and functools modules for efficient programming. Key functions and examples are provided for each topic to illustrate their usage.
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

Modes:

 "r" → Read (default)

 "w" → Write (overwrites file)

 "a" → Append (adds data)

 "x" → Create (fails if file exists)

 "b" → Binary mode

 "t" → Text mode (default)

file = open("[Link]", "r")

content = [Link]()

print(content)

[Link]()

file = open("[Link]", "w")

[Link]("Hello World")

[Link]()

Appending to a File

file = open("[Link]", "a")

[Link]("\nNew Line Added")

[Link]()

Using with Statement (Best Practice)

Automatically closes the file:

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

content = [Link]()

print(content)

8. Checking File Exists


import os

if [Link]("[Link]"):

print("File exists")

else:

print("File not found")

import os

[Link]("test") # create folder

[Link]("test") # remove folder

[Link]("[Link]") # delete file

format string

name = "Geetha"

age = 20

print("My name is %s and I am %d years old" % (name, age))

name = "Geetha"

age = 20
print("My name is {} and I am {} years old".format(name, age))

name = "Geetha"

age = 20

print(f"My name is {name} and I am {age} years old")\

num = 12.34567

print("%.2f" % num) # 12.35

print("{:.2f}".format(num)) # 12.35

print(f"{num:.2f}") # 12.35

command line arguments


Command line arguments in Python are
values passed to a program when you
run it from the terminal/command
prompt.
1. WITHOUT sys (using input())
name = input("Enter your name: ")
age = int(input("Enter your age: "))

print(f"Name: {name}, Age:


{age}")

output:
Enter your name: Geetha
Enter your age: 20
Name: Geetha, Age: 20

[Link] sys (Command Line Arguments)


import sys
print("Arguments:", [Link])
import sys

name = [Link][0]
print(f"Name: {name}")

Structure of a Package
Example:
mypackage/

├── __init__.py
├── math_ops.py
├── string_ops.py

✅ Step-by-Step: Create a Package


🔹 Step 1: Create a folder
Create a folder named mypackage

🔹 Step 2: Add __init__.py


Create an empty file:
__init__.py
👉 This tells Python it's a package

🔹 Step 3: Create modules inside package


📄 math_ops.py
def add(a, b):
return a + b
📄 string_ops.py
def greet(name):
return "Hello " + name
✅ Step 4: Use Package in Another File
Create [Link] outside the package:

Python itertools (Simple Explanation)


itertools is a built-in Python module used
for fast and memory-efficient looping.
It is very useful in problems involving
combinations, permutations, and iteration.

✅ Why use itertools?


✔ Faster than normal loops
✔ Saves memory
✔ Useful for data science, ML, competitive
coding

🔹 Important Functions in itertools

1️⃣ count() → Infinite counting


import itertools

for i in [Link](1, 2):


print(i)
if i > 10:
break
👉 Output:
1 3 5 7 9 11

2️⃣ cycle() → Repeats elements infinitely


import itertools

count = 0
for i in [Link](['A', 'B', 'C']):
print(i)
count += 1
if count == 5:
break
👉 Output:
ABCAB

3️⃣ repeat() → Repeat same value


import itertools

for i in [Link]("Hi", 3):


print(i)
👉 Output:
Hi Hi Hi

4️⃣ permutations() → All possible


arrangements
from itertools import permutations

data = [1, 2, 3]
print(list(permutations(data)))
👉 Output:
[(1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2),
(3,2,1)]

5️⃣ combinations() → Select without order


from itertools import combinations

data = [1, 2, 3]
print(list(combinations(data, 2)))
👉 Output:
[(1,2), (1,3), (2,3)]

6️⃣ product() → Cartesian product


from itertools import product

print(list(product([1, 2], ['A', 'B'])))


👉 Output:
[(1,'A'), (1,'B'), (2,'A'), (2,'B')]

7️⃣ chain() → Combine multiple iterables


from itertools import chain

print(list(chain([1,2], [3,4])))
👉 Output:
[1, 2, 3, 4]

8️⃣ accumulate() → Running total


from itertools import accumulate

print(list(accumulate([1, 2, 3, 4])))
👉 Output:
[1, 3, 6, 10]
Permutations (arrangement)
👉 AB, BA
Combinations (selection)
👉 AB only
Product (with repetition)
👉 AA, AB, BA, BB

What is functools?
👉 functools is a built-in Python module used
for:
 Working with functions
 Functional programming tools
 Optimizing and reusing code

🔹 Important Functions in functools

1️⃣ reduce() → Apply function repeatedly


👉 Combines all elements into a single value
from functools import reduce

data = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, data)

print(result)
👉 Output:
10
👉 Works like:
((1+2)+3)+4

2️⃣ partial() → Fix some arguments


👉 Creates a new function with fixed values
from functools import partial

def power(a, b):


return a ** b
square = partial(power, b=2)

print(square(5))
👉 Output:
25

3️⃣ lru_cache() → Cache results (very


important)
👉 Stores previous results to make code
faster
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)

print(fib(10))
👉 Speeds up recursive functions 🚀

4️⃣ wraps() → Preserve function info


👉 Used in decorators
from functools import wraps

def my_decorator(func):
@wraps(func)
def wrapper():
print("Before")
func()
return wrapper

5️⃣ cmp_to_key() → Convert comparison to


key
👉 Useful in sorting
from functools import cmp_to_key

def compare(a, b):


return a - b

data = [5, 2, 9, 1]
[Link](key=cmp_to_key(compare))

print(data)
mark = int(input("Enter mark: "))

if 0 <= mark <= 100:


if mark >= 90:
print("Grade A")
elif mark >= 75:
print("Grade B")
elif mark >= 50:
print("Grade C")
else:
print("Fail")
else:
print("Invalid input")

You might also like