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

Answered by Dhir P. Python tutor

918 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Write a basic program to output the lowest of 3 input numbers. (You may omit error checks on your inputs)


What is the difference between a list and an array?


Print "Hello World!" ten times without typing (or pasting) the print function more than once


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–2024

Terms & Conditions|Privacy Policy