Show Menu
Cheatography

Python Conditions Cheat Sheet by

Example

a = 2 
b = 8
if (a < b):
 ­ ­ ­  print(­"a < b")
>>> a < b
We must define scope before the
print
. In fact python relies on indent­ation (white­space at the beginning of a line) to define scope in the code.

Elif

if (a > b): 
 ­ ­ ­  print(­"a > b")
elif (a < b):
 ­ ­ ­ ­pri­nt(­"a < b")
>>> a < b
The
elif
keyword is used to say if the previous conditions were not true, then try this condition.

Else

if (a > b): 
 ­ ­  print(­"a > b")
elif (a < b):
 ­ ­ ­ ­pri­nt(­"a < b")
else:
 ­ ­  print(­"a is equal to b")
The else keyword catches anything which isn't caught by the preceding condit­ions.

Short Hand If

if a < b: print(­"a < b")

Short Hand If ... Else

Two condit­ions:
print(­"a > b") if a > b else print(­"a < b")
Three condit­ions:
print(­"a > b") if a > b else print(­"a is equal to b") if a == b else print(­"a < b") 
>>> a < b

AND

if (condi­tion_1 and condition_2):
 ­ ­ ­  print(­"Both conditions are correc­t")
else:
     print(­"At least one of the conditions is incorr­ect­")

OR

if (condi­tion_1 or condition_2):
 ­ ­ ­  print(­"At least one of the conditions is correc­t")
else:
     print(­"Both conditions are incorr­ect­")
 

Nested If

if (a > 0): 
 ­ ­ ­  if (a > b):
 ­ ­ ­ ­ ­ ­ ­  print(­"a > 0 and a > b")
 ­ ­ ­  elif (a < b):
 ­ ­ ­ ­ ­ ­ ­ ­ ­pri­nt(­"a > 0 and a < b")
else:
 ­ ­ ­  print(­"a < 0")
>>> a > 0 and a < b

The pass Statement

if (a < b): 
 ­ ­ ­  pass
if
statements cannot be empty, but if we for some reason have an if statement with no content, we can put in the
pass
statement to avoid getting an error.
 

Comments

Great one. Carry on!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by Nouha_Thabet