退出无限循环并处理错误情况
我是Python新手。在这里,我编写了一个从地图中检索值的 Python 程序。 截至目前,一切正常。
当用户输入“M”时,它将检索它会询问主号码,并再次要求用户输入,并且根据用户输入,它从字典和字典中检索值。很快。
现在我关心的是
- 如何退出循环。
- 如果我在要求 M/N 时输入无效怎么办?
- 如果当它询问 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
- How can I exit from the loop.
- What if I give an invalid input when it asks for M/N?
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1:您可以使用
break
跳出 for 或 while 循环。2/3:考虑这些例外情况。我们无法真正告诉您如何处理异常,因为这取决于您想要什么,但这里有一种帮助您开始的方法。
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..
通常,您会使用 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.