如何检测python程序中是否未给出输入

时间:2017-09-17 02:12:04

标签: python

我有一个python程序,它提示用户输入位置或索引,并根据位置或索引删除列表中的元素。 python程序有效,但我遇到的问题是如果没有给出用户输入,它会自动删除列表中的整行。

示例:

lst = [1,2,3,4,5]
enter position: 2

output: [1,2,4,5]

enter position: #user just pressed enter without giving any input

output: []

我正在一个类中编写函数:

def delete(self,index):
    """
    This function deletes an item based on the index
    :param self: the array
    :param index: the index of an item in the array
    :return: the array is updated
    :raises: IndexError if out of range
    """
    if not index:
        self.__init__()
    if index<0:
        index = index + self.count
    for i in range(index, self.count -1):
        self._array[i] = self._array[i+1]
    self.count-=1

并提示用户输入如下:

position = int(input("Enter position:"))

由于位置只接收整数,因此我无法按“输入”而不会收到错误因此我正在寻找一种方法,如果用户没有给出任何位置,它会注册它并打印一个空的列表而不是错误消息。

1 个答案:

答案 0 :(得分:1)

您正在寻找的是try - except阻止。请参阅以下示例:

input_invalid = true
while input_invalid:
    user_input = input("Enter position: ")
    try:
        user_input = int(user_input)
        input_invalid = false
    except ValueError:
        print("Please enter a valid integer!")

此处,try - except块捕获任何错误(指定类型的错误) 在except)中抛出代码块。在这种情况下,尝试在不包含整数(int())的字符串上调用ValueError会导致错误。您可以使用它来明确地防止错误并控制程序的逻辑流程,如上所示。

不使用try - except的替代解决方案是使用.isdigit()方法预先验证数据。如果您使用.isdigit()(我个人认为更好),您的代码将如下所示:

input_invalid = true
while input_invalid:
    user_input = input("Enter position: ")
    if user_input.isdigit():
        input_invalid = false
    else:
        print("Please enter a valid integer!")

希望这有帮助!