So I am making a prime number detector as a project. I’m VERY new to programming and my friend showed me a little python. I want to make a function that detects if the user puts in a number for the input (like 5,28,156,42,63) and if the put in something else (like banana,pants,or cereal) to give them a custom error saying "Invalid Number. Please Try Again" and then looping the program until they put in a number.
Please help me make this work.
def number_checker():
user_number = int(input('Please enter a Number: '))
check = isinstance(user_number, int)
if check == True:
print ('This is a number')
if check == False:
print ('This is not a number')
1) Casting input to int
would raise an exception if the input string cannot be converted to int
.
user_number = int(input('Please enter a Number: '))
^^^
2) It does not make sense to cross-verify user_number
with int
instance as it would already be int
3) You can try
def number_checker():
while not input("enter num: ").isdigit():
print("This is not a number")
print("This is a number")
number_checker()
Try following:
def number_checker():
msg = 'Put your number > '
while True:
user_input = input(msg)
correct = user_input.isdigit()
if correct:
print("This is an integer")
return # here you can put int(user_input)
else:
print("This is not an integer")
msg = 'You typed not integer. Try again.> '
if __name__ == '__main__':
number_checker()
And it's also good rule give names for your functions as verbs according to what they do. For this one, I would give, for example def int_input
or something.