Raising Exceptions with
In Python, you can
Example:
In this example, we manually raise a
raiseIn 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
Example:
Here, we define a custom exception called
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
Example:
The
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
Syntax:
Example:
If the condition fails, an
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
Clean up resources: Always clean up resources (e.g., files, database connections) using
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.
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
Exercise 3: Age Validator
Write a function that checks if a person’s age is valid (age >= 18). Raise a custom exception
Exercise 4: Password Validation
Write a function that takes a password as input. Raise a
Exercise 5: Custom Exception
Create a custom exception called
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
kindly submit your homework at @kidscoderchat with #py_homework
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
Raising exceptions manually with the
Creating custom exceptions to handle specific situations.
The
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!
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?
Advantages of Modules:
Code organization
Code reuse
Avoids redundancy
Better maintainability
Creating a Simple Module
Let’s create a module named
You can then import and use this module in another Python script.
Example of importing and using 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!
Importing Modules
There are several ways to import modules in Python:
1. Import the entire module:
Access the module’s functions or variables using
2. Import specific functions or variables:
In this case, you can directly use the
3. Import with an alias:
4. Import everything from a module:
This imports all functions and variables from the module. Use this carefully to avoid name conflicts.
There are several ways to import modules in Python:
1. Import the entire module:
import mymodule
Access the module’s functions or variables using
mymodule.function_name().2. Import specific functions or variables:
from mymodule import greet
In this case, you can directly use the
greet() function without the module prefix.3. Import with an alias:
import mymodule as mm
print(mm.greet("Bob")) # Output: Hello, Bob!
4. Import everything from a module:
from mymodule import *
This imports all functions and variables from the module. Use this carefully to avoid name conflicts.
Exploring Built-in Modules
Example: Using the
Example: Using the
Example: Using the
Python comes with a wide range of built-in modules that provide functionality for common tasks. Some popular built-in modules include:
math: Mathematical functionsrandom: Random number generationdatetime: Working with dates and timesos: Interacting with the operating systemsys: System-specific parameters and functionsExample: Using the
math Moduleimport math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
Example: Using the
random Moduleimport random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
Example: Using the
datetime Moduleimport datetime
now = datetime.datetime.now()
print(now) # Output: Current date and time
What is a Package?
A package is a collection of modules organized in directories that provide a hierarchical structure. Packages allow you to organize your project into multiple modules and sub-packages.
Creating a Package
A package is simply a directory that contains one or more modules and a special file named __init__.py. The __init__.py file is required to make Python treat the directory as a package. It can be empty or contain initialization code for the package.
Package Structure:
Example: Creating a Package
1. Create a directory named
2. Inside the directory, create the following files:
3. Now you can import the package modules in your Python code:
Example:
A package is a collection of modules organized in directories that provide a hierarchical structure. Packages allow you to organize your project into multiple modules and sub-packages.
Creating a Package
A package is simply a directory that contains one or more modules and a special file named __init__.py. The __init__.py file is required to make Python treat the directory as a package. It can be empty or contain initialization code for the package.
Package Structure:
mypackage/
__init__.py
module1.py
module2.py
Example: Creating a Package
1. Create a directory named
mypackage.2. Inside the directory, create the following files:
mypackage/__init__.py:# This is the initialization file for the package
mypackage/module1.py:def add(a, b):
return a + b
mypackage/module2.py:def subtract(a, b):
return a - b
3. Now you can import the package modules in your Python code:
Example:
from mypackage import module1, module2
print(module1.add(10, 5)) # Output: 15
print(module2.subtract(10, 5)) # Output: 5
❤1
Installing and Using External Packages (PIP)
Python has a huge collection of third-party packages available via the Python Package Index (PyPI). You can install these packages using the
Installing a Package with PIP
To install an external package, use the command:
Example: Installing and Using the
Once installed, you can use the
This will print the JSON response from the given URL.
Python has a huge collection of third-party packages available via the Python Package Index (PyPI). You can install these packages using the
pip tool.Installing a Package with PIP
To install an external package, use the command:
pip install package_name
Example: Installing and Using the
requests Librarypip install requests
Once installed, you can use the
requests module to make HTTP requests:import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json())
This will print the JSON response from the given URL.
Finding and Installing External Packages
To find packages:
- Visit the Python Package Index (PyPI) to browse and search for Python packages.
To install a package globally (available for all projects):
To install a package locally in a virtual environment:
1. Create a virtual environment:
2. Activate the virtual environment:
3. Install the package:
To find packages:
- Visit the Python Package Index (PyPI) to browse and search for Python packages.
To install a package globally (available for all projects):
pip install package_name
To install a package locally in a virtual environment:
1. Create a virtual environment:
python -m venv myenv
2. Activate the virtual environment:
# Windows
myenv\Scripts\activate
# Mac/Linux
source myenv/bin/activate
3. Install the package:
pip install package_name
Managing Dependencies with
In larger projects, you may want to specify which external packages (dependencies) your project needs. This is typically done using a
Creating
You can automatically generate this file with the following command:
This command lists all installed packages and their versions in the
Installing Dependencies from
To install all the packages listed in a
requirements.txtIn larger projects, you may want to specify which external packages (dependencies) your project needs. This is typically done using a
requirements.txt file.Creating
requirements.txtYou can automatically generate this file with the following command:
pip freeze > requirements.txt
This command lists all installed packages and their versions in the
requirements.txt file.Installing Dependencies from
requirements.txtTo install all the packages listed in a
requirements.txt file, use the following command:pip install -r requirements.txt
Practice Exercises for Day 12
Exercise 1: Simple Module
Create a Python module with functions for addition, subtraction, multiplication, and division. Import the module in another script and use its functions.
Exercise 2: Math and Random Modules
Use the built-in
Exercise 3: Package Creation
Create a package with two modules: one for basic math operations (addition, subtraction) and one for advanced operations (power, square root). Import these modules in a script and use their functions.
Exercise 4: External Package
Install the
Exercise 5: Virtual Environment
Create a virtual environment, activate it, install the
Exercise 1: Simple Module
Create a Python module with functions for addition, subtraction, multiplication, and division. Import the module in another script and use its functions.
Exercise 2: Math and Random Modules
Use the built-in
math and random modules to generate random numbers and calculate their square roots.Exercise 3: Package Creation
Create a package with two modules: one for basic math operations (addition, subtraction) and one for advanced operations (power, square root). Import these modules in a script and use their functions.
Exercise 4: External Package
Install the
requests module using pip and write a Python script to fetch and display data from a public API (e.g., a list of posts from JSONPlaceholder).Exercise 5: Virtual Environment
Create a virtual environment, activate it, install the
requests module, and use it in a Python script.👍1
Summary
In Day 12, we covered:
Modules: How to create and import modules to organize your code.
Packages: Organizing multiple modules into packages for better structure.
Built-in modules: Using standard Python modules like
PIP: Installing external packages and managing project dependencies with
Virtual environments: Isolating dependencies for different projects.
Mastering modules and packages is essential for writing scalable and maintainable Python programs. It helps in organizing code, avoiding repetition, and using reusable components. Keep practicing to solidify your understanding!
In Day 12, we covered:
Modules: How to create and import modules to organize your code.
Packages: Organizing multiple modules into packages for better structure.
Built-in modules: Using standard Python modules like
math, random, and datetime.PIP: Installing external packages and managing project dependencies with
requirements.txt.Virtual environments: Isolating dependencies for different projects.
Mastering modules and packages is essential for writing scalable and maintainable Python programs. It helps in organizing code, avoiding repetition, and using reusable components. Keep practicing to solidify your understanding!
❤2
Day 13: Object-Oriented Programming (OOP) - Classes and Objects
Welcome to Day 13 of the "Noob to Pro in Python" course! Today, we’ll dive into Object-Oriented Programming (OOP), a powerful paradigm in Python. OOP helps in structuring programs using objects, which can contain both data and methods. We'll begin with understanding classes and objects, which are the foundation of OOP.
Welcome to Day 13 of the "Noob to Pro in Python" course! Today, we’ll dive into Object-Oriented Programming (OOP), a powerful paradigm in Python. OOP helps in structuring programs using objects, which can contain both data and methods. We'll begin with understanding classes and objects, which are the foundation of OOP.
❤1
Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that focuses on using objects and classes. In OOP:
A class is a blueprint for creating objects.
An object is an instance of a class.
Key Concepts of OOP:
Class: A blueprint for creating objects.
Object: An instance of a class.
Attributes: Data (variables) stored in an object.
Methods: Functions that are defined inside a class and describe the behavior of the objects.
Instantiation: The process of creating an object from a class.
Object-Oriented Programming (OOP) is a programming paradigm that focuses on using objects and classes. In OOP:
A class is a blueprint for creating objects.
An object is an instance of a class.
Key Concepts of OOP:
Class: A blueprint for creating objects.
Object: An instance of a class.
Attributes: Data (variables) stored in an object.
Methods: Functions that are defined inside a class and describe the behavior of the objects.
Instantiation: The process of creating an object from a class.