Back to Cheatsheets

python

Table of Contents

1. SYNTAX

2. STRINGS

3. FUNCTIONS

4. CONTROL FLOW

5. LISTS

5. LOOPS

6. MODULES

7. DICTIONARIES

8. FILES

9. CLASSES

SYNTAX

Escape Sequences

Comments

# This is an inline comment

"""
This is a multi-line comment.
So I can write as much as I want.
"""

Variables

var_name = var_value

Errors

Numbers

Calculations

None

STRINGS

"This is a string"
'This is also a string'

Concatenate

Slicing / Splitting

Formatting

Printing with arguments

'This is {} string'.format(argument1)`

'This is {argument1} string'.format(argument1=argument1)

FUNCTIONS

def func_name(param1, param2 = default):
    # do something here
    return func_value

Return

LAMBDA

func_name = lambda param: return
lambda x: outcome_if_true if conditional else outcome_if_false

Parameters

Arguments

Positional Argument Unpacking

def func_name(*args):
  var_name = args[0]
  for arg in args[1:]:
    #do something
  return var_name

Keyword Arguments

Keyword Argument Unpacking

def func_name(**kwargs):

Decorators

def decorator_name(func_name):
  def wrapper(*args, **kwargs):
    # do stuff
    func_name(*args, **kwargs)
  return wrapper

@decorator_name
def func_name(param):
  # do stuff

CONTROL FLOW

Boolean Expressions

Boolean Operators

Relational Operators

Conditional statement

if (this is True):
    # do something
elif (this is True):
    # and if condition not met
    # do something
else: 
    # none of above conditions have been met
    # do something

Try and Except

try:
    # some statement
except ErrorName:
    # this error occured so stop and do this

LISTS

list_name = [item1, item2]

Create

Combine

Sort

Index

list_name[num]

Manipulate

List Comprehension

LOOPS

for

for temp_item in list_name:
    # each item in list does this

nested

for small_list in big_list:
    for item in small_list:
        # do something

while

while condition == True:
    # keep going

MODULES

Import

from module_name import object_name as alias_name
from file_name import func_name

datetime

from datetime import datetime

random

import random

pyplot

from matplotlib import pyplot as plt 

decimal

from decimal import Decimal

DICTIONARIES

dict_name = {"key1": value1, "key2": value2}

Add pair

my_dict["new_key"] = "new_value"

Add multiple pairs

dict_name.update({pairs})

Update value

my_dict["existing_key"] = "new_value_to_replace"

my_dict["existing_key"] += value

Combine lists into dictionary

dict_name = {key:value for key, value in zip(list1_name, list2_name)}

Get Value

dict_name.get(key, value_if_none)

OR

dict_name['key']

Delete Pair

dict_name.pop(key, default_if_none)

Get all keys

list(dict_name)
dict_name.keys()

Get all values

dict_name.values()
list(dict_name.values())

Get both

dict_name.items()

FILES

with open('file_name.txt', 'r') as file_var:
  # do something

TXT FILES

Read all

with open('file_name.txt') as file_var:
  file_contents = file_var.read()

Read line by line

with open('file_name.txt') as file_var:
  for line in file_var.readlines():
    # do something

Read a line

with open('file_name.txt') as file_var:
  first_line = file_var.readline()
  second_line = file_var.readline()

Write

with open('file_name.txt', 'w') as file_var:
  file_var.write("Text to go in file")

Append

with open('file_name.txt', 'a') as file_var:
    file_var.write("Text to add to file")

Old way

file_variable = open('file_name.txt', 'a')
file_variable.write("Text to add")
file_variable.close()

CSV

col1, col2, col3
row1_value1, row1_value2, row1_value3
row2_value1, row2_value2, row2_value3

Import CSV

import csv

Read CSV

list_to_append = []
with open('file_name.csv', newline='') as file_var:
  file_reader = csv.DictReader(file_var, delimiter=',')
  for row in file_reader:
    list_to_append.append(row['csv_col_name'])

Write CSV

data_to_write = [{'col1': row1_value1, 'col2': row1_value2, 'col3': row1_value3},
                {'col1': row2_value1, 'col2': row2_value2, 'col3': row2_value3}]

with open('new_file_name.csv', 'w') as file_var:
  fields = ['col1', 'col2', 'col3']
  output_writer = csv.DictWriter(file_var, fieldnames=fields)

  output_writer.writeheader()
  for item in data_to_write:
    output_writer.writerow(item)

JSON

{
    'key1': value1,
    'key2': value2,
    'key3': value3,
}

Import

import json

Read JSON

with open('file_name.json') as file_var:
  data_var = json.load(file_var)

Write JSON

data_to_write = {dictionary_values}

with open('new_file_name.json', 'w') as file_var:
  json.dump(data_to_write, file_var)

CLASSES

Define

class ClassName:
  pass

Object

var_name = ClassName(params_for_init)

### Class Variables

class ClassName:
  class_var = ""

Methods

class ClassName:

  def method_name(self, args):
    var_name = self.class_var # do something

Constructors (__init__)

class ClassName:
  def __init__(self, param):
    self.param = param
    # do something

Instance Variables

object_name.instance_var = ''

Attributes

String Representation (__repr__)

class ClassName
  def __repr__(self):
    # return a string

Inheritance

class BaseClassName:
  def __init__(self, param):
    self.param = param

class SubClassName(BaseClassName)
  def __init__(self, param, param2)
    super().base_class_func_name(param)
    self.param2 = param2

Exceptions

class NewExceptionName(Exception):
  # do something

Interfaces

class Class1:
  def func1():
    #do stuff
class Class2:
  def func1():
    # do stuff

obj_name.func1()    

Dunder Methods

def __dunder__(self, params):