---
title: "Write a function to check if a number is prime. with explanation"  
description: "Write a function to check if a number is prime. with explanation"  
author: "Ravi Vishwakarma"  
published: 2025-09-02  
updated: 2025-09-03  
canonical: https://www.mindstick.com/forum/161900/write-a-function-to-check-if-a-number-is-prime-with-explanation  
category: "python"  
tags: ["python-3.4", "python"]  
reading_time: 2 minutes  

---

# Write a function to check if a number is prime. with explanation

**Write a [function to check](https://www.mindstick.com/forum/158803/create-a-function-to-check-if-a-given-number-is-a-perfect-number-or-not-using-rust) if a number is prime. with [explanation](https://yourviews.mindstick.com/view/84608/what-are-hindenburg-s-allegations-against-adani-detailed-explanation)**

## Replies

### Reply by Anubhav Sharma

### Prime Number Reminder:

- A **prime number** is a number greater than **1** that has **no divisors** other than **1 and itself**.
- **Examples:** `2, 3, 5, 7, 11, 13` are prime.
- `4, 6, 8, 9, 10` are not prime because they can be divided by numbers other than 1 and themselves.

### Python Program

```python
def is_prime_number(n):
    # Prime numbers are greater than 1
    if n <= 1:
        return False

    # Check divisibility from 2 to sqrt(n) -> (n**0.5)
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:  # if divisible by i
            return False
    return True

# Test the function
num = int(input("Enter a number: "))
if is_prime_number(num):
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")
```

### Explanation

**Base Case**:

- Numbers `0`, `1`, and negative numbers are **not prime**.

```python
if n <= 1:
    return False
```

**[Check](https://yourviews.mindstick.com/story/2248/never-forget-to-check-these-specifications-before-buying-a-mobile-phone) divisibility**:

```python
for i in range(2, int(n**0.5) + 1):
```

- We only check divisors up to `√n` instead of `n-1`.
- Why? If `n` has a factor larger than `√n`, then the corresponding smaller factor would already have been found.
- This makes it **efficient**.

**Check modulus**:

```python
if n % i == 0:
    return False
```

- If `n` divides evenly by `i`, then it’s not prime.

**Return True if no divisors found**:

```python
return True
```

## Output :

```plaintext
Enter a number: 29
29 is a prime number
```

```plaintext
Enter a number: 20
20 is not a prime number
```


---

Original Source: https://www.mindstick.com/forum/161900/write-a-function-to-check-if-a-number-is-prime-with-explanation

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
