0
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: "))
        except ValueError:
                print("Empty input!")
        break
if(words[i]):
        print("The length of the word is: " , len(words[i]))

因此,我能够捕捉到我目前正在执行的 Hangman 程序的值错误,但后来它发生在我身上。它不仅捕获空输入的值错误,而且如果有人要输入非整数字符(如字母),它也会捕获值错误。我希望它两者都做,那么如何设置另一个将打印(“请输入整数!”)的异常?

该死,我尝试通过添加我为程序想到的其他几行来修复程序,并且我添加了一个“break”但是当我这样做时,我不能出现一个错误,指出“i”未定义。现在,如果我把它拿出来运行程序,即使用户输入一个整数作为输入,循环也会继续。

4

1 回答 1

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

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

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

    if i in (None, ""):
        print("Null input")
        continue

    try:
        i = int(i)
    except ValueError:
        print("Not valid integer")
        continue
    else:
        if not 0 <= i < 10:
            print("not in valid range of 0<=number<10")
            continue

    break

print("You have entered", i)
print("The word you have chosen is {} letters long".format(words[i]))

input()函数返回一个字符串。如果您想先执行更多检查,则公然将其转换为int()立即可能不是正确的做法。这首先检查它是否为空字符串,然后通过尝试将其转换为整数来检查它是否为整数int(),然后检查该整数是否在有效范围内。在此结束时,i剩余的有效整数。

于 2013-10-25T02:07:19.077 回答