REPL演示
好吧,因为输入将被解析为字符串,int只能将数字字符串强制为整数。。。如果输入错误,你就麻烦大了,因为它会立即停止你的程序。在
我建议使用while循环和try-except异常语句进行错误处理。在
python2.x注意事项:使用raw_input,因为如果传递没有字符串引号的字符,input将导致NameError: name is not defined。在>>> my_array = [] # camelCase is not the convention in Python
>>>
>>> array_length = None
>>> while array_length is None:
... try:
... array_length = int(input("Please enter the length of array you wish to create: "))
... except ValueError:
... print("Invalid input - please enter a finite number for the array length.")
...
Please enter the length of array you wish to create: 4
>>>
>>> print(array_length)
4
>>> while len(my_array) < array_length:
... try:
... my_array.append(int(input()))
... except ValueError:
... print("Invalid input - please enter a number!")
...
1
abc
Invalid input - please enter a number!
2
3
4
>>>
>>> print(my_array)
[1, 2, 3, 4]
作为脚本运行
^{pr2}$
在我的控制台中运行:$ python3 input-program.py
Please enter the length of array you wish to create: 4
Your array length is 4.
1
2
3
4
Your array is [1, 2, 3, 4]