I want to sanitize my user input in my class. All is working as expected but first of all, I would like to avoid to set a default value for my digit
parameter. Secondly, I would like to avoid to put everything in a big while-loop and instead call implicitly a function which asserts the user input.
Initially, I thought to create a @staticmethod could do the job but I was obviously wrong (Why does staticmethod not assert my user input?).
My code is:
class CompositeNumbers:
def __init__(self, digit=6):
self.uinput = digit
flag = True
while flag:
try:
self.uinput = int(input("Enter a number: "))
while self.uinput <= 0:
self.uinput = int(input("Please enter a positive number: "))
else:
flag = False
for i in range(2, self.uinput):
if self.uinput % i == 0:
print("The number is composite!")
break
else:
print("The number is a prime!")
break
except ValueError:
print("Wrong input!")
EDIT
My previous attempt to use a function did not work as I wanted it to. I would need to call the check_input
function. It would check my input but if I would call the userinput
function, it would not check the input implicitly.
@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
askForValidNumber
which contains an endless loop to take the input, check it and return it only if it is valid. \$\endgroup\$p1 = CompositeNumbers(6); p1
(2) I created in my SO account the question because my @staticmethod was unsatisfiable (see my edit). \$\endgroup\$