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”。现在,如果我取出它并运行程序,即使用户输入整数作为输入,循环仍将继续。
最佳答案
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
。
关于python - 错误异常处理python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579926/