Checking if a Number is Prime in Python
A natural number greater than 1 is considered a prime number if it cannot be divided evenly by any natural number other than 1 and itself. In other words, a prime number has no other divisors except 1 and itself.
Example Python Script (test.py
):
# Python program to check if the user's input is a prime number # User input num = int(input("Please enter a number: ")) # Prime numbers are greater than 1 if num > 1: # Check for factors for i in range(2, num): if (num % i) == 0: print(num, "is not a prime number") print(i, "times", num // i, "is", num) break else: print(num, "is a prime number") # Numbers less than or equal to 1 are not prime else: print(num, "is not a prime number")
Output Examples:
$ python3 test.py Please enter a number: 1 1 is not a prime number $ python3 test.py Please enter a number: 4 4 is not a prime number 2 times 2 is 4 $ python3 test.py Please enter a number: 5 5 is a prime number
This script determines if a number is prime by checking if it has any divisors other than 1 and itself. If it does, it is not a prime number; otherwise, it is.