Practice Exercises for Day 9
Exercise 1: Create a Simple Module
Create a module called
Exercise 2: Using Standard Library Modules
Write a Python program that calculates the area of a circle using the
Exercise 3: Directory Operations with the
Write a Python script that uses the
Exercise 4: Custom Package
Create a package called
Exercise 5: Exploring
Write a Python program to generate a random password of 8 characters using the
Exercise 1: Create a Simple Module
Create a module called
temperature.py that contains two functions: celsius_to_fahrenheit() and fahrenheit_to_celsius(). Import this module and use it in another program to convert temperatures.Exercise 2: Using Standard Library Modules
Write a Python program that calculates the area of a circle using the
math module.Exercise 3: Directory Operations with the
os ModuleWrite a Python script that uses the
os module to list all files in the current directory and create a new directory called "TestFolder".Exercise 4: Custom Package
Create a package called
math_operations with two modules: basic.py and advanced.py. In basic.py, create functions for basic arithmetic operations (add, subtract, multiply, divide), and in advanced.py, create functions for operations like exponentiation and square root. Write a script that uses this package.Exercise 5: Exploring
random ModuleWrite a Python program to generate a random password of 8 characters using the
random module.๐1
Summary
In Day 9, we explored the following topics:
Modules: Files containing Python code that can be imported and reused.
Standard Library Modules: Common built-in modules like
Packages: Directories containing multiple related modules, which allow for better organization of your code.
Modules and packages are essential to writing maintainable Python code and help you tap into Pythonโs vast ecosystem of libraries and tools. With these skills, youโll be able to write modular and reusable code that scales well as your projects grow
In Day 9, we explored the following topics:
Modules: Files containing Python code that can be imported and reused.
Standard Library Modules: Common built-in modules like
math, datetime, os, and random.Packages: Directories containing multiple related modules, which allow for better organization of your code.
pip: Pythonโs package installer for managing third-party libraries.dir() and help(): Useful functions for exploring modules and getting documentation.Modules and packages are essential to writing maintainable Python code and help you tap into Pythonโs vast ecosystem of libraries and tools. With these skills, youโll be able to write modular and reusable code that scales well as your projects grow
๐2
Introduction to File Handling
Python provides built-in functions to work with files. The most common operations include:
Opening a file:
Reading from a file:
Writing to a file:
Closing a file:
Syntax:
The
'
'
'
'
'
'
Python provides built-in functions to work with files. The most common operations include:
Opening a file:
open()Reading from a file:
read(), readline(), readlines()Writing to a file:
write(), writelines()Closing a file:
close()Syntax:
file = open("filename", "mode")The
mode defines how the file will be opened:'
r': Read (default mode, raises an error if the file does not exist)'
w': Write (creates a new file if it does not exist, overwrites existing content)'
a': Append (creates a new file if it does not exist, appends to existing content)'
x': Create (creates a new file, raises an error if the file exists)'
b': Binary mode (e.g., 'rb' for reading binary files)'
t': Text mode (default mode, used for reading/writing text files)๐2
Opening and Closing Files
Opening a File
To open a file, use the
Example:
This will open the file
Closing a File
Itโs good practice to close a file after you are done with it using the
Alternatively, you can use the
Example:
Opening a File
To open a file, use the
open() function.Example:
file = open("example.txt", "r")This will open the file
example.txt in read mode ('r').Closing a File
Itโs good practice to close a file after you are done with it using the
close() method. This frees up system resources.file.close()
Alternatively, you can use the
with statement to automatically close the file after the block of code is executed.Example:
with open("example.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed after the block๐2
Reading from a File
Python provides several methods to read the contents of a file.
Reads the entire content of a file as a single string.
Example:
Reads one line at a time from the file.
Example:
Reads all lines of a file and returns them as a list of strings.
Example:
Python provides several methods to read the contents of a file.
read() MethodReads the entire content of a file as a single string.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content) # Prints the entire file contentreadline() MethodReads one line at a time from the file.
Example:
with open("example.txt", "r") as file:
line = file.readline()
print(line) # Prints the first line of the filereadlines() MethodReads all lines of a file and returns them as a list of strings.
Example:
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines) # Prints all lines in a list๐2โค1
Writing to a File
To write content to a file, you can use the
The write() method writes a string to the file.
Example:
The
Example:
To write content to a file, you can use the
write() or writelines() methods. Opening a file in write ('w') mode will create the file if it doesnโt exist or overwrite it if it does.write() MethodThe write() method writes a string to the file.
Example:
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a Python program.\n")writelines() MethodThe
writelines() method takes a list of strings and writes them to the file.Example:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
๐3โค1
Appending to a File
When you want to add content to the end of an existing file without overwriting it, you can use the append mode ('
Example:
When you want to add content to the end of an existing file without overwriting it, you can use the append mode ('
a').Example:
with open("output.txt", "a") as file:
file.write("This line will be appended.\n")โค1๐1
Working with Binary Files
In addition to text files, you can also work with binary files such as images, videos, and executables by opening the file in binary mode ('
Reading a Binary File
Example:
Writing to a Binary File
Example:
In addition to text files, you can also work with binary files such as images, videos, and executables by opening the file in binary mode ('
b').Reading a Binary File
Example:
with open("image.jpg", "rb") as file:
binary_content = file.read()
print(binary_content) # Outputs the binary content of the imageWriting to a Binary File
Example:
with open("new_image.jpg", "wb") as file:
file.write(binary_content) # Writes binary content to a new file๐2โค1
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
Example:
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:
Example:
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
Exercise 2: File Copying
Exercise 3: Reverse Content
Exercise 4: Binary File Handling
Exercise 5: Character Frequency
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
Reading from and writing to files using methods like
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
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!
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?
Common built-in exceptions include:
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
Python provides the
Basic Syntax:
Example:
In this example, trying to divide by zero would normally crash the program. Instead, we catch the
try and exceptPython provides the
try and except blocks to handle exceptions and prevent program crashesBasic 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
Example:
In this example:
FileNotFoundError is raised if the file does not exist.
ZeroDivisionError is raised if thereโs an attempt to divide by zero.
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
You can use an
Example:
If no exception occurs, the code in the
else ClauseYou 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
The
Example:
Here, the
finally ClauseThe
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
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