This is a simple problem statement in which we need to find whether a number is positive, negative or zero using Python. Any number greater than zero is positive, and any number less than zero is called a negative number. The number may be a float or an integer.
This article discusses simple ways to check the number using Python examples.
Table of contents
1. Using if-elif-else Statements
This is the most straightforward way to check the sign of a number in Python using if-elif-else.
- If num is greater than 0, it is positive.
- Else if num is less than 0, it is negative.
- Else num is equal to 0, it is zero.
Code Example
2. Using Ternary (Conditional) Operator
Python doesn’t have a direct ternary operator like other languages, but you can simulate it with conditional expressions to find if the number is positive, negative or zero.
This is a more compact way of writing conditions. The conditional expressions are evaluated from left to right.
- If num > 0, it prints “Positive”.
- Else if num < 0, it prints “Negative”.
- Otherwise, it prints “Zero”.
Code Example
3. Using Lambda function
A lambda function in Python is a small, anonymous function that is defined using the lambda keyword. It can have multiple arguments but only one expression, which is evaluated and returned.
lambda arguments: expression
lambda→ Keyword to define the function.arguments→ Input parameters (similar to function arguments).expression→ A single operation that returns a result.
This is more concise way to perform the same check in a more functional programming style. It works similar to the ternary operator but wrapped inside a lambda.
Code Example
4. Using NumPy’s sign Function
If you are working with NumPy, a popular library for numerical computing, you can use numpy.sign() that returns the sign of a number or an array of numbers.
numpy.sign(num) returns 1 for positive numbers, -1 for negative numbers, and 0 for zero. Based on this, you can print the corresponding message.
Note: The Numpy library is not bundled with the default Python installation. We need to install it separately.
Code Example
Summary
There are various ways in Python to check if a number is positive, negative, or zero, ranging from basic conditional checks to more functional and library-based approaches.

Leave a Reply