Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Check if a number is Prime - Python Program

Example 1 :

# Check prime number n = int(input("Enter a number: ")) is_prime = True if n <= 1: is_prime = False else: for i in range(2, int(n ** 0.5) + 1): if n % i == 0: is_prime = False break if is_prime: print(f"{n} is a Prime number.") else: print(f"{n} is NOT a Prime number.")

Output

 
OUTPUT 1:
Enter a number: 11
11 is a Prime number. 


OUTPUT 2 :
Enter a number: 12
12 is NOT a Prime number. 

Explanation:

  • A prime number is divisible only by 1 and itself.
  • We check up to sqrt(n) for efficiency.
  • Breaks early if divisor is found.

Example 2 : Advanced Program

def is_prime(number): """ Checks if a given number is a prime number. Args: number (int): The integer to be checked for primality. Returns: bool: True if the number is prime, False otherwise. """ if number <= 1: return False # Prime numbers are greater than 1 # Check for divisibility from 2 up to the square root of the number # We only need to check up to the square root because if a number 'n' # has a divisor greater than its square root, it must also have a # divisor smaller than its square root. for i in range(2, int(number**0.5) + 1): if number % i == 0: return False # Found a divisor, so it's not prime return True # No divisors found, so it's prime # Get input from the user num = int(input("Enter a number to check: ")) # Check if the number is prime and print the result if is_prime(num): print(f"{num} is a prime number.") else: print(f"{num} is not a prime number.")

Output

 
OUTPUT 1:
Enter a number to check: 7
7 is a prime number.

OUTPUT 2 :
Enter a number to check: 8
8 is not a prime number.

Explanation:

 

is_prime(number) function:

  • This function takes an integer numberas input.
  • It first handles edge cases: numbers less than or equal to 1 are not prime, so it immediately returns False.
  • For numbers greater than 1, it iterates through possible divisors starting from 2 up to the square root of the number. This optimization is based on the mathematical property that if a number has a divisor greater than its square root, it must also have a divisor smaller than its square root.
  • Inside the loop, if numberis perfectly divisible by any i (i.e., number % i == 0), it means number has a factor other than 1 and itself, so it is not prime, and the function returns False.
  • If the loop completes without finding any divisors, it means the numberis only divisible by 1 and itself, so it is prime, and the function returns True.