Wednesday, 27 November 2024

Day 6 : Python Program to Check prime number

 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

Popular Posts

Categories

100 Python Programs for Beginner (78) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (179) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) Python (950) Python Coding Challenge (392) Python Quiz (46) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses