Check Positive, Negative, or Zero in Python
Zero is not positive. Put it in its own branch or you will lie to the user.
BeginnerBasic Python ProgramsExample 8 of 25
check-positive-negative-or-zero.py
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")
Output
Enter a number: -3 -3.0 is negative
In this one
- zero needs its own branch
- > 0 is not "not negative"
What's going on
Three buckets: > 0, < 0, else. Zero has to be the else. Stick it under > 0 and you print "0.0 is positive". I've marked that wrong on quizzes.
float so -0 still comes through as 0.0. Fine.
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.