if Statements
If an expression returns TRUE
statements are carried out; otherwise, they aren't.
if expression:
statements
Sample:
no = 11 if no >10: print ("Greater than 10") if no <=30 printf ("Between 10 and 30")
Output:
>>> Greater than 10 Between 10 and 30 >>>
else Statements
An else
statement follows an if
statement and contains code called when the if statement is FALSE
.
x = 2 if x == 6 printf ("Yes") else: printf ("No")
elif Statements
The elif
(shortcut of else if
) statement is used when changing if
and else
statements. A series of if…elif
statements can have a final else
block, which is called if none of the if
or elif
expressions is TRUE
.
num = 12 if num == 5: printf ("Number = 5") elif num == 4: printf ("Number = 4") elif num == 3: printf ("Number = 3") else: printf ("Number = 12")
Output:
>>> Number = 12 >>>
Boolean Logic
Python uses logic operators like AND
, OR
and NOT
.
The AND
operator uses two arguments and evaluates to TRUE
if, and only if, both arguments are TRUE
. Otherwise, it evaluates to FALSE
.
>>> 1 == 1 and 2 == 2 True >>> 1 == 1 and 2 == 3 False >>> 1 != 1 and 2 == 2 False >>> 4 < 2 and 2 > 6 False >>>
Boolean operator or uses two arguments and evaluates as TRUE
if either (or both) of its arguments are TRUE
, and FALSE
if both arguments are FALSE
.
The result of NOT TRUE
is FALSE
, and NOT FALSE
goes to TRUE
.
>>> not 2 == 2 False >>> not 6 > 10 True >>>
Operator Precedence
Operator Precedence uses the mathematical idea of operation order, e.g. multiplication begins performed before addition.
>>> False == False or True True >>> False == (False or True) False >>> (False == False) or True >>>True >>>