0

In this code, I wanted to take 2 numbers and add them to the list to use later. This code works correctly as long as it does not get an error, but when one of the exceptions is activated, the function returns None.

class NotPositiveError(Exception):
    pass

lenghts_list = []

def exception():
    try:
        user_num = int(input("Put a number: "))
        if user_num > 0:
            return user_num
        else:
            raise NotPositiveError
    except ValueError as Err:
        print(Err)
        #return "False"
        exception()
    except NotPositiveError:
        print("Sorry, your input should be positive")
        #return "False"
        exception()

print("put two number. The first is for the size of your main list and the second is for the size of the operator lists ")
for i in range(2):
    user_lenght = exception()
    print(user_lenght)
    lenghts_list.append(user_lenght)
print(lenghts_list)

If you give it 1 and then 2, it will give you [1, 2]. But if you give it "s", it will ask for input again and you give it 1, it will go to the second one and you will go to 2. it will give you [None, 2] How fix this!?

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 1
    If you want to use recursive functions for this (which is probably not a great idea), you need to return the calls. `return exception()` – Mark Aug 12 '23 at 20:27
  • If you really mean to have a recursive function the answers to this [question](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) will help. – quamrana Aug 12 '23 at 20:32
  • If you just want to have the user input valid values, then the answers to this [question](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) will help. – quamrana Aug 12 '23 at 20:34
  • This is really not a good way to do things, easing and exception just to catch it in the same block. – juanpa.arrivillaga Aug 13 '23 at 02:29
  • And also, it's probably better to use a while loop here, not recursion, but you are forgetting to `return` the result of your recursive calls, that's why you get `None` – juanpa.arrivillaga Aug 13 '23 at 02:30

0 Answers0