Python Cheat Sheet
Python Cheat Sheet
Keyword False, True And, Or, Not Break Continue Class Def
Keywords Description Data values from the data type Boolean Logical operators: (and y) — both x andy must be True (cory) — either x ory must be True (not x) — x must be false Ends loop prematurely Finishes current loop iteration Defines a new class — a real-world concept (object oriented programming) Defines @ new function or class method. For latter, first parameter (“self”) points to the class object. When calling class method, first parameter is implicit. Checks whether element is in sequence Code Example False == (1> 2), True == (2>1) x, y= True, False (xory)==True #True (xand y) == False #True (not y) == True #True while(True): break # no infinite loop print("hello world") while(True): continue print("43") # dead code class Beer: def init__(self): self.content = 0.0 becks = Beer() # constructor - create class becks.drink() # beer empty: b.content 42 in [2, 39, 42] # TrueKeyword If, Elif, Else For, While None Lambda Return Description Conditional Program Execution: Program Starts With “If" Branch, Tries The “Elif” Branches, And Finishes With “Else” Branch (Until One Branch Evaluates To True). #For Loop Declaration For itn [0,1,2]: Print(l) Checks Whether Both Elements Point To The Same Object Empty Value Constant Function With No Name (Anonymous Function) Terminates Execution Of The Function And Passes The Flow Of Execution To The Caller. An Optional Value After The Return Keyword Specifies The Function Result.
Code Example X= Int(Input("Your Value: ")) : Print("'Big") Print(Medium") Else: Print("Small") # While Loop - Same Semantics J=0 While | <3: Print) Jeti WEES} XIsY # True [3] Is [3] # False Def F(): K=2 F() Is None # True (Lambda X: X + 3)(3) # Returns 6 Def Incrementor(X): Return X+1 Incrementor(4) # Returns 5Keyword Boolean Integer, Float
Basic Data Types
Description
The Boolean Data Type Is A Truth Value,
Either True Or False.
The Boolean Operators Ordered By Priority:
Not X — “IfX Is False, Then X, Else Y"
XAnd Y — “If Xs False, Then X, Else Y”
XOrY — “IFX Is False, Then Y, Else X"
These Comparison Operators Evaluate To
True:
1<2
Code Example
#44, Indexing And Slicing
S="The Youngest Pope Was 11 Years Old"
Print(S[0)) #
Print(S[1:3]) # ‘he’
Print(S[-3:-1]) # ‘ol’
Print(S[-3:]) # ‘old’
X=S.Split() # Creates String Array Of Words
Print(X[-3] + "" +X[-1] +" +X[2] + "S")
#'11 Old Popes'
#45, Most Important String Methods
Y=" This Is Lazy\T\N "
Print(Y.Strip()) # Remove Whitespace: ‘This
Is Lazy’
Print("DrDre".Lower()) # Lowercase:
‘drdre’
Print("Attention".Upper()) # Uppercase:
‘ATTENTION’
Print("Smartphone" Startswith("Smart")) #
True
Print(Smartphone".Endswith(""Phone")) #
True
Print("Another".Find("Other")) # Match
Index: 2
Print("Cheat".Replace("Ch", "M'")) # ‘meat’
Print(,’ Join({"F", "B", "I"D) #8,"
Print(Len("Rumpelstiltskin")) # String
Length: 15
Print("Ear" In "Earth") # Contains: TrueKeyword
List
Adding
Elements.
Removal
Reversing
Sorting
Indexing
Stack
Complex Data Types
Description
Acontainer data type that stores a
sequence of elements. Unlike strings, lists
are mutable: modification possible.
Add elements to a list with (i) append, (ii)
insert, or (ii) ist concatenation.
The append operation is very fast.
Removing an element can be slower.
This reverses the order of list elements.
Sorts alist. The computational complexity
of sorting is O(n log n) for n list elements.
Finds the first occurence of an element in
the list & returns its index. Can be slow as
the whole list is traversed.
Python lists can be used intuitively as stack
via the two list operations append() and
pop().
Code Example
1=[1,2,2]
print(len(l)) #3
[1, 2, 2].append(4) #[1, 2, 2, 4]
(1, 2, 4] insert(2,2) #[1, 2, 2, 4]
(1, 2,2] + [4] #(1, 2,2, 4]
(1, 2, 2, 4].remove(1) # (2, 2, 4]
(1, 2, 3].reverse() # [3, 2, 1]
(2,4, 2] sort() # [2, 2, 4]
[2,2, 4Lindex(2) # index of element 4is
“g"
[2,2, 4]index(2,1) # index of element 2
after pos 1is "1"
stack = [3]
stack.append(42) # [3, 42]
stack.pop() #42 (stack: [3])
stack,pop() # 3 (stack: (])Keyword
Set
Dictionary
Reading And
Writing
Elements
Dictionary
Looping
Membership
Operator
List And Set
Comprehension
Description
Asetis an unordered collection of
elements. Each can exist only once.
The dictionary isa useful data structure for
storing (key, value) pairs.
Read and write elements by specifying the
key within the brackets. Use the keys() and
values() functions to access all keys and
values of the dictionary.
You can loop over the (key, value) pairs of
a dictionary with the items() method.
Check with the ‘in’ keyword whether the
set, list, or dictionary contains an element.
Set containment is faster than list
containment.
List comprehension is the concise Python
way to create lists. Use brackets plus an
expression, followed by a for clause. Close
with zero or more for or if clauses.
Set comprehension is similar to list
comprehension.
Code Example
basket = {'apple', ‘eggs’, ‘banana’,
‘orange'}
same = set(['apple’, ‘eggs’, ‘banana’,
‘orange'])
calories = {'apple’ : 52, banana’ : 89,
‘choco’ :546}
print(caloriesf'apple'] < calories{'choco'])
# True
calories['cappu'] = 74
print(caloriesf'banana'] <
calories['cappu'}) # False
print(‘apple’ in calories.keys()) # True
print(52 in calories.values()) # True
for k, v in calories.items():
print(k) if v> 500 else None # ‘chocolate’
basket = {‘apple’, ‘eggs’, ‘banana’,
‘orange’}
print(‘eggs' in basket} # True
print('mushroom' in basket} # False
# List comprehension
1=[CHi'+x)for xin [Alc Bob’, Pete]
print()# (Hi Alice, Hi Bob’, 'Hi Pete’)
I2= [x* y fr x in range(3) for yin range(3) ify)
print(I2)# (0, 0,2)
4 Set comprehension
squares = {x"*2 or x in [0,24] ifx<4} 4 {0,4}Keyword
Classes
Instance
Classes
Description
Acdass encapsulates data and functionality
~ data as attributes, and functionality as
methods. Itis a blueprint to create
concrete instances in the memory.
7 ~ Instance”
tributes
Name gy e
sate a
Color v
Methods
Command)
Bark(Freq)
You are an instance of the class human. An
instance is a concrete implementation of a
Class: all attributes of an instance have a
fixed value. Your hair is blond, brown, or
black - but never unspecified.
Each instance has its own attributes
independent of other instances. Yet, class
variables are different. These are data
values associated with the class, not the
instances. Hence, all instance share the
same class variable species in the example.
Code Example
class Dog:
Blueprint of a dog
# class variable shared by all instances
species = ["canis lupus"]
def __init_(self, name, color):
self.name = name
selfstate = "sleeping"
self.color = color
def command(self, x):
ifx==self.name:
self.bark(2)
elifx=="sit":
self.state= "sit"
else:
self.state = "wag tail”
def bark(self, freq):
for iin range(freq):
print("(" + self.name
+"); Woof!")
bello = Dog("bello", "black")
alice = Dog("alice", "white"
print(bello.color) # black
print(alice.color) # white
bello.bark(1) # [bello]: Woof!Keyword
Self
Creation
Description
The first argument when defining any
method is always the self argument. This
argument specifies the instance on which
you call the method.
Self gives the Python interpreter the
information about the concrete instance.
To define a method, you use self to modify
the instance attributes. But to call an
instance method, you do not need to
specify self.
You can create classes “on the fly” and use
them aslogical units to store complex data
types.
class Employee():
pass
employee = Employee()
employee.salary = 122000
employee.firstname = “alice”
employee.lastname = "wonderland"
print(employee-firstname +" "
+employee.lastname +" "
+ str(employee.salary) + "S")
# alice wonderland 122000
Code Example
alice.command("sit")
print("[alice]:" + alice.state)
# [alice]: sit
bello.command("nio")
print("[bello}: " + bello.state)
4# {bello}: wag tall
alice.command("alice")
# [alice]: Woof!
# [alice]: Woof!
bello.species += ["Wulf"]
print(len(bello.species)
== len(alice.species)) # True (!)
DID YOU LIKE THIS
POST?
TELL US IN THE COMMENTS BELOW!
DROP A ag FOR MORE SUCH VALUABLE
CONTENT!