当我在我的数组中插入一个字符串时,我希望发生的是它拒绝字符串并给出一条消息,解释如何只允许在数组中使用整数。而是重复之前插入的整数。
import sys
ArrayWidth = 9
mmWidth = 22
ArrayDivider = '=' * 33
ArrayDivider = ArrayDivider.center(ArrayWidth)
mmDivider = '=' * 28
mmDivider = mmDivider.center(mmWidth)
MaxAndMin = 'Maximum & Minimum'
MaxAndMin = MaxAndMin.center(mmWidth)
Array = 'Array'
Array = Array.center(ArrayWidth)
Numbers = []
while True:
NumberInput = input('Enter a whole number (Exit the loop by pressing "0"): ')
try:
NumberInput2 = int(NumberInput)
if NumberInput2 == 0:
break
if NumberInput2 <= 0:
print('Please enter a number greater then 0.');
continue;
except ValueError:
print("Error. Non-numeric data was entered.")
except:
print("Error with input...")
Numbers.append(NumberInput2)
print('\n'+ArrayDivider+Array+ArrayDivider)
print(sorted(Numbers, key=int),'\n')
print(mmDivider+MaxAndMin+mmDivider)
print('Maximum Number = {}'.format(max(Numbers)))
print('Minimum Number = {}'.format(min(Numbers)))
答案 0 :(得分:3)
无论是否抛出异常,您都会Numbers.append(NumberInput2)
。当int
提升ValueError
时,NumberInput2
不会被重新分配并保留旧值。
试试这个:
while True:
NumberInput = input('Enter a whole number (Exit the loop by pressing "0"): ')
try:
NumberInput2 = int(NumberInput)
if NumberInput2 == 0:
break
if NumberInput2 <= 0:
print('Please enter a number greater then 0.');
continue
Numbers.append(NumberInput2)
except ValueError:
print("Error. Non-numeric data was entered.")
except:
print("Error with input...")
或者,您可以在打印错误消息后continue
,就像使用非正输入一样。