Check if a given Number is Prime or not Using a While Loop in Python

Now we are going to know how to check if a given number is prime or not using a while loop in Python:

Simple code:

num = int(input("Enter a number: "))
is_prime = True
i = 2
while i <= num//2:
    if num % i == 0:
        is_prime = False
        break
    i += 1
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

Output:

Enter a number: 12
12 is not a prime number

Code with comments:

# get the input number from the user
num = int(input("Enter a number: "))

# initialize the is_prime variable to True
is_prime = True

# initialize the counter i to 2
i = 2

# continue looping until i reaches the largest possible factor of the number
while i <= num//2:
    # check if the number is divisible by i
    if num % i == 0:
        # set the is_prime variable to False and exit the loop
        is_prime = False
        break
    # increment the counter i by 1
    i += 1

# check if the is_prime variable is True and print the result
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

In the above code, we first get the input number from the user using the input() function and convert it to an integer using the int() function.

We then initialize the is_prime variable to True and the counter i to 2.

We use a while loop to check if the number is divisible by any number between 2 and num//2.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x