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

1388 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Define a function that takes in the age of the user and adds it to an output sentence such as "You are ..... old".


Which function is ran when an object is instantiated?


What is the outcome of the following code? print(2*[3,4,5])


Using the shared code editor, write a recursive function for calculating a factorial of an input parameter.


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences