Python Program to Check prime number
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Code Explanation
Input
num = int(input("Enter a number: "))
input(): Prompts the user to enter a number.
int(): Converts the input into an integer.
Check if the Number is Greater than 1
if num > 1:
Prime numbers must be greater than 1.
If num <= 1, it is not a prime number, and the code skips to the else block at the end.
Check Divisibility Using a Loop
for i in range(2, num):
range(2, num): Generates numbers from 2 to
num −1
num−1 (inclusive of 2 but excluding num).
The loop iterates over potential divisors (i) to check if any of them divide num.
If Divisible by Any Number
if num % i == 0:
print(f"{num} is not a prime number.")
break
num % i == 0: Checks if num is divisible by i.
If num is divisible by any number in the range, it is not a prime number.
The program prints the result and exits the loop using break to avoid unnecessary checks.
If the Loop Completes Without Finding Divisors
else:
print(f"{num} is a prime number.")
The else block associated with the for loop executes only if the loop completes without hitting a break.
This means no divisors were found, so num is a prime number.
Handle Numbers Less Than or Equal to 1
else:
print(f"{num} is not a prime number.")
If num <= 1, the program directly prints that the number is not prime.
#source code --> clcoding.com
0 Comments:
Post a Comment