Python Cheat Sheet - Keywords
” → Visit finxter.com
“A puzzle a day to learn, code, and play
Keyword Description Code example
False, True Boolean data types False == (1 > 2), True == (2 > 1)
None Empty value constant ():
def f
x = 2
f() == None # True
and, or, not Logical operators: x, y = True, False
(x and y) → both x and y must be True (x or y) == True # True
(x or y) → either x or y must be True (x and y) == False True
#
(not x) → x must be false (not y) == True True
#
break Ends loop prematurely while(True):
break # no infinite loop
print("hello world")
continue Finishes current loop iteration while(True):
continue
print("43") # dead code
class Defines a new class → a real-world concept class beer:
(object oriented programming) x = 1.0 # litre
def drink(self):
def Defines a new function or class method. For latter, self.x = 0.0
first parameter (“self”) points to the class object. b = beer() # creates class with constructor
When calling class method, first parameter is implicit. b.drink() # beer empty: b.x == 0
if, elif, else Conditional program execution: program starts with x = int(input("your value: "))
“if” branch, tries the “elif” branches, and finishes with if x > 3:
“else” branch (until one branch evaluates to True). print("Big")
elif x == 3:
print("Medium")
else:
print("Small")
for, while # For loop declaration # While loop - same semantics
for i in [0,1,2]: j = 0
print(i) while j < 3:
print(j)
j = j + 1
in Checks whether element is in sequence 42 in [2, 39, 42] # True
is Checks whether both elements point to the same y = x = 3
object x is y # True
[3] is [3] # False
lambda Function with no name (anonymous function) (lambda x: x + 3)(3) # returns 6
return Result of a function def i ncrementor(x):
return x + 1
incrementor(4) # returns 5