Cheatography
https://cheatography.com
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 indentation (whitespace at the beginning of a line) to define scope in the code. |
Elif
if (a > b): print("a > b") elif (a < b): print("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): print("a < b") else: print("a is equal to b")
|
The else keyword catches anything which isn't caught by the preceding conditions. |
Short Hand If
if a < b: print("a < b")
|
Short Hand If ... Else
Two conditions: |
print("a > b") if a > b else print("a < b")
|
Three conditions: |
print("a > b") if a > b else print("a is equal to b") if a == b else print("a < b") >>> a < b
|
AND
if (condition_1 and condition_2): print("Both conditions are correct") else: print("At least one of the conditions is incorrect")
|
OR
if (condition_1 or condition_2): print("At least one of the conditions is correct") else: print("Both conditions are incorrect")
|
|
|
Nested If
if (a > 0): if (a > b): print("a > 0 and a > b") elif (a < b): print("a > 0 and a < b") else: print("a < 0") >>> a > 0 and a < b
|
The pass Statement
|
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. |
|
Created By
Metadata
Favourited By
Comments
Md. Zubair, 17:19 21 Dec 19
Great one. Carry on!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by Nouha_Thabet