0% found this document useful (0 votes)
2 views

Python cheatsheet

The document provides an overview of various Python data types and methods, including strings, lists, sets, dictionaries, and tuples. It covers basic operations, functions, and advanced concepts such as named tuples and ordered dictionaries. Additionally, it highlights the use of lambda functions, comprehensions, and various Python operators.

Uploaded by

jameshyh88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python cheatsheet

The document provides an overview of various Python data types and methods, including strings, lists, sets, dictionaries, and tuples. It covers basic operations, functions, and advanced concepts such as named tuples and ordered dictionaries. Additionally, it highlights the use of lambda functions, comprehensions, and various Python operators.

Uploaded by

jameshyh88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Strings – Basic Methods List – Remove from a List Sets – Joins & Subsets Named Tuple

Content Overview
Dictionary – Intro
' I am alone '.strip() [1,2,3].pop() Also known as mappings or hash tables. They are key value set1 = {1,2,3} • Tuple is an immutable and hashable list.
# 'I am alone' --> Strips all whitespace characters from # 3 --> mutates original list, default index in the pop pairs that are guaranteed to retain order of insertion. • Named tuple is its subclass with named elements.
Functions set2 = {3,4,5}
Python Types • Functions both method is -# 1 (the last item) from collections import namedtuple
my_dict = {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': set3 = set1.union(set2) # {1,2,3,4,5}
• Number • Lambda # ends. Point = namedtuple('Point', 'x y')
[1,2,3].pop(1) # 2 --> mutates original list False} set4 = set1.intersection(set2) # {3}
• Strings • Comprehensions p = Point(1, y=2)# Point(x=1, y=2)
'On an island'.strip('d’) [1,2,3].remove(2) set5 = set1.difference(set2) # {1, 2}
• Boolean Dictionary – Accessing key-value pair p[0] # 1
• Ternary # 'On an islan' --> # Strips all passed characters from # None --> [1,3] Removes first occurrence of item or raises set6 = set1.symmetric_difference(set2)# {1, 2, 4, 5}
• Dictionary • Map, Filter, Reduce my_dict['name'] # Andrei Neagoie p.x # 1
both # ends. # ValueError. set1.issubset(set2) # False
• Tuples • Any & All my_dict.get('age') # 30 --> Returns None if key does not getattr(p, 'y') # 2
set1.issuperset(set2) # False
• Sets • Closures 'but life is good!'.split() # ['but', 'life', 'is', 'good!'] [1,2,3].clear() exist. p._fields # Or: Point._fields #('x', 'y’)
set1.isdisjoint(set2) # False --> return True if two sets have a
• None • Scope 'Help me'.replace('me', 'you’) # None --> mutates original list and removes all items: [] my_dict.get('ages', 0 ) # 0 --> Returns default (2nd param) if null intersection. from collections import namedtuple
Basics # 'Help you' --> Replaces first with second param key
Advanced Python del [1,2,3].[0] Sets – Frozenset Person = namedtuple('Person', 'name height')
• Comparison Operator • Modules # is not found person = Person('Jean-Luc', 187)
'Need to make fire'.startswith('Need')# True # This aims to delete the 1st element to give [2,3] Dictionary – Special functions
• Logical Operator 'and cook rice'.endswith('rice') # True # hashable --> it can be used as a key in a dictionary or as an f'{person.height}' # '187'
• Iterators List – Ordering
• Loops 'bye bye'.index(e) # 2 len(my_dict) # 3 # element in a set. '{p.height}'.format(p=person)# '187'
• Decorators
• Range 'still there?'.upper() # STILL THERE? [1,2,5,3].sort() list(my_dict.keys()) # ['name', 'age', 'magic_power'] <frozenset> = frozenset(<collection>)
• Class OrderedDict
• Enumerate 'HELLO?!'.lower() # hello?! # None --> Mutates list to [1, 2, 3, 5] list(my_dict.values()) # ['Andrei Neagoie', 30, False]
• Type Excel None • Maintains order of insertion.
• Counter 'ok, I am done.'.capitalize() # 'Ok, I am done.’ list(my_dict.items())
• File IO [1,2,5,3].sort(reverse=True) from collections import OrderedDict
• Named Tuple # [('name', 'Andrei Neagoie'), ('age', 30), ('magic_power', type(None) # NoneType
• Useful libraries 'oh hi there'.find('i’) # None --> Mutates list to [5, 3, 2, 1] # Store each person's languages, keeping
• Ordered Dictionary False)] a = None
# 4 --> returns the starting index position of the first Dictionary – Adding & changing key-value pair # track of who responded first.
[1,2,5,3].reverse()
# occurrence Comparison Operators programmers = OrderedDict()
# None --> Mutates list to [3, 5, 2, 1] my_dict['favourite_snack'] = 'Grapes’
'oh hi there'.count('e') # 2 programmers['Tim'] = ['python', 'javascript']
/*{'name': 'Andrei Neagoie', 'age': 30, == # equal values programmers['Sarah'] = ['C++']
Strings – String Formatting sorted([1,2,5,3])
'magic_power': False, != # not equal programmers['Bia'] = ['Ruby', 'Python', 'Go']
name1 = 'Andrei' # [1, 2, 3, 5] --> new list created
'favourite_snack': 'Grapes’} */ > # left operand is greater than right operand
NUMBERS - Types name2 = 'Sunny' list(reversed([1,2,5,3])) < # left operand is less than right operand for name, langs in programmers.items():
Python’s main types are int and float print(f'Hello there {name1} and {name2}’) my_dict.update({'cool': True}) print(name + '-->’)
# [3, 5, 2, 1] --> reversed() returns an iterator >= # left operand is greater than or equal to right operand
# Hello there Andrei and Sunny /* {'name’: 'Andrei Neagoie’, for lang in langs:
type(1) # int List – Useful Operations <= # left operand is less than or equal to right operand
# Newer way to do things as of python 3.6 'age': 30, print('\t' + lang)
type(-10) # int <element> is <element> # check if two operands refer to same
1 in [1,2,5,3] # True 'magic_power': False,
type(0) # int print('Hello there {} and {}'.format(name1, name2)) # object in memory
min([1,2,3,4,5])# 1 'favourite_snack': 'Grapes’, Functions - *args and **kwargs
type(0.0) # float # Hello there Andrei and Sunny max([1,2,3,4,5])# 5 'cool': True} */ Logical Operators • Splat (*) expands a collection into positional arguments,
type(2.2) # float
type(4E2) # float - 4*10 to the power of 2 print('Hello there %s and %s' %(name1, name2)) sum([1,2,3,4,5])# 15 1 < 2 and 4 > 1 # True while splatty-splat (**) expands a dictionary into
{**my_dict, **{'cool': True} }
# Hello there Andrei and Sunny List – Get 1st and last elements /* {'name’: 'Andrei Neagoie’, 1 > 3 or 4 > 1 # True keyword arguments.
NUMBERS – Arithmetic Operators # --> you can also use %d, %f, %r for integers, floats, 1 is not 4 # True args = (1, 2)
mList = [63, 21, 30, 14, 35, 26, 77, 18, 49, 10] 'age': 30,
10 + 3 # 13 string 'magic_power': False, not True # False kwargs = {'x': 3, 'y': 4, 'z': 5}
first, *x, last = mList 1 not in [2,3,4]# True
10 - 3 # 7 # representations of objects respectively 'favourite_snack': 'Grapes’, some_func(*args, **kwargs)
print(first) #63
10 * 3 # 30 Strings – Palindrome Check 'cool': True} */ if <condition that evaluates to boolean>: # same as some_func(1, 2, x=3, y=4, z=5)
print(last) #10
10 ** 3 # 1000 Dictionary – Removing key-value pair # perform action1 Functions - *Inside Function Definition
word = 'reviver'
10 / 3 # 3.3333333333333335 List – Matrix/Nested List + Indexing of one elif <condition that evaluates to boolean>: • Splat combines zero or more positional arguments into
p = bool(word.find(word[::-1]) + 1) del my_dict['name']
10 // 3 # 3 --> floor division - no decimals and returns an matrix = [[1,2,3], [4,5,6], [7,8,9]] # perform action2 a tuple, while splatty-splat combines zero or more
print(p) # True my_dict.pop('name', None)
int matrix[2][0] else: keyword arguments into a dictionary.
new_dict = my_dict.pop('favourite_snack’)
10 % 3 # 1 --> modulo operator - return the reminder. Boolean - Intro # 7 --> Grab first first of the third item in the matrix object # perform action3
# Removes item from dictionary. def add(*a):
# Good for deciding if number is even or odd List – Looping through a matrix by rows
bool(True) Dictionary – Special creation methods return sum(a)
NUMBERS – Basic Functions
bool(False) mx = [[1,2,3],[4,5,6]] new_dict = Loops – For Loops add(1, 2, 3) # 6
pow(5, 2) # 25 --> like doing 5**2 # all of the below evaluate to False. Everything else will for row in range(len(mx)): dict([['name','Andrei'],['age',32],['magic_power',False]]) # my_list = [1,2,3] Functions - Ordering of parameters
abs(-50) # 50 # evaluate to True in Python. for col in range(len(mx[0])): Creates a dict from collection of key-value pairs. my_tuple = (1,2,3)
print(mx[row][col]) # 1 2 3 4 5 6 def f(*args): # f(1, 2, 3)
round(5.46) # 5 print(bool(None)) my_list2 = [(1,2), (3,4), (5,6)]
new_dict = dict(zip(['name','age','magic_power'],['Andrei',32, def f(x, *args): # f(1, 2, 3)
round(5.468, 2)# 5.47 --> round to nth digit print(bool(False)) List – Transform into a list my_dict = {'a': 1, 'b': 2. 'c': 3}
False])) def f(*args, z): # f(1, 2, z=3)
bin(512) # '0b1000000000' --> binary format print(bool(0)) [mx[row][col] for row in range(len(mx)) for col in for num in my_list:
# Creates a dict from two collections. def f(x, *args, z): # f(1, 2, z=3)
hex(512) # '0x200' --> hexadecimal format print(bool(0.0)) range(len(mx[0]))] Dictionary – Dictionary Comprehension print(num) # 1, 2, 3
def f(**kwargs): # f(x=1, y=2, z=3)
print(bool([])) #[1,2,3,4,5,6] {key: value for key, value in new_dict.items() if key == 'age' for num in my_tuple:
NUMBERS – Converstion of strings to numbers def f(x, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
print(bool({})) List – Combine columns with zip and * or key == 'name'} print(num) # 1, 2, 3
age = input("How old are you?") print(bool(())) # {'name': 'Andrei', 'age': 32} --> Filter dict by keys for num in my_list2: def f(*args, **kwargs):
coordinate = ['x', 'y', 'z']
age = int(age) print(bool('')) print(num) # (1,2), (3,4), (5,6) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
value = [3, 4, 5] Tuples – Intro
pi = input("What is the value of pi?") print(bool(range(0))) for num in '123’:
pi = float(pi) print(bool(set())) result = zip(coordinate, value) Like lists, but they are used for immutable things. print(num) # 1, 2, 3 def f(x, *args, **kwargs):
result_list = list(result) for k,v in my_dict.items(): # Dictionary Unpacking # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
List - Intro my_tuple = ('apple','grapes','mango', 'grapes')
Strings - Intro Unlike strings, lists are mutable sequences in python. print(result_list) print(k) # 'a', 'b', 'c’ def f(*args, y, **kwargs):
Tuples – Accessing Elements
Stored as sequences of letters in memory. print(v) # 1, 2, 3 # f(x=1, y=2, z=3) | f(1, y=2, z=3)
my_list = [1, 2, '3', True] c, v = zip(*result_list) apple, grapes, mango, grapes = my_tuple # Tuple unpacking
type('Hellloooooo') # str Loops – While Loops Other Uses of *
# We assume this list won't mutate for each example below print('c =', c) len(my_tuple) # 4
'I\'m thirsty' len(my_list) # 4 print('v =', v) while <condition that evaluates to boolean>: [*[1,2,3], *[4]] # [1, 2, 3, 4]
my_tuple[2] # mango
"I'm thirsty" my_list.index('3') # 2 List – List Comprehension # action {*[1,2,3], *[4]} # {1, 2, 3, 4}
my_tuple[-1] # 'grapes'
"\n" # new line my_list.count(2) # 1 --> count how many times 2 appears # new_list[<action> for <item> in <iterator> if <some if <condition that evaluates to boolean>: (*[1,2,3], *[4]) # (1, 2, 3, 4)
"\t" # adds a tab Tuples – Immutability property
condition>] break # break out of while loop {**{'a': 1, 'b': 2}, **{'c': 3}} # {'a': 1, 'b': 2, 'c': 3}
List – Indexing & Slicing my_tuple[1] = 'donuts' # TypeError
Strings – Indexing & Slicing a = [i for i in 'hello'] # ['h', 'e', 'l', 'l', '0'] if <condition that evaluates to boolean>:
# : is called slicing and has the format [ start : end : step ] my_tuple.append('candy')# AttributeError continue # continue to the next line in the block head, *body, tail = [1,2,3,4,5]
b = [i*2 for i in [1,2,3]] # [2, 4, 6]
'Hey you!'[4] # y my_list[3] # True c = [i for i in range(0,10) if i % 2 == 0]# [0, 2, 4, 6, 8] Tuples – Methods
# waiting until user quits Lambda
name = 'Andrei Neagoie' my_list[1:] # [2, '3', True] List – Advanced Functions my_tuple.index('grapes') # 1 msg = '' # lambda: <return_value>
name[4] # e my_list[:1] # [1] my_tuple.count('grapes') # 2 while msg != 'quit’: # lambda <argument1>, <argument2>: <return_value>
my_list[-1] # True list_of_chars = list('Helloooo’) Tuples – Zipping and Unzipping
# : is called slicing and has the format [ start : end : step ] msg = input("What should I do?")
my_list[::1] # [1, 2, '3', True] # ['H', 'e’, 'l', 'l', 'o', 'o', 'o', 'o’] # Factorial
name[:] # Andrei Neagoie print(msg)
my_list[::-1] # [True, '3', 2, 1] # Zip from functools import reduce
name[1:] # ndrei Neagoie sum_of_elements = sum([1,2,3,4,5]) # 15
my_list[0:3:2] # [1, '3'] list(zip([1,2,3], [4,5,6])) # [(1, 4), (2, 5), (3, 6)] Range n=3
name[:1] # A
List – Adding to a List element_sum = [sum(pair) for pair in zip([1,2,3],[4,5,6])] # unzip range(10) # range(0, 10) --> 0 to 9 # Fibonacci
name[-1] # e
# [5, 7, 9] z = [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip() function range(1,10) # range(1, 10) --> 1 to 9 fib = lambda n : n if n <= 1 else fib(n-1) + fib(n-2)
name[::1] # Andrei Neagoie my_list * 2 # [1, 2, '3', True, 1, 2, '3', True]
name[::-1] # eiogaeN ierdnA my_list + [100] sorted_by_second = sorted(['hi','you','man'], key=lambda unzip = lambda z: list(zip(*z)) list(range(0,10,2))# [0, 2, 4, 6, 8] result = fib(10)
name[0:10:2]# Ade e # [1, 2, '3', True, 100] --> doesn't mutate original list, el: el[1]) unzip(z) Enumerate print(result) #55
creates # ['man','hi', 'you’] Comprehensions
Strings – Concatenation for i, el in enumerate('helloo'):
# new one Sets – Intro
'Hi there ' + 'Timmy' # 'Hi there Timmy’ # lambda arguments : expression print(f'{i}, {el}') <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
my_list.append(100) sorted_by_key = sorted([{'name': 'Bina', 'age': 30}, Unordered collection of unique elements. # 0, h <set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
'*'*10 # ********** my_set = set()
# None --> Mutates original list to [1, 2, '3', True,100] {'name':'Andy', 'age': 18}, # 1, e <iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
Strings – Basic String Functions my_set.add(1) # {1} <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
# Or: <list> += [<el>] {'name': 'Zoey', 'age': 55}], # 2, l
len('turtle') # 6 my_set.add(100)# {1, 100}
key=lambda el: (el['name’])) # 3, l output = [i+j for i in range(3) for j in range(3)]
my_list.extend([100, 200]) my_set.add(100)# {1, 100} --> no duplicates!
/* Sorting 2nd characters alphabetically ('a', 'i', 'o'), the # 4, o # [0, 1, 2, 1, 2, 3, 2, 3, 4]
# None --> Mutates original list to [1, 2, '3', True, 100, 200] Sets – List to set conversion
corresponding words are rearranged.*/ # 5, o
my_list.insert(2, '!!!’) # Is the same as:
/* [{'name': 'Andy', 'age':18}, new_list = [1,2,3,3,3,4,4,5,6,1]
# None --> [1, 2, '!!!', '3', True] - Inserts item at index and Counter output = []
{'name': 'Bina', 'age': 30}, set(new_list) # {1, 2, 3, 4, 5, 6}
moves # the rest to the right. for i in range(3):
{'name': 'Zoey', 'age': 55}]*/ Sets – Remove elements and copy over from collections import Counter for i in range(3):
' '.join(['Hello','There’]) colors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue'] output.append(i+j)
my_set.remove(100) # {1} --> Raises KeyError if element not
# 'Hello There' --> Joins elements using string as separator. List – Read Line of a file into a list counter = Counter(colors)# Counter({'blue': 3, 'red': 2,
found Ternary Condition
List – Copy a List with open("myfile.txt") as f: my_set.discard(100) # {1} --> Doesn't raise an error if 'yellow': 1})
counter.most_common()[0] # ('blue', 3) # <expr_if_true> if <condition> else <expr_if_false>
basket = ['apples', 'pears', 'oranges'] lines = [line.strip() for line in f] element not # found [a if a else 'zero' for a in [0, 1, 0, 3]] # ['zero', 1, 'zero', 3]
new_basket = basket.copy() my_set.clear() # {}
new_basket2 = basket[:] new_set = {1,2,3}.copy()# {1,2,3}
Map, Filter, reduce Iterators – For Custom Objects Class – Properties Useful Libraries – CSV Datetime – Timezone
from functools import reduce class PrintNumber: import csv
class Car: <tz> = UTC # UTC timezone.
list(map(lambda x: x + 1, range(10))) def __init__(self, max): def __init__(self, name): # Read CSV <tz> = tzlocal() # Local timezone.
# [1, 2, 3, 4, 5, 6, 7, 8, 9,10] self.max = max self.name = "Jimmy” def read_csv_file(filename): <tz> = gettz(‘<Cont.>/<City>' # Timezone from 'Continent/City_Name' str.
# iter() method in a class print(Car.name) # Jimmy with open(filename, encoding='utf-8') as file:
list(filter(lambda x: x > 5, range(10))) print(Car(“Sam”).name # Sam return csv.reader(file, delimiter=';’) <DTa> = <DT>.astimezone(<tz>) # Datetime, converted to passed
# (6, 7, 8, 9) def __iter__(self):
Class – Inheritance timezone.
self.num = 0 # Write rows to CSV <Ta/DTa> = <T/DT>.replace(tzinfo=<tz>) # Unconverted object with new
list(reduce(lambda acc, x: acc + x, range(10))) return self class Animal:
def write_to_csv_file(filename, rows): # timezone.
# 45 # next() method in a class def breathe(self):
with open(filename, 'w', encoding='utf-8') as file:
Any & All def __next__(self): print("breathing")
writer = csv.writer(file, delimiter=';’) Regex – Intro
any([False, True, False]) if(self.num >= self.max): class Fish(Animal):
writer.writerows(rows)
# True if at least one item in collection is true, False if raise StopIteration def breathe(self): import re
Useful Libraries – JSON
empty self.num += 1 super.breathe() <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
return self.num print("underwater") re.sub(r'cat', 'dog', 'I love my cat') # 'I love my dog’
all([True,1,3,True]) import json
nemo = Fish()
# True if all items in collection are true print_num = PrintNumber(3) <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
nemo. breathe() <list> = re.findall(<regex>, text) # Returns all occurrences.
<object> = json.loads(<str>)
Closures print_num_iter = iter(print_num) #breathing re.findall(r'\d+', 'Order 123, item 456') # ['123', '456']
We have a closure when: print(next(print_num_iter)) # 1 #underwater
# Read Object From JSON File <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the
• A nested function references a value of its enclosing print(next(print_num_iter)) # 2 Class – Multiple Inheritance def read_json_file(filename): matches.
function print(next(print_num_iter)) # 3 class A: pass with open(filename, encoding='utf-8') as file: re.split(r'[, ]+', 'apple, orange banana') # ['apple', 'orange', 'banana']
• The enclosing function returns the nested function. class B: pass
# raises StopIteration return json.load(file)
• If multiple nested functions within enclosing function class C(A, B): pass <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
reference the same value, that value gets shared. print(next(print_num_iter)) re.search(r'\d+', 'Order 123').group() # '123'
C.mro() # Write Object To JSON File
• To dynamically access function's first free variable use Decorators – Simple Functions # Order of traversal when searching for a method >> def write_to_json_file(filename, an_object): <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
'<function>.__closure__[0].cell_contents' def decorator(func): [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>] with open(filename, 'w', encoding='utf-8') as file: re.match(r'Hello', 'Hello World') # Match object
def get_multiplier(a): def wrapper(): json.dump(an_object, file, ensure_ascii=False, indent=2)
def out(b): print("Before calling the function.") Try Except – Error Types Regex – Special Sequences
return a * b func() # Syntax Error • Expressions below hold true for strings that contain only ASCII
Useful Libraries – Pickle
return out print("After calling the function.") print(12 + 4)) characters.
return wrapper import pickle • Use capital letters for negation.
multiply_by_3 = get_multiplier(3) # Name Error <bytes> = pickle.dumps(<object>) '\d' == '[0-9]' # Digit
multiply_by_3(10) # 30 # Applying the decorator to a function my_number = 4 <object> = pickle.loads(<bytes>) '\s' == '[ \t\n\r\f\v]' # Whitespace
@decorator my_num + 2 '\w' == '[a-zA-Z0-9_]' # Alphanumeric
Scope # Read Object From File
def greet():
If variable is being assigned to anywhere in the scope, it is # Zero Division Error def read_pickle_file(filename):
print("Hello, World!")
regarded as a local variable, unless it is declared as a 5%0 with open(filename, 'rb’) as file:
'global' or a 'nonlocal'. greet() Try Except – Except return pickle.load(file)
def get_counter(): # Before calling the function. while True:
# Hello, World! # Write Object To File
i=0 try:
# After calling the function. def write_to_pickle_file(filename, an_object):
def out(): x = int(input('Enter your age: '))
Decorators – Methods, Class, chaining with open(filename, 'wb') as file:
nonlocal i except ValueError:
def method_decorator(func): pickle.dump(an_object, file)
i += 1 print('Oops! That was no valid number. Try
return i def wrapper(self, *args, **kwargs): again...’)
print("Before method execution") Useful Libraries – Time
return out else:
res = func(self, *args, **kwargs) # code that depends on the try block running successfully from time import time
counter = get_counter() print("After method execution") start_time = time() # Seconds since
# should be placed in the else block.
counter(), counter(), counter() return res ...
print('Carry on!’)
# (1, 2, 3) return wrapper duration = time() - start_time
break
Module Useful Libraries – Math
class MyClass: Try Except – Raising Exceptions
from math import e, pi
# Default: Runs main() if file wasn't imported. @method_decorator x = "hello" from math import cos, acos, sin, asin, tan, atan, degrees,
if __name__ == '__main__’: def say_hello(self): radians
main() print("Hello!") if not type(x) is int: from math import log, log10, log2
raise TypeError("Only integers are allowed") from math import inf, nan, isinf, isnan
import <module_name> obj = MyClass()
Try Except – Finally Useful Libraries – Statistics
from <module_name> import <function_name> obj.say_hello()
from statistics import mean, median, variance, pvariance,
import <module_name> as m # Before method execution try:
pstdev
from <module_name> import <function_name> as # Hello! raise KeyboardInterrupt
m_function except: Useful Libraries – Random
# After method execution
from <module_name> import * Decorators – Class print('oops') from random import random, randint, choice, shuffle
def fun(cls): finally: random() # random float between 0 and 1
cls.class_name = cls.__name__ print('All done!') randint(0, 100) # random integer between 0 and 100
Iterators – Basic Level random_el = choice([1,2,3,4]) # select a random element
• Built-in function that returns an iterator for the given return cls File IO – Opening a file
from list
object, which then allows you to iterate over its elements @fun <file> = open('<path>', mode='r', encoding=None) shuffle([1,2,3,4]) # shuffles a list
one at a time. class Person: Modes
• Process elements of a collection sequentially without pass • 'r' - Read (default). Datetime – Intro
accessing them by index. • 'w' - Write (truncate). • Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime'
• Various iterable objects such as lists, tuples, and custom print(Person.class_name) # Person • 'x' - Write or fail if the file already exists. <DT> andc'timedelta' <TD> classes. All are immutable and
objects Decorators – Chaining hashable.
• 'a' - Append.
def decor1(func): • 'w+' - Read and write (truncate). • Time and datetime can be 'aware' <a>, meaning they have
<iter> = iter(<collection>)
def inner(): • 'r+' - Read and write from the start. defined timezone, or 'naive' <n>, meaning they don't.
<iter> = iter(<function>, to_exclusive)
x = func() • 'a+' - Read and write from the end. • If object is naive it is presumed to be in system's timezone.
# Sequence of return values until 'to_exclusive’.
return x * x • 't' - Text mode (default). from datetime import date, time, datetime, timedelta
<el> = next(<iter> [, default]) return inner • 'b' - Binary mode. from dateutil.tz import UTC, tzlocal, gets
# Raises StopIteration or returns 'default’ on end. File IO – File
def decor(func): Datetime – Constructors
def inner(): <file>.seek(0) # Moves to the start of the file. • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
# list of vowels
x = func() <str/bytes> = <file>.readline() # Returns a line. • 'fold=1' means second pass in case of time jumping back from 1 hour.
phones = ['apple', 'samsung', 'oneplus']
return 2 * x <list> = <file>.readlines() # Returns a list of lines.
phones_iter = iter(phones) from datetime import time, datetime, timedelta, date
return inner
print(next(phones_iter)) # apple <file>.write(<str/bytes>) # Writes a string or bytes object. <D> = date(year, month, day)
print(next(phones_iter)) # samsung @decor1 <file>.writelines(<list>) <T> = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None,
print(next(phones_iter)) # oneplus @decor # Writes a list of strings or bytes objects. fold=0)
def num(): <DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
File IO – Read text from file
import random return 10 <TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
def read_file(filename):
iterator = iter(lambda: random.randint(1, 5), 3) @decor with open(filename, encoding='utf-8') as file: minutes=0, hours=0, weeks=0)
for num in iterator: @decor1 return file.readlines() # or read() Datetime – Now
print(num) def num2(): <D/DTn> = datetime.date.today() # Current local date or naive datetime.
#5 for line in read_file(filename):
return 10 <DTn> = datetime.datetime.utcnow() # Naive datetime from current UTC
# 5, will stop once 3 appears print(line)
print(num()) # 400 File IO – Write Text to File time.
print(num2()) # 200 <DTa> = datetime.datetime.now(<tz>) # Aware datetime from current tz
def write_to_file(filename, text): time.
Class – __init__ with open(filename, 'w', encoding='utf-8') as file:
The init method is called every time a new object is created file.write(text)
from the class.
File IO – Append Text to File
class Car:
def append_to_file(filename, text):
def __init__(self):
with open(filename, 'a’, encoding='utf-8') as file:
print("Building car")
file.write(text)
my_toyota = Car() # "building car"

You might also like