gpt4 book ai didi

python - 错误异常处理python程序

转载 作者:行者123 更新时间:2023-12-03 08:57:31 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com