Handling errors and exceptions in Hangman python program

喜你入骨 提交于 2019-12-11 21:20:10

问题


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.")

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.


回答1:


i is not defined in the except block. You should check whether the user entered nothing before you try to parse the integer:

user_input = input("message")
if not user_input:
    print("Empty input.")
else:
    try:
        i = int(user_input)
        break
    except ValueError:
        print("Must be an integer input.")



回答2:


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

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

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.



来源:https://stackoverflow.com/questions/19576384/handling-errors-and-exceptions-in-hangman-python-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!