This Python program is an implementation to CS50’s Introduction to Programming with Python Week 7 - NUMB3RS Problem Set. The numb3rs.py
program provides a way to validate IPv4 addresses. Here's how to use the program and understand its implementation.
-
Open your terminal.
-
Navigate to the directory where you have saved the
numb3rs.py
file.cd path/to/your/directory
-
Run the program using the
python
command:python numb3rs.py
-
The program will prompt you to enter an IPv4 address. Enter the address and press Enter.
-
The program will output whether the entered IPv4 address is valid or not.
The numb3rs.py
program uses the re
module to validate the input IPv4 address. It follows these steps:
-
The
matches()
function uses there.search()
function to search for a pattern that matches an IPv4 address. It returns the matched pattern if found, otherwise, it returnsNone
. -
The
validate()
function first calls thematches()
function to get the matched pattern of the input IPv4 address. -
If the matched pattern is not
None
, the function splits the pattern into four parts using the dot separator and attempts to convert each part to an integer. -
The function checks if each part of the IPv4 address is within the valid range of 0 to 255. If all parts are valid, the function returns
True
, indicating a valid IPv4 address. -
If the input IPv4 address does not match the pattern or any of its parts are not within the valid range, the function returns
False
.
- Follow the steps mentioned in the "How to Run the Program" section to run the
numb3rs.py
program. - Enter different IPv4 addresses, both valid and invalid, to see how the program validates them.
The test_numb3rs.py
file contains test cases to ensure the correctness of the numb3rs.py
program. The pytest
framework is used to run these test cases. The test cases include scenarios for valid and invalid IPv4 addresses, as well as some edge cases.
To run the test cases, execute the following command in your terminal:
pytest test_numb3rs.py
This will execute the test cases defined in the test_numb3rs.py
file and display the results.
- The program provides a basic validation for IPv4 addresses based on their format and the range of each part.
- The
re
module is used to perform regular expression matching, which helps to identify patterns in the input string. - The
pytest
framework simplifies the process of writing and running test cases to ensure the functionality of the program. It's important to write comprehensive test cases to cover various scenarios.pip install pytest
- The
AttributeError
handling is used in thematches()
function to handle cases wherere.search()
returnsNone
. - The program only validates IPv4 addresses, not IPv6 addresses.