Python Program to Check a Number Is Positive or Negative

1. Introduction

In this post, we will explore how to determine if a number is positive or negative in Python. While this might seem like a straightforward task, doing it recursively is a great way to understand the concept of recursion, which is particularly useful in solving more complex problems.

Recursion is a programming technique where a function calls itself. To avoid infinite recursion, a base case is defined. For checking if a number is positive or negative, the base case can be the number itself, since any non-zero number can be classified as positive or negative.

2. Program Steps

1. Define a recursive function that takes an integer as an argument.

2. Set the base case for the function to stop calling itself.

3. If the number is positive or negative, return the corresponding result.

4. If the number is zero, it is neither positive nor negative, return that result.

3. Code Program

def check_positive_negative(num):
    # Base case: if the number is greater than 0, it is positive
    if num > 0:
        return "Positive"
    # Base case: if the number is less than 0, it is negative
    elif num < 0:
        return "Negative"
    # Base case: if the number is 0, it is neither positive nor negative
    else:
        return "Neither Positive Nor Negative"

Output:

print(check_positive_negative(10))  # Output: Positive
print(check_positive_negative(-5))  # Output: Negative
print(check_positive_negative(0))   # Output: Neither Positive Nor Negative

Explanation:

1. The function check_positive_negative is defined to accept one parameter, num.

2. It checks if num is greater than 0, in which case it returns "Positive".

3. If num is less than 0, it returns "Negative".

4. If num is exactly 0, it returns "Neither Positive Nor Negative", as zero is neither positive nor negative.

5. There is no recursive call in this function because the nature of the problem doesn't require breaking down the problem into smaller subproblems.

Comments