gilquintero
gilquintero

Reputation: 1

Support only integers in input for python

Ok, so I built a a function to accept only numeric inputs. I am new to python. Basically I am getting an error when I try writing a non-numeric input and then write a numeric input. This is my code

class TestNumericInput:

    def numeric_input(self):
        val = str(input())
        if val.isdigit():
            val_number = int(val)
            return val_number
        else:
            print('Please write only numbers (i.e. 0, 1, 2...)')
            self.numeric_input()

    def start(self):
        my_number = self.numeric_input()
        print(my_number * 5)

This is a screenshot of the error I am getting

error screenshot

Thanks

Upvotes: 0

Views: 74

Answers (1)

David Culbreth
David Culbreth

Reputation: 2796

While @HarshalPerekh's answer does solve your immediate problem, recursion can introduce issues with the stack depth (though that is very unlikely here). While I know that the max stack depth is in the thousands, it's worth noting that implementing this behavior is possible with an algorithm that doesn't involve recursion, and therefore much less potential stack depth (I think just 2, given the loop).

It also turns out that you can do it with a few fewer lines of code as well!

def numeric_input(self):
    val = str(input())
    while not val.isdigit():
        print('Please write only numbers (i.e. 0, 1, 2...)')
        val = str(input())
    return int(val)

def start(self):
    my_number = self.numeric_input()
    print(my_number * 5)

On another note, the reason that you got nothing is because when you did branch into the not-a-digit branch, there was no return. In Python, the default return value of a function, that is, what it returns when there's not a return statement, is None. Because your function never executed an explicit return, None was returned. The type of None is NoneType. I hope this helps explain the error you were seeing.

Upvotes: 1

Related Questions