Python Program to Check if Number is Positive or Negative
You can check if a number is positive or negative in Python using an
if statement like this: if number > 0: print('Positive') elif number < 0: print('Negative') else: print('Zero').Examples
Input5
OutputPositive
Input-3
OutputNegative
Input0
OutputZero
How to Think About It
To decide if a number is positive or negative, first think about what positive means: greater than zero. Negative means less than zero. If the number is exactly zero, it is neither positive nor negative. So, check if the number is greater than zero, then less than zero, and if neither, it must be zero.
Algorithm
1
Get the number input from the user2
Check if the number is greater than zero3
If yes, print 'Positive'4
Else, check if the number is less than zero5
If yes, print 'Negative'6
Otherwise, print 'Zero'Code
python
number = float(input('Enter a number: ')) if number > 0: print('Positive') elif number < 0: print('Negative') else: print('Zero')
Output
Enter a number: 5
Positive
Dry Run
Let's trace the input 5 through the code
1
Input
User enters 5, so number = 5.0
2
Check if number > 0
5.0 > 0 is True
3
Print result
Print 'Positive'
| Step | Condition | Result | Output |
|---|---|---|---|
| 1 | number > 0 | True | Positive |
Why This Works
Step 1: Check if number is greater than zero
The code uses if number > 0 to find if the number is positive.
Step 2: Check if number is less than zero
If the first check fails, elif number < 0 checks if the number is negative.
Step 3: Handle zero case
If neither condition is true, else runs, meaning the number is zero.
Alternative Approaches
Using ternary conditional operator
python
number = float(input('Enter a number: ')) print('Positive' if number > 0 else 'Negative' if number < 0 else 'Zero')
This method is shorter but can be harder to read for beginners.
Using a function
python
def check_sign(num): if num > 0: return 'Positive' elif num < 0: return 'Negative' else: return 'Zero' number = float(input('Enter a number: ')) print(check_sign(number))
This approach organizes code better and is reusable.
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of comparisons regardless of input size, so it runs in constant time.
Space Complexity
It uses a fixed amount of memory for variables and no extra data structures, so space is constant.
Which Approach is Fastest?
All approaches run in constant time and space; differences are mainly in readability and reusability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-elif-else | O(1) | O(1) | Clarity and beginners |
| Ternary operator | O(1) | O(1) | Short code, experienced users |
| Function-based | O(1) | O(1) | Code reuse and organization |
Always convert input to a number type like
float before checking its sign.Forgetting to handle the zero case separately can cause wrong output.