How to check if a number is negative in python?

In mathematics, a negative number is a real number less than 0. For example, -2, -67.87, -34, -0.564 all are negative numbers. This article discusses different approaches to check if a number is negative in python.

Checking if a number is negative by using an if-else statement

Let us consider the following example. A user-defined function negative checks if a number is less than 0. If the condition is True, the program executes the if Statement, and output is printed.

def negative( num ):
    if num<0:
        print(num, " is negative")
    else:
        print(num, "is not negative")

negative(4)
negative(-5)
negative(0)

The above program gives output as

4 is not negative
-5  is negative
0 is not negative

Checking if a number is negative by converting the number to string data type

A function negative is defined to check if the number is negative. The str() function converts the number to a string data type. The if statement checks if the first character of the string is equal to the hyphen '-'. If the condition is True, the number is a negative number.

def negative( num ):
    str_num = str(num)
    if str_num[0] == '-':
        print(num, " is negative")
    else:
        print(num, "is not negative")

negative(4)
negative(-5)
negative(0)

Output

4 is not negative
-5  is negative
0 is not negative
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions