Python supports the usual logical conditions from mathematics:
Equal to
Not Equal to
Less than
Less than or Equal to
Greater than
Greater than or Equal to
These conditions can be used in several ways, most commonly in "if statements" and loops.
a == b ## Equal to
x != b ## Not Equal to
c < d ## Less than
m <= n ## Less than or Equal to
i > j ## Greater than
p >= q ## Greater than or Equal to
An "if statement" is written by using the
Indentation is very important.
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.
a = 2
if a > 0 : ## condition True
print ("a is greater than Zero." )
if a < 0 : ## condition False
print ("a is less than Zero." )
if (a+12 == 14 ): ## using Parentheses ()
print ("a plus is equal to 14." )
The
Example :
a = 2
if a < 0 : ## condition False
print ("a is less than Zero" )
else :
print ("a is greater than Zero" )
The
Indentation is very important.
a = 2
if a < 0 : ## condition False
print ("a less than Zero" )
elif a > 0 : ## condition True
print ("a greater than Zero" )
In this example a is greater than 0, so the first condition is not true, but the elif condition is true, so we print to screen that "a greater than zero".
If the all the presceding conditions are false than python execute the code in else condition.
a = 2
if a == 10 : ## condition False
print ("a is equal to 10." )
elif a > 10 : ## condition False
print ("a is greater than 10." )
elif a <= 0 : ## condition False
print ("a is less than or equal to 0." )
else :
print ("a is less than 10 and greater than 0." )
In this example all the if and elif conditions are false, so we print to screen that "a is less than 10 and greater than 0.".
If you have only one statement to execute,one for if, and one for else, you can put it on the same line as the if statement.
a = 2
if a == 2 : print ("a is equal to 2." )
print ("a is greater than 10." ) if (a > 10 ) else print ("a is less than 10." )
This technique is known as Ternary Operators, or Conditional Expressions.a = 2
print ("a is greater than 10." ) if (a > 10 ) else print ("a is less than 10." ) if (a != 2 ) else print ("a is equal to 2." )
The
a = 2
if a < 10 and a > 0 :
print ("a is less than 10 and greater than 0." )
The
a = 2
if a < 10 or a < 0 :
print ("a is less than 10 and greater than 0." )
## code executed when any one of the conditions are true.
You can use
a = 2
if a > 0 : ## condition True
if a < 10 : ## condition True
print ("a is greater than 0 and less than 10" )
else :
print ("a is greater than 0 and greater than 10" )
else :
print ("a is less than zero" )
if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
a = 2
if a > 0 : ## condition True
pass