Issue
The problem I'm trying is cs50's introduction to programming with python problem set 7 numb3rs problem, wherein I need to check if the Ip address entered is a valid Ip address or not. The thing is check50 gives me three error messages that I do not understand. These are the three errors:
:( correct numb3rs.py passes all test_numb3rs.py checks
expected exit code 0, not 1
:| test_numb3rs.py catches numb3rs.py only checking if first byte of IPv4 address is in range
can't check until a frown turns upside down
:| test_numb3rs.py catches numb3rs.py accepting expecting five-byte IPv4 address
can't check until a frown turns upside down
import re
def main():
print(validate(input("IPv4 Address: ")))
def validate(ip):
address = "(0|[1-9]|[1-9][0-9]|[1-2][0-5][0-5]|1[0-9][0-9]|2[0-4][0-9])"
if re.search(fr'^{address}\.{address}\.{address}\.{address}$', ip):
return "True"
else:
return "False"
if __name__ == "__main__":
main()
This is the code. I tried using sys to exit the program after print but that does not work. I also tried returning True and False as bools but that also didn't work. I also did a test_numb3rs.py as the problem asked for it and checked everything(All bytes, if user input was not an Ip address, and so on).
Solution
here are my codes, and i pass all the tests:
import re
def main():
print(validate(input("IPv4 Address: ")))
def validate(ip):
if re.search(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$", ip):
list_of_numbers = ip.split(".")
for number in list_of_numbers:
if int(number) < 0 or int(number) > 255:
return False
return True
else:
return False
if __name__ == "__main__":
main()
and the test_numb3rs.py:
from numb3rs import validate
def main():
test_format()
test_range()
def test_format():
assert validate(r"1.2.3.4")==True
assert validate(r"1.2.3")==False
assert validate(r"1.2")==False
assert validate(r"1")==False
def test_range():
assert validate(r"255.255.255.255")==True
assert validate(r"512.1.1.1")==False
assert validate(r"1.512.1.1")==False
assert validate(r"1.1.512.1")==False
assert validate(r"1.1.1.512")==False
if __name__ == "__main__":
main()
Answered By - Othniel Jean
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.