Home > front end >  Check if elements in list are integers and bigger than 0
Check if elements in list are integers and bigger than 0

Time:04-09

I have this program where among other things I have to validate if the list of elements is composed only of integers bigger than 0, but my current validation isn't working. This is my current program:

def validateList(num):
    i = 0
    while i < len(num):
        x = num[i]
        try:
            a = int(x)
            if a > 0:
                i  = 1
                return a
            else:
                print('Must be higher than 0,')
                return validateList(num)
        except:
            print ('Values must be integers.')
            return validateList(num)

def pedirListaAlternativos():
    string = input("Input a list of numbers separated by comma and space: ")
    list = string.split(', ')
    print(validarLista(list))

It has to be iterative and I can only use lists and cycles, not functions. Any help would be appreciated.

CodePudding user response:

You probably want a function that returns either True or False depending on whether the list is comprised entirely of integers with values greater than zero. For example:

def isValidList(lst):
  for e in lst:
    try:
      if int(e) <= 0:
        return False
    except ValueError:
      return False
  return True

This is an iterative solution whereas the original code seems to be attempting recursion (which is quite unnecessary)

  • Related