Search code examples
inputwhile-loopinfinite-loopserversocket

Stay in while loop after an exception


I want the user to stay in a while loop by entering an ip address to be looked up, they can stay looking up the ip when prompted if they want to proceed by typing y or n, upon the exception which occurs often because not all IP addresses are found I was getting an infinite loop so I just had it break out of the loop for now. How can I continue after the exception to ask the user if they would like to look up another IP rather than breaking out of the loop? Thanks.

import socket

print("\n----------Look up Domain by IP Address----------\n")

response3 = input("Enter an IP Address: ")

while True:
    try:
        domain = socket.gethostbyaddr(response3)[0]#.split(".")[1]
        print("\nDomain Name is", domain)

    except(socket.error):
        print("\nA domain name could not be found.")
        break

    response4 = input("Would you like to look up another IP adress? type y for [yes] or n for [no]: ")            

    if response4 == "y":

        response3 = input("Enter an IP Address: ")

    elif response4 == "n":
        print("\n[END]")
        break  

Solution

  • Don't use [break], [break] means jumping out the loop. Use [continue] to start the next step of the loop.

    If you want to continue to the second [try] in the first [try], the [break] in the first [try] could be changed to [pass], which means Do nothing.