Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! 🚀 Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! 🐍
Download Telegram
Handling File Exceptions
File operations can result in errors, such as trying to open a non-existent file in read mode. You can handle such cases using exception handling with try and except.

Example:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found. Please check the filename.")
1
File Positioning: seek() and tell()
tell(): Returns the current position of the file pointer (in bytes).
seek(offset, from_what): Moves the file pointer to a specified location.

Example:
with open("example.txt", "r") as file:
print(file.tell()) # Prints the current position of the file pointer
file.seek(0) # Moves the pointer to the beginning of the file
print(file.read())
Practice Exercises for Day 10

Exercise 1: Word Count

Write a Python program to count the number of words in a text file.


Exercise 2: File Copying
Write a Python program that copies the contents of one file into another file.


Exercise 3: Reverse Content
Write a Python program that reads the content of a file and writes it to a new file in reverse order


Exercise 4: Binary File Handling
Write a Python program that opens a binary file (such as an image) and creates a copy of it.


Exercise 5: Character Frequency
Write a Python program that reads a text file and counts the frequency of each character in the file.
Summary
Today, we covered file handling in Python, including:
Opening and closing files using the open() function and context managers.
Reading from and writing to files using methods like read(), write(), and writelines().
Appending data to files using append mode.
Working with binary files for tasks such as handling images.
Handling file exceptions and understanding file positioning with seek() and tell().

Understanding file handling is crucial for many real-world applications, such as logging, data storage, and working with structured data like CSV or JSON files. Keep practicing these concepts, as they are foundational to your development as a Python programmer! Happy coding!
👍1
Day 11: Handling Exceptions in Python
Welcome to Day 11 of the "Noob to Pro in Python" course! Today, we’ll focus on exceptions in Python, learning how to handle errors effectively. Exception handling is crucial for writing robust, error-free programs that behave predictably even when things go wrong. You’ll understand how to catch exceptions, raise errors, and use custom exceptions.
What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts its normal flow. When a Python program encounters an error, it raises an exception, which terminates the program unless the error is handled.


Common built-in exceptions include:
ZeroDivisionError: Raised when dividing by zero.
FileNotFoundError: Raised when a file or directory is requested but doesn't exist.
ValueError: Raised when a function receives an argument of the correct type but inappropriate value.
TypeError: Raised when an operation is performed on an inappropriate type.
Exception Handling with try and except
Python provides the try and except blocks to handle exceptions and prevent program crashes

Basic Syntax:
try:
# Code that might raise an exception
risky_code()
except ExceptionType:
# Code to handle the exception
handle_exception()


Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")


In this example, trying to divide by zero would normally crash the program. Instead, we catch the ZeroDivisionError and print a message.
👍1
Catching Multiple Exceptions
You can catch different types of exceptions and handle them separately by specifying multiple except blocks.

Example:
try:
file = open("non_existent_file.txt", "r")
result = 10 / 0
except FileNotFoundError:
print("File not found!")
except ZeroDivisionError:
print("Cannot divide by zero!")


In this example:
FileNotFoundError is raised if the file does not exist.
ZeroDivisionError is raised if there’s an attempt to divide by zero.
The else Clause
You can use an else clause to define a block of code to be executed if no exceptions are raised in the try block.

Example:
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)


If no exception occurs, the code in the else block will execute.
The finally Clause
The finally block is always executed, regardless of whether an exception occurred or not. It’s commonly used for cleaning up resources, such as closing files or network connections.

Example:
try:
file = open("example.txt", "r")
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always be executed.")
file.close()


Here, the finally block ensures that the file is closed, even if an error occurs during execution.
Raising Exceptions with raise
In Python, you can raise exceptions manually using the raise keyword. This is useful when you want to trigger an exception under specific conditions.

Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above.")
return "Valid age"

try:
check_age(16)
except ValueError as e:
print(e)


