In this python tutorial, you will learn how to Check if a Number is Positive or Negative using the if, elif and else statements along with the greater and equality operators of the python programming language.
How to Check if a Number is Positive or Negative?
Let’s take a look at the source code , here the values are given as input by the user in the code, the == equality operator and the > greater than operator along with the if, elif and else statements carry out the function.
RUN CODE SNIPPET#program to Check if a Number is Positive or Negative num = float(input("Enter a number: ")) if num > 0: print("\n{0} is a positive number".format(num)) elif num == 0: print("Zero") else: print("\n{0} is a negative number".format(num))
INPUT:
-8659
OUTPUT:
Enter a number: -8659.0 is a negative number
- Here we give the user the option to enter the values and the input values are scanned using the
input
function and are stored in the variablenum
with the statements/strings("Enter a number: ")
, we use thefloat
function and declare the input value as a decimal value. - In the STDIN section of the code editor the input values are entered.
- We declare the
if
statement with the conditions asnum > 0
followed by a colon:
. If the conditions are met, theprint
function will display the statement("\n{0} is a positive number".format(num))
. - We declare the
elif
statement with the conditions asnum == 0
followed by a colon:
. If the conditions are met, theprint
function will display the statement("Zero")
. - If neither of the above conditions are not met the
else
function will be executed and theprint
function will display the statement("\n{0} is a negative number".format(num)).
- In the above lines of code, the variables
{0}
will hold the value ofnum
where theformat
function helps in variable substitution and data formatting.
NOTE:
- The == equality is a comparison operator which returns True is the two items are equal and returns False if not equal.
- The > greater than operator is a comparison operator which returns True if the condition is satisfied, if not it returns false.
- The input() function allows a user to insert a value into a program, it returns a string value.
- The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
- The elif is short for else if, it allows us to check for multiple expressions.
- The colon : at the end of the if, elif and else statement tells Python that the next line of code should only be run if the condition is true.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.