Python Conditions Cheat Sheet

A Programming › Python cheat sheet in English by Nouha_Thabet
24,400 views 3,317 downloads 19 Dec 2019 History
4.3 avg · 1 rating

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.

Badges

Useful Cheat Sheet Nice Cheat Sheet Downloaded from Unusual Locations × 1

Comments (1)

Md. Zubair 17:19 21 Dec 2019

Great one. Carry on!

Reply

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.