0

So, I am able to prompt the user for their IP address and check whether it is valid or not, but I cannot seem to figure out how to get this program to ask the user for another IP address if the one entered is invalid. Any help would be great!

import ipaddress 

def validate_ip_address(address):
    while True:
        try:
            ip = ipaddress.ip_address(address)
            print("IP address {} is valid.".format(address, ip))
        except ValueError:
            print("IP address {} is not valid".format(address))
            continue
        else:
            break
ip = input("Enter an ip: ")
validate_ip_address(ip)
Nate
  • 1
  • 2
  • I'm not really sure how to write an if else statement for an IP address – Nate Apr 14 '22 at 16:54
  • There's nothing there that requires an `if` `else` statement. You basically just need to wrap this in a very simple `while` loop. What about the answers in that linked post do you not understand? – Random Davis Apr 14 '22 at 17:11
  • @RandomDavis I tried using a while True but my except just keeps looping on the output. – Nate Apr 14 '22 at 17:24
  • @Nate You need to change the value of `address` in the loop. One way is to move the `input()` call inside your function. – Code-Apprentice Apr 14 '22 at 17:28

1 Answers1

0

With the while loop in place, you are still only requesting input from the user once. You need to request the input inside the while loop to allow the user to try again.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268