退出无限循环并处理错误情况

发布于 2024-12-28 10:54:54 字数 740 浏览 0 评论 0原文

我是Python新手。在这里,我编写了一个从地图中检索值的 Python 程序。 截至目前,一切正常。

当用户输入“M”时,它将检索它会询问主号码,并再次要求用户输入,并且根据用户输入,它从字典和字典中检索值。很快。

现在我关心的是

  1. 如何退出循环。
  2. 如果我在要求 M/N 时输入无效怎么办?
  3. 如果当它询问 Main 或 Name 时我给它一个无效的输入怎么办?

谁能帮我解决这个问题吗?我想知道如何实现上述3个条件。我用Java实现了这些条件,但不知道如何用Python实现。

streetno={"1":"Sachin Tendulkar","2":"Sehwag","3":"Dravid","4":"Dhoni","5":"Kohli"}
streetname = dict((y,x) for x,y in streetno.items())
while True:
    inp= raw_input('Enter a M/N:')
    if inp=="M" or inp=="m":
        key=raw_input( "Enter the main number :")
        result=streetno[key]

    else:
        key = raw_input("Enter the street name: ")
        result = streetname[key]


    print result

I'm new to Python. Here I've written a Python program which retrieves values from the map.
As of now it's working fine.

When user enters "M" it will retrieve it will ask for main no and again it asks for user input and the depending on the user input it retrieves values from the dictionary & so on.

Now my concern is

  1. How can I exit from the loop.
  2. What if I give an invalid input when it asks for M/N?
  3. What if I give it an invalid input when it asks for Main or Name?

Can anyone help me with this?? I want to know How to implement above 3 conditions. I implemented these conditions in Java and I don't know how to do it in Python.

streetno={"1":"Sachin Tendulkar","2":"Sehwag","3":"Dravid","4":"Dhoni","5":"Kohli"}
streetname = dict((y,x) for x,y in streetno.items())
while True:
    inp= raw_input('Enter a M/N:')
    if inp=="M" or inp=="m":
        key=raw_input( "Enter the main number :")
        result=streetno[key]

    else:
        key = raw_input("Enter the street name: ")
        result = streetname[key]


    print result

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等你爱我 2025-01-04 10:54:54

1:您可以使用 break 跳出 for 或 while 循环。

2/3:考虑这些例外情况。我们无法真正告诉您如何处理异常,因为这取决于您想要什么,但这里有一种帮助您开始的方法。

while True:
    inp = raw_input('Enter a M/N or Q to quit:')

    if inp.lower() == 'q':
        break

    if inp.lower() == "m":
        key = raw_input("Enter the main number :")
        try:
            print(streetno[key])
        except KeyError:
            print("You picked an invalid street number")

    elif inp.lower() == 'n':
        key = raw_input("Enter the street name: ")
        try:
            print(streetname[key])
        except KeyError:
            print("You picked an invalid street name")

    else:
        print("{0} is an invalid choice.".format(inp))

1: You can break out of a for or while loop with break.

2/3: Account for those exceptions. We can't really tell you how to deal with exceptions since it depends on what you want, but here's one way to get you started..

while True:
    inp = raw_input('Enter a M/N or Q to quit:')

    if inp.lower() == 'q':
        break

    if inp.lower() == "m":
        key = raw_input("Enter the main number :")
        try:
            print(streetno[key])
        except KeyError:
            print("You picked an invalid street number")

    elif inp.lower() == 'n':
        key = raw_input("Enter the street name: ")
        try:
            print(streetname[key])
        except KeyError:
            print("You picked an invalid street name")

    else:
        print("{0} is an invalid choice.".format(inp))
泛泛之交 2025-01-04 10:54:54

通常,您会使用 Try/Except 块捕获异常。请参阅本教程链接。如果您输入不正确的主名称或名称,则会引发 KeyError,因为字典没有匹配的键。您的 except 块将捕捉到这一点,您可以使用“继续”重新启动提示。最后,要退出循环,您需要一个触发器,例如输入“Q”作为 elif 选项退出。要退出循环,您可以调用 break

Generally you would catch exceptions with a Try/Except block. See this tutorial, link. If you enter an incorrect main or name, a KeyError will be raised since the dicts do not have a matching key. Your Except blocks will catch this and you can restart the prompt with a 'continue'. Finally, to exit the loop you need a trigger, like entering a 'Q' to quit as an elif option. To exit a loop you'd call break.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文