How to Classify Numbers in Python?

Estimated read time 2 min read

To classify numbers in Python, you need to define the criteria or rules for classification. Here are a few common ways to classify numbers based on different criteria:

  1. Even or Odd: You can classify numbers as even or odd based on whether they are divisible by 2. Here’s an example:
def classify_even_odd(number):
    if number % 2 == 0:
        return "Even"
        return "Odd"

# Example usage:
print(classify_even_odd(7))  # Output: Odd
print(classify_even_odd(12))  # Output: Even
  1. Positive, Negative, or Zero: You can classify numbers as positive, negative, or zero based on their sign. Here’s an example:
def classify_sign(number):
    if number > 0:
        return "Positive"
    elif number < 0:
        return "Negative"
        return "Zero"

# Example usage:
print(classify_sign(-5))  # Output: Negative
print(classify_sign(0))  # Output: Zero
print(classify_sign(8))  # Output: Positive
  1. Prime or Composite: You can classify numbers as prime or composite based on whether they have factors other than 1 and themselves. Here’s an example:
def is_prime(number):
    if number < 2:
        return False
    for i in range(2, int(number ** 0.5) + 1):
        if number % i == 0:
            return False
    return True

# Example usage:
print(is_prime(7))  # Output: True
print(is_prime(12))  # Output: False

These are just a few examples of how you can classify numbers in Python. The specific criteria and rules for classification will depend on your requirements and the problem you’re trying to solve.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply