Check Positive, Negative, or Zero in Python
Give positive numbers, negative numbers, and zero their own Python branches. Practice strict comparisons with decimal input in this beginner sign classifier.
1# Program to check if a number is positive, negative, or zero23num = float(input("Enter a number: "))45if num > 0:6 print(num, "is positive")7elif num < 0:8 print(num, "is negative")9else:10 print("The number is zero")
Sample Output
-3.0 is negative
The conversion produces -3.0, which satisfies the less-than-zero test.
In this one
- Split numbers around zero
- Use strict comparisons
- Recognize signed floating-point zero
How it works
- 1
Convert the response into num using float.
- 2
Test positivity before testing negativity.
- 3
Use the final else for zero and print its message.
Edge cases
Zero
Enter 0.
Both strict comparisons fail, so zero gets its own message.
Negative zero
Enter -0.0.
It compares equal to zero and is not classified as negative.
What's going on
Three buckets: greater than zero, less than zero, and zero itself. The strict comparisons matter. Put zero under >= 0 and you will call it positive.
float reads decimal as well as whole-number text. Python first tests num > 0, then num < 0 if necessary. For an ordinary finite number, failing both tests leaves zero, so the final else prints a different message.
The sample enters -3 and stores -3.0. It reaches the negative branch. Signed floating-point zero is a small wrinkle: -0.0 compares equal to 0.0, so it reaches else too. This is a sign classifier, not input validation for special float values such as nan.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is the first test > 0 rather than >= 0?
Pick an answer to check it.
Question 2
Which branch handles -3?
Pick an answer to check it.
Questions people ask
Why is the first test > 0 rather than >= 0?
Strict > keeps zero out of the positive category.
Which branch handles -3?
The elif branch, because -3.0 is less than zero.
Does this reject text such as hello?
No. float raises ValueError before any of the sign comparisons run.