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程序的值错误,但后来发生了。它不仅捕获空输入的值错误,而且如果有人要输入像字母一样的非整数字符,它也会捕获值错误。我希望它同时执行这两个操作,那么如何设置另一个将打印的异常(“请输入一个整数!”)?
该死,我尝试通过添加一些我为该程序提出的其他行来修复该程序,并添加了一个“中断”,但是当我这样做时,我不能错误地说“我”不是定义。现在,如果我将其取出并运行程序,即使用户输入一个整数作为输入,循环也会继续。
答案 0 :(得分: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
。