Python Program: Checking if a Number is Positive, Negative, or Zero
In this blog post, we will delve into a fundamental Python program that checks whether a given number is positive, negative, or zero. The article will provide a detailed explanation of the algorithm used in the program, present the Python code for implementation, and include examples with corresponding outputs.
Understanding the Algorithm
The algorithm for determining if a number is positive, negative, or zero is straightforward and involves the following steps:
- Input Number: Accept a numerical input from the user.
- Check Conditions:
- If the number is greater than zero, it is positive.
- If the number is less than zero, it is negative.
- If the number is equal to zero, it is zero.
- Display Result: Output the result indicating whether the number is positive, negative, or zero.
Python Program for Checking Number Sign
Let’s implement the algorithm in a Python program:
def check_number_sign(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
# Input from user
user_input = float(input("Enter a number: "))
# Check and display result
result = check_number_sign(user_input)
print(f"The number {user_input} is {result}.")
Output Example
Example: Checking Sign of -7.5
Enter a number: -7.5
The number -7.5 is Negative.
Explanation
The Python program defines a function check_number_sign
that takes a number as input and uses conditional statements (if
, elif
, else
) to determine whether the number is positive, negative, or zero. The input
function is employed to gather user input, and the result is displayed.
Conclusion
This Python program offers a simple yet effective way to determine the sign of a given number. It is a foundational concept in programming and is frequently used in various applications. You can use this program as a building block for more complex projects or adapt it based on specific requirements. Feel free to experiment with different input values and explore variations of the algorithm. If you have any questions or would like to explore more Python programming topics, please feel free to ask!