Learn about Prime Number Program in Python using While Loop in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Prime Number Program in Python using While Loop
A prime number is a positive integer greater than 1 that can be divided by 1 and itself. Example: 2,3,5,7,…. are all prime numbers.
The below program checks whether the number given by the user is a prime number or not using the while loop.
Program:
# Python program to check if a number is prime or not
# input number
num = int(input('Enter a number: '))
count = 0
i = 2
# If number is greater than 1
while(i <= num//2):
if(num % i ==0):
count += 1
break
i += 1
# display result
if(count == 0 and num != 1):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
Enter a number: 7
7 is a prime number
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Python Program to Check Prime Number