Day 3: Python Essentials - Strings, File Handling, Decorators & Generators ??
Sarasa Jyothsna Kamireddi
Aspiring Python Developer | Machine Learning Enthusiast | Experienced in Reliability Engineering
Today, I'm diving into powerful Python concepts essential for writing clean and efficient code: Strings, File Handling, Decorators, and Generators. Let's explore! ??
1?? Python Strings - More than Just Text
Strings in Python are immutable, meaning they cannot be modified in place
? Common String Operations
text = "Hello, Python!"
print(text.upper()) # HELLO PYTHON!
print(text.lower()) #hello, python!
print(text.split()) # ['Hello',' Python!']
print(text.replace("Python","World"] # Hello, World!
print(len(text)) #14
?? Use f-strings for better readability in string formatting:
name = "Jyothsna"
print(f"Hello, {name}!") # Hello, Jyothsna!
2?? File Handling - Reading & Writing Files
Python makes working with files simple! ??
? Reading a File
with open("sample.txt", "r") as file:
content = file.read()
print(content)
? Writing to a File
with open("output.txt","a") as file:
file.write("\nAppending new content!")
3?? Decorators - Adding Functionality to Functions
Decorators are used to modify functions without changing their code
? Basic Decorator Example
def my_decorator(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper
@my_decorator
def say_hello():
print("Hello, World!")
say_hello()
?? Output:
Before the function call
Hello, World!
After the function call
? Use Cases: logging, Authentication, Execution Timing
4?? Generators - Efficient Iteration with Yield
A generator is a special function that produces values on demand instead of storing them in memory
? Creating a Generator with yield
def my_generator():
yield 1
yield 2
yield 3
gen=my_generator()
print(next(gen)) #1
print(next(gen)) #2
print(next(gen)) #3
? Why to Use Generators?
?? Saves memory - No need to store large data in RAM
?? Improves performance - Generates value only when needed
?? Example: Generating an Infinite Sequence
def infinite_numbers():
num=0
while True:
yield num
num+=1
gen=infinite_numbers()
for i in range(10):
print(next(gen))
Summary of Today's Concepts
?? Strings - Use f-strings for formatting
?? File Handling - Use "with-open()" to manage files safely
?? Decorators - Modify functions without changing their code
?? Strings - Use yield for memory-efficient loops
?? Which concept do you use the most? Let me know in the comments! ??
#100DaysOfCode #Python #Programming #Coding #Learning