处理在Hangman python程序中的错误和异常 [英] Handling errors and exceptions in Hangman python program

查看:126
本文介绍了处理在Hangman python程序中的错误和异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print("Welcome to Hangman! Guess the mystery word with less than 6 mistakes!")

words= ['utopian','fairy','tree','monday','blue'] 

while True:
        try:
                i=int(input("Please enter an integer number (0<=number<10) to choose the word in the list: "))
            break





        except ValueError:
                if(i!=int):
                        print("Must be an integer input.")
                else:
                        print("Empty input.")

处理我的Hangman程序中的异常,再次遇到另一个问题。你可以运行这个程序,看看我出错了。我想要值错误是具体的,在我有一个这样的代码之前:
除了ValueError:
print(Value error!)
但现在我想要它是特定于什么错误是。所以如果用户输入一个空的输入,我希望程序告诉他们他们打印了一个空字符串。如果他们输入一个字母顺序的字母,我想特别来看这个错误。当我们在它的时候,如果他们从列表范围中输入一个整数,我想要有一个捕获的索引错误。

Getting into handling exceptions on my Hangman program and once again I've come across another problem. You can run this program and see where I went wrong. I want the value error to be specific, before I had a code like this: except ValueError: print("Value error!") But now I want it to be specific to what the error is. So if the user enters an empty input, I want the program to tell them that they printed an empty string. If they entered a alphabetical letter, I want to catch that error specifically. Hell while we're at it, if they enter an integer out of the list range I want to there to be a caught index error.

推荐答案

要检查 i 是否为空,我会先做:

To check if i is empty, I would first do:

answer = input()  # Save the raw answer

if answer in (None, ''):
    print('Value was empty!')
    continue

然后你可以尝试把它变成一个整数:

Then you can try turning it into an integer:

try:
    i = int(answer)
except ValueError:
    print('Your answer was not an integer')
    continue

最后,要检查 i 是否在您的单词列表中,您可以轻松地执行以下操作:

Finally, to check if i is in your list of words, you can easily do:

try:
    word = words[i]
except IndexError:
    print("Value was out of range!)
else:
    return word

将所有内容保存在一个函数中,您可以使用返回字像我这样做很容易退出你的而True 循环,而不是担心破裂。

Stick all of that in a function, and you can use return word like I did to easily exit out of your while True loop, rather than worrying about breaking.

这篇关于处理在Hangman python程序中的错误和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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