Reputation: 3
I am trying to create a function that will test whether a number is a prime number and then return True or False. I am an extreme beginner at Python, so please make your code as simple as possible. Here's what I tried so far (only returns True):
def isPrime(x):
x = int(x)
for i in range(2, x):
if(x % i == 0):
x == False
else:
x == True
return x
print(isPrime(input("Enter a prime number.")))
Upvotes: 0
Views: 3873
Reputation: 678
You almost made it, just need to change it like this:
def isPrime(x):
x = int(x)
for i in range(2, x):
if x % i == 0:
return False
return x >= 2
print(isPrime(input("Enter a prime number.")))
EDIT: As pointed by @MarkRansom, when the i
variable reaches the square root of x
, it is safe to assume that there are no more possible divisors for it:
from math import sqrt
def isPrime(x):
x = int(x)
for i in range(2, int(sqrt(x)) + 1):
...
Upvotes: 2
Reputation:
When you typed this, I believe you meant as follows below:
def isPrime(x):
x = int(x)
for i in range(2, x):
if (x % i) == 0:
x = False
else:
x = True
return x
print(isPrime(input("Enter a prime number.")))
## Which runs as follows in python IDLE:
>>> def isPrime(x):
x = int(x)
for i in range(2, x):
if (x % i) == 0:
x = False
else:
x = True
return x
>>> print(isPrime(input("Enter a prime number.")))
Enter a prime number.11
True
>>> print(isPrime(input("Enter a prime number.")))
Enter a prime number.100
False
I know when I started out, I made many typing errors. By rereading my code and lots of practice, I slowly got better.
Here's a how I would write out your task.
def isPrime(h):
h = int(h)
test = None
for x in range(2, h):
if (h%x) == 0:
test = False
print(f"{test}, the number {h} is not a prime!")
break
else:
test = True
print(f"{test}ly, the number {h} is a prime!")
## Then I'll run the call to the function in python IDLE as:
>>>
>>> isPrime(input("Enter a number.\n"))
Enter a number.
11
Truely, the number 11 is a prime!
>>>
>>> isPrime(input("Enter a number.\n"))
Enter a number.
110
False, the number 110 is not a prime!
>>>
One of most important things, that really helped me was:
Upvotes: 0
Reputation: 41925
I believe the simplest form of your program would be along the lines:
def isPrime(x):
if x > 1:
for i in range(2, x):
if x % i == 0:
return False
return True
return False
print(isPrime(int(input("Enter a number: "))))
But this is not as efficient as it could be. To do better, we would treat 2 (and all even numbers) as a special case and only allow the divisor to cover the odd numbers from 3 to the square root of the number we're testing. The more divisions we can avoid, the faster it goes.
Ultimately using a Sieve of Eratosthenes will beat this approach, even with optimizations.
Upvotes: 1