x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Floats
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Strings
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Python Advanced Data Types
Heaps
import heapq
myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # turn myList into a Min Heap
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap
heapq.heappush(myList, 10) # insert 10
x = heapq.heappop(myList) # pop and return smallest item
print(x) # => 1
Negate all values to use Min Heap as Max Heap
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # multiply by -1 to negate
heapq.heapify(myList)
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)
Stacks and Queues
from collections import deque
q = deque() # empty
q = deque([1, 2, 3]) # with values
q.append(4) # append to right side
q.appendleft(0) # append to left side
print(q) # => deque([0, 1, 2, 3, 4])
x = q.pop() # remove & return from right
y = q.popleft() # remove & return from left
print(x) # => 4
print(y) # => 0
print(q) # => deque([1, 2, 3])
q.rotate(1) # rotate 1 step to the right
print(q) # => deque([3, 1, 2])
Python Strings
Array-like
>>> hello = "Hello, World"
>>> print(hello[1])
e
>>> print(hello[-1])
d
Get the character at position 1 or last
Looping
>>> for char in "foo":
... print(char)
f
o
o
Loop through the letters in the word "foo"
Slicing string
┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'
Check String
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True
Concatenates
>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'
Formatting
name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))
format() Method
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
Input
>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'
>>> f'{"text":10}' # [width]
'text '
>>> f'{"test":*>10}' # fill left
'******test'
>>> f'{"test":*<10}' # fill right
'test******'
>>> f'{"test":*^10}' # fill center
'***test***'
>>> f'{12345:0>10}' # fill with numbers
'0000012345'
f-Strings Type
>>> f'{10:b}' # binary type
'1010'
>>> f'{10:o}' # octal type
'12'
>>> f'{200:x}' # hexadecimal type
'c8'
>>> f'{200:X}'
'C8'
>>> f'{345600000000:e}' # scientific notation
'3.456000e+11'
>>> f'{65:c}' # character type
'A'
>>> f'{10:#b}' # [type] with notation (base)
'0b1010'
>>> f'{10:#o}'
'0o12'
>>> f'{10:#x}'
'0xa'
>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']
Access
>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
class Dog:
# Method of the class
def bark(self):
print("Ham-Ham")
charlie = Dog()
charlie.bark() # => "Ham-Ham"
Class Variables
class MyClass:
class_variable = "A class variable!"
# => A class variable!
print(MyClass.class_variable)
x = MyClass()
# => A class variable!
print(x.class_variable)
Super() Function
class ParentClass:
def print_test(self):
print("Parent Method")
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's print_test()
super().print_test()
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # => John
User-defined exceptions
class CustomError(Exception):
pass
Polymorphism
class ParentClass:
def print_self(self):
print('A')
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self() # => A
obj_B.print_self() # => B
Overriding
class ParentClass:
def print_self(self):
print("Parent")
class ChildClass(ParentClass):
def print_self(self):
print("Child")
child_instance = ChildClass()
child_instance.print_self() # => Child
Inheritance
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
Miscellaneous
Comments
# This is a single line comments.
""" Multiline strings can be written
using three "s, and are often used
as documentation.
"""
''' Multiline strings can be written
using three 's, and are often used
as documentation.
'''
Generators
def double_numbers(iterable):
for i in iterable:
yield i + i
Generators help you make lazy code.
Generator to list
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
# => [-1, -2, -3, -4, -5]
print(gen_to_list)
Handle exceptions
try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
See:
See:
See:
See:
See:
See:
See:
The / means quotient of x and y, and the // means floored quotient of x and y, also see
See:
See:
See:
Heaps are binary trees for which every parent node has a value less than or equal to any of its children. Useful for accessing min/max value quickly. Time complexity: O(n) for heapify, O(log n) push and pop. See:
Deque is a double-ended queue with O(1) time for append/pop operations from both sides. Used as stacks and queues. See: