我正在尝试在一个简单的min-max程序中验证用户输入。我有多个输入的整数,我正在尝试为所有输入的值使用一个if语句,如果它不是整数,则输出错误消息。当我尝试它的设置方式时,我可以输入整数和非整数,它最终会出错,说:
if(数字1、数字2、数字3、数字4、数字5(.idigit((:
AttributeError:"tuple"对象没有属性"isdigit">
以下是完整的代码。
# Print welcome message
print('Please enter five integers to find the minimum and maximum values.')
# Take 5 numbers from user and convert that to integer and store in variables
validInteger = False
while not validInteger:
number1 = input('Enter your first integer: ')
number2 = input('Enter your second integer: ')
number3 = input('Enter your third integer: ')
number4 = input('Enter your fourth integer: ')
number5 = input('Enter your fifth integer: ')
if (number1, number2, number3, number4, number5).isdigit():
validInteger = True
else:
print('Please enter an integer I.E. 13.')
# Call max function to calculate max value
max =max(number1,number2,number3,number4,number5)
# Call min function to calculate min value
min = min(number1,number2,number3,number4,number5)
# Print max number
print('Max value is: ' + str(max))
# Print min number
print('Min value is: ' + str(min))
您应该使用:
if all(x.isdigit() for x in (number1, number2, number3, number4, number5)):
validInteger = True
为什么会出现错误
(number1, number2, number3, number4, number5)
形成元组,元组没有isdigit()
方法:
>>> type((number1, number2, number3, number4, number5))
<class 'tuple'>
isdigit()
是字符串的一种方法。
>>> 'abc'.isdigit()
False
>>> '123'.isdigit()
True
您需要依次对每个输入字符串调用isdigit()
方法:
if all(n.isdigit() for n in [number1, number2, number3, number4, number5]):
validInteger = True
all()
函数检查结果,如果结果都是True
,则返回True
。