1

当我在我的数组中插入一个字符串时,我期望发生的是它拒绝该字符串并给出一条消息,解释如何只允许在数组中使用整数。而是重复之前插入的整数。

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)))
4

1 回答 1

3

Numbers.append(NumberInput2)无论是否引发异常,您都会这样做。当intraises时ValueErrorNumberInput2不会重新分配并保留旧值。

尝试这个:

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在打印错误消息后,就像您对非肯定输入所做的那样。

于 2013-03-20T19:49:29.767 回答