Python Program - Check whether a Number is Positive or Negative
A number is said to be positive if it is greater than zero and it is said to be negative if it is less than zero. A number can be checked for zero, positive and negative using if, if-else, nested if-else and short-hand if-else statements.
Method 1: Using If statement
In the example below, if conditional statements are used to check whether a given number is positive or negative.
def CheckNumber(x): if x > 0: message = "Positive number" if x == 0: message = "Zero" if x < 0: message = "Negative number" print(message) CheckNumber(5.5) CheckNumber(-10.8)
The above code will give the following output:
Positive number Negative number
Method 2: Using If-else statement
It can also be achieved using If-else conditional statements.
def CheckNumber(x): if x > 0: message = "Positive number" elif x == 0: message = "Zero" else: message = "Negative number" print(message) CheckNumber(5.5) CheckNumber(-10.8)
The above code will give the following output:
Positive number Negative number
Method 3: Using Nested If-else statement
The above problem can also be solved using nested if-else conditional statements.
def CheckNumber(x): if x >= 0: if x > 0: message = "Positive number" else: message = "Zero" else: message = "Negative number" print(message) CheckNumber(5.5) CheckNumber(-10.8)
The above code will give the following output:
Positive number Negative number
Method 4: Using Short hand If-else statement
Short hand if-else conditional statements can also be used here.
def CheckNumber(x): message = "Positive number" if x > 0 else \ "Zero" if x == 0 else "Negative number" print(message) CheckNumber(5.5) CheckNumber(-10.8)
The above code will give the following output:
Positive number Negative number
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python Program - Merge Sort
- Python Program - Shell Sort
- Stack in Python
- Queue in Python
- Python Program - Find LCM of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable
- Python Program - To Check Armstrong Number
- Python Program - Counting Sort
- Python Program - Radix Sort
- Python Program - Find Largest Number among Three Numbers
- Python Program - Print Floyd's Triangle