异常后停留在while循环中 [英] Stay in while loop after an exception

查看:54
本文介绍了异常后停留在while循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户通过输入要查找的 ip 地址来保持在 while 循环中,当提示他们是否要通过键入 y 或 n 继续查找时,他们可以继续查找 ip,因为经常发生的异常是因为并非所有的 IP 地址都被找到我遇到了一个无限循环,所以我现在只是让它跳出循环.如何在异常之后继续询问用户是否要查找另一个 IP 而不是跳出循环?谢谢.

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  

推荐答案

不要使用 [break],[break] 表示跳出循环.使用 [continue] 开始循环的下一步.

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

如果想继续第一个[try]中的第二个[try],可以将第一个[try]中的[break]改为[pass],即Do nothing.

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.

这篇关于异常后停留在while循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