gpt4 book ai didi

Python 2.7 尝试并排除 ValueError

转载 作者:太空狗 更新时间:2023-10-29 17:11:28 24 4
gpt4 key购买 nike

我使用 int(raw_input(...)) 查询预期为 int 的用户输入

然而,当用户没有输入整数时,即只是点击回车,我得到一个 ValueError。

def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
while True:
#Test if valid row col position and position does not have default value
if rangeRows.count(rowPos) == 1 and rangeCols.count(colPos) == 1 and inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
break
else:
print "Either the RowCol Position doesn't exist or it is already filled in."
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
return inputMatrix

我试着变聪明,使用 try 和 except 来捕获 ValueError,向用户打印警告,然后再次调用 inputValue()。然后当用户输入 return 到查询时它会工作但是当用户正确输入整数时它会倒下

下面是修改后的带有try and except的部分代码:

def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
try:
rowPos = int(raw_input("Please enter the row, 0 indexed."))
except ValueError:
print "Please enter a valid input."
inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)
try:
colPos = int(raw_input("Please enter the column, 0 indexed."))
except ValueError:
print "Please enter a valid input."
inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)

最佳答案

一个快速而肮脏的解决方案是:

parsed = False
while not parsed:
try:
x = int(raw_input('Enter the value:'))
parsed = True # we only get here if the previous line didn't throw an exception
except ValueError:
print 'Invalid value!'

这将一直提示用户输入,直到 parsedTrue,这只会在没有异常的情况下发生。

关于Python 2.7 尝试并排除 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5025399/

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