In this example, we manually raise a ValueError if the age is below 18.
Custom Exceptions
You can create your own exceptions by subclassing the built-in Exception class. Custom exceptions allow you to define your own error types for more precise control over program flow.

Example:
class InvalidAgeError(Exception):
"""Custom exception for invalid age."""
pass

def check_age(age):
if age < 18:
raise InvalidAgeError("You must be at least 18 years old.")
return "Valid age"

try:
check_age(16)
except InvalidAgeError as e:
print(e)


Here, we define a custom exception called InvalidAgeError and raise it if the age is below 18.
Exception Hierarchy
All exceptions in Python inherit from the base class BaseException. Common exceptions such as ZeroDivisionError, ValueError, and TypeError inherit from Exception, which in turn inherits from BaseException.

Example:
try:
raise ValueError("An error occurred")
except Exception as e:
print("Caught an exception:", e)


The Exception class will catch any standard exception.
👍1
Using assert for Simple Debugging
The assert statement allows you to test if a condition in your code is True. If the condition is False, it raises an AssertionError.

Syntax:
assert condition, message


Example:
age = 15
assert age >= 18, "Age must be 18 or above!"


If the condition fails, an AssertionError is raised with the given message.
Best Practices for Exception Handling

Be specific with exceptions: Catch only the exceptions you expect. Avoid using a generic except Exception for everything.

Clean up resources: Always clean up resources (e.g., files, database connections) using finally or context managers (with).

Avoid silent failures:
Don’t just catch exceptions and do nothing. Always log errors or take meaningful action.

Use custom exceptions for better clarity: When writing large applications, create custom exceptions for more meaningful error reporting.
Practice Exercises for Day 11

Exercise 1: Division by Zero

Write a function that divides two numbers. Use exception handling to catch division by zero and print an appropriate message.

Exercise 2: File Handling with Exceptions
Write a Python program to open a file and read its content. Use exception handling to catch and handle a FileNotFoundError.

Exercise 3: Age Validator
Write a function that checks if a person’s age is valid (age >= 18). Raise a custom exception InvalidAgeError if the age is below 18.

Exercise 4: Password Validation
Write a function that takes a password as input. Raise a ValueError if the password is shorter than 8 characters or doesn't contain a number.

Exercise 5: Custom Exception
Create a custom exception called NegativeNumberError. Write a function that raises this exception if a negative number is passed.
Homework for Day 11

Simple Calculator

Write a Python program that implements a calculator with functions for addition, subtraction, multiplication, and division. Use exception handling to catch invalid inputs and division by zero.


kindly submit your homework at @kidscoderchat with #py_homework
Summary
In Day 11, we covered:

Exceptions: What they are and why they occur.
Handling exceptions using try, except, else, and finally blocks.
Raising exceptions manually with the raise keyword.
Creating custom exceptions to handle specific situations.
The assert statement for simple debugging and validation.

Effective exception handling ensures that your programs can manage unexpected situations without crashing. This is essential for building reliable, maintainable software. Practice these techniques by solving the exercises and applying them in real-world scenarios. Keep coding and refining your skills!
👍2
Day 12: Working with Modules and Packages in Python
Welcome to Day 12 of the "Noob to Pro in Python" course! Today, we will learn about modules and packages in Python. Understanding how to organize your code into modules and packages is crucial for creating maintainable, reusable, and scalable programs. We will also explore Python’s built-in modules and learn how to create your own.
What is a Module?
A module is simply a Python file (with a .py extension) that contains Python code. It may contain functions, classes, variables, and runnable code. Instead of writing all your code in a single file, you can split it into multiple files (modules) and use them in different parts of your project.


Advantages of Modules:
Code organization
Code reuse
Avoids redundancy
Better maintainability

Creating a Simple Module
Let’s create a module named mymodule.py:
# This is a simple module with a function

def greet(name):
return f"Hello, {name}!"

You can then import and use this module in another Python script.

Example of importing and using a module:
import mymodule

print(mymodule.greet("Alice")) # Output: Hello, Alice!