PYTHON: Program to Check if a Number is Prime.
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
PYTHON: Program to Check if a Number is Prime.
If you're like me, then you might come across clashes on CodinGame where you need to check if a number is prime or not. In my case, I can never remember how to write the code.
Here is a simple function you can create to check if a number is prime:
PROGRAM: Defining 'isPrime()'
1
2
3
4
5
6
7
8
9
10
11
def isPrime(n):
for i in range(2, n):
if (n%i) == 0:
return False
return True
# Let's test it out:
print(isPrime(2)) # True
print(isPrime(7)) # True
print(isPrime(60)) # False
Enter to Rename, Shift+Enter to Preview
Try it for yourself by changing the code and test-lines above.
Conclusion:
We have defined a function isPrime()
using 5 lines of code.
Happy Coding, Code-Parser
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content