How do I check if a number is prime using a python program?

We begin by making a function using Python where we take in an argument and then check if it is a an integer. If not we ask them to try again but with an integer. Then we check to see if the input was either 1 or 0 as we know these are not prime. Also, if the input was a negative number we again ask them to try again. Finally, if all the checks have been validated then we go through each number from 2 to the input and check if the input is divisible by any number in between. If it is then it is not a prime, otherwise we can deduce that it is a prime. def prime(input): try: int(input) except: return 'Please enter a number' prime_check = True if input == 1 or input == 0: return False if input < 0: return 'Please enter a positive number' for x in range(2, input): if input % x == 0: prime_check = False break return prime_check

DP
Answered by Dhir P. Python tutor

1545 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What is the difference between a list and an array?


Write a short program to print all the even numbers 1 to 100


How do I use for loops in Python?


What is the difference between DFS and BFS? Where can I apply each?


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

MyTutor is part of the IXL family of brands:

© 2025 by IXL Learning