0

I read these two entries (Meaning of classmethod and staticmethod for beginner, staticmethod) and got the impression that @staticmethod can function like an user input assert statement to ensure the correct input.

Is my assumption incorrect? (@staticmethod can assert user input)

When I enter in my code an expected value of x>0 and not a non-digit, I get my result whether it is a prime or a composite number. But If I have a negative number, 0 or a non-digit, I can enter input until it is 'correct' and my code exits or it prints "Wrong Input".

My goal is to 'clean' the input through the staticmethod (or anything else basically) but within my class.

My code:

class CompositeNumbers:
    def __init__(self, digit):
        self.digit = digit

    @staticmethod
    def check_input(digit):
        try:
            while digit <= 0:
                digit = int(input("Try again: "))
        except TypeError:
            print("Wrong Input")

    def userinput(self):

        uinput = self.digit

        for i in range(2, uinput):
            if uinput % i == 0:
                print("The number is composite!")
                break
            else:
                print("The number is a prime!")
                break

EDIT

I have moved my check_input function now into my userinput. When running the code it finishes without error but does not print the output.

class CompositeNumbers:
    def __init__(self, digit):

        self.digit = digit

    def userinput(self, digit):

        if digit <= 0 or TypeError:

            def check_input(digit):
                flag = True
                while flag:
                    try:
                        while digit <= 0:
                            digit = int(input("Try again: "))
                        else:
                            flag = False
                            return digit
                    except TypeError:
                        print("Wrong Input")


        for i in range(2, digit):
            if digit % i == 0:
                print("The number is composite!")
                break
            else:
                print("The number is a prime!")
                break
Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • If everything is working but you are asking for a review, this question is better suited for [CodeReview](https://codereview.stackexchange.com/). – Bram Vanroy Dec 04 '18 at 15:03
  • 4
    Static methods and input sanitation are totally unrelated concepts. A static method is just a regular function that is bound to a class. It looks like you expect your static method to be called implicitly when assigning `digit`. That won't work. – Patrick Haugh Dec 04 '18 at 15:03
  • Precisely, that is actually what I expected to happen. Thanks for your commment. – Alex_P Dec 04 '18 at 16:20

0 Answers0