Cheat Sheets #3: Python Essentials, Object Oriented, Data Structures, Complexities, Flask

1. Python Basics Cheat Sheet

Source:- https://intellipaat.com/blog/tutorial/python-tutorial/python-cheat-sheet-basics/

Basic:

Basic rules to write Python syntax:

Rule #1: Python is white-space dependent; code blocks are indented using spaces.
Rule #2: Python language is case sensitive. It matters for variables, functions and any keyword in general.

Data Types

  • Numbers: a=2(Integer), b=2.0(Float), c=1+2j(Complex)
  • List: a=[1,2,3,’Word’]
  • Tuple: a= (1,2,4)
  • String: a=“New String”
  • Sets: a= {2,3,4,5}
  • Dictionary: x= {‘a’: [1,2],‘b’: [4,6]

Operators

Numeric Operator (Say, a holds 5, b holds 10)

  • a + b = 15
  • a — b = -5
  • a * b = 50
  • b/a = 2
  • b % a = 0
  • a**b =510
  • 0//2.0 = 3.0, -11//3 = -4

Comparison Operator

  • (a == b): not true
  • (a!= b): true
  • (a > b): not true.
  • (a > b): not true
  • (a >= b): not true
  • (a <= b) is true

Boolean Operator

  • a and b
  • a or b
  • not a

Operations

List Operations

  • List=[]:Defines an empty list
  • list[i]=a: Stores a at the ith position
  • list[i]: Retrieves the character at the ith position
  • list[i:j]: Retrieves characters in the range i to j
  • append(val): Adds item at the end
  • pop([i]): Removes and returns item at index i

String Operations

  • String[i]: Retrieves the character at the ith position
  • String[i:j]: Retrieves characters in the rangei to j

Dictionary Operations

  • dict={} : Defines an empty dictionary
  • dict[i]=a: stores “a” to the key “i”
  • dict[i]: Retrieves the item with the key “i”
  • key: Gives all the key items
  • values: Gives all the values

Flow Control Method:

if-else (Conditional Statement):

For loop (Iterative Loop Statement):

While loop (Conditional Loop Statement):

Functions

def new_function():
print(“Hello World”)
new_function()

Lambda Function

lambda a,b: a+b
lambda a,b: a*b

Generic Operations

  • range(5): 0,1,2,3,4
  • S=input(“Enter:”)
  • Len(a): Gives item count in a
  • min(a): Gives minimum value in a
  • max(a): Gives minimum value in a
  • sum(a): Adds up items of an iterable and returns sum
  • sorted(a): Sorted list copy of a
  • importing modules: import random

File Operations:

  • “r” — Read — Default value. Opens a file for reading, error if the file does not exist
  • “a” — Append — Opens a file for appending, creates the file if it does not exist
  • “w” — Write — Opens a file for writing, creates the file if it does not exist
  • “x” — Create — Creates the specified file, returns an error if the file exists

Try & Except Block:

try:
[Statement body block]
raise Exception()
except Exception as e:
[Error processing block]

Oops Concepts

  • Inheritance: A process of using details from a new class without modifying existing class.
  • Polymorphism: A concept of using common operation in different ways for different data input.
  • Encapsulation: Hiding the private details of a class from other objects.
Source :- https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/

Class/object Example:

Class: class Pen:
pass
object:obj=Pen()

Data Structures

The areas in which Data Structures are applied:

  • Compiler design
  • Operating system
  • Database Management System
  • Statistical Analysis Package
  • Numerical Analysis
  • Graphics
  • Artificial Intelligence
  • Simulations

Data structures used in the following areas:

  • RDBMS: Array (Array of structure)
  • Network data model: Graph
  • Hierarchical Data model: Trees

Types of Data Structures:

Primitive Data Structures:

  • We can use * to repeat the string for a specific number of times
  • String can be sliced, that is to select parts of the string
z1 = x[2:]
print(z1)
# Slicing
z2 = y[0] + y[1]
print(z2)
Output: ke
Co
  • To capitalize the strings
str.capitalize('cookie')
  • To retrieve the length of the strings
str1 = "Cake 4 U"
str2 = "404"
len(str1)
  • To replace parts of a string with another string
str1.replace('4 U', str2)
  • Boolean: It is a built-in data type that can take the values TRUE or FALSE

Non- Primitive Data Structures:

  • Array: It is a compact way of collecting data types where all entries must be of the same data type.
import array as arr
a = arr.array("I",[3,6,9])
type(a)
  • Linked list: List in Python is used to store collection of heterogeneous items. It is described using the square brackets [] and hold elements separated by comma
x = [] # Empty list
type(x)
  • Stack: It is a container of objects that can be inserted or removed according to LIFO (Last in First Out) pop() method is used during disposal in Python
stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 -> 5 (Top)
stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 (Top)
print(stack)
  • Queue: It is a container of objects that can be inserted or removed according to FIFO (First in First Out)
  • Graph: It is a data structure that consists of a finite set of vertices called nodes, and a finite set of ordered pair (u,v) called edges. It can be classified as direction and weight
  • Binary Tree: Tree is a hierarchical data structure. Here each node has at most two children
  • Binary Search Tree: It provides moderate access/ search and moderate insertion/ deletion
  • Heap: It is a complete tree and is suitable to be stored in an array, it is either MIN or Max
  • Hashing: Collection of items that are stored in a way that it becomes easy to find them is hashing

Lists and tuples (In Python):

  • To initialize empty list /tuple:
Lists: myList = []
Tuples: myTuple = ()
  • To specify size of tuple/list:
len(m­yLi­stO­rTu­ple)
  • To get an element in position x in list/tuple:
"x" in myList­OrT­uple
  • Index of element ‘X’ of list/tuple
myLis­tOr­Tup­le.i­nd­ex(­"­x") -- If not found, throws a Value­Error exception
  • Number of occurrences of X in list/tuple:
myLis­tOr­Tup­le.c­ou­nt(­"­x")
  • Update an item of List/tuple:
Lists: myList[x] = "x"
Tuples: tuples are immutable!
  • Remove element in position X of list/tuple:
Lists: del myList[x]
Tuples: tuples are immutable!
  • Concatenate two lists/tuples:
Lists: myList1 + myList2
Tuples: myTuple1 + myTuple2
Concatenating a List and a Tuple will produce a TypeE­rror exception
  • Insert element in position x of a list/t­uple
Lists: myLis­t.i­nse­rt(x, "value")
Tuples: tuples are immutable!
  • Append “­x” to a list/t­uple:
Syntax: Lists: myList.append("x")
Tuples: tuples are immutable!
  • Convert a list/tuple to tuple/list:
Syntax: List to Tuple: tuple(myList)
Tuple to List: list(­myT­uple)

Sets:

  • To initialize an empty set:
Syntax: mySet = set()
  • Initialize a non-empty set
Syntax: mySet = set(el­ement1, elemen­t2...)
  • To add element X to the set
Syntax: mySet.ad­d("x­")
  • Remove element “­x” from a set:
Method 1: mySet.re­mov­e("x­") -- If "­x" is not present, raises a KeyErorr
Method 2: mySet.di­sca­rd(­"­x") -- Removes the element, if present
  • Remove every element from the set
Syntax: mySet.cl­ear()
  • Check if “­x” is in the set
Syntax: "x" in mySet
  • Union of two sets
Method 1: mySet1.union(mySet2)
Method 2: mySet1 | mySet2
  • Inters­ection of two sets
Method 1: mySet1.intersect(mySet2)
Method 2: mySet1 & mySet2
  • Difference of two sets
Method 1: mySet1.difference(mySet2)
Method 2: mySet1 - mySet2
  • Symmetric difference of two sets
Method 1: mySet1.symmetric_difference(mySet2)
Method 2: mySet1 ^ mySet2
  • Size of the sets:
len(m­ySet)

Dictionaries:

  • Initialize an empty Dict
myDict = {}
  • Add an element with key “­k” to the Dict
myDic­t["k­"] = value
  • Update the element with key “­k”
myDic­t["k­"] = newValue
  • Get element with key “­k”
myDic­t["k­"] -- If the key is not present, a KeyError is raised
  • Check if the dictionary has key “­k”
"k" in myDict
  • Get the list of keys
myDic­t.k­eys()
  • Get the size of the dictionary
len(m­yDict)
  • Delete element with key “­k” from the dictionary
del myDict­["k"]
  • Delete all the elements in the dictionary
myDic­t.c­lear()

Algorithms and the complexities:

Symbol Table:

Flask — Web app development Framework

https://www.idiotinside.com/uploads/2015/02/flask-cheat-sheet.pdf
https://s3.us-east-2.amazonaws.com/prettyprinted/flask_cheatsheet.pdf

Layout

Flask for Django users comparison

http://flask-cheat-sheet.herokuapp.com/
  1. https://cheatography.com/amicheletti/cheat-sheets/python-flask/pdf/
  2. https://intellipaat.com/blog/tutorial/python-tutorial/
  3. https://perso.limsi.fr/pointal/_media/python:cours:mementopython3-english.pdf
  4. https://cheatography.com/scottashipp/cheat-sheets/object-oriented-design-principles/

--

--

--

Don’t be intimidated by jargon. For example, a model is just a fancy word for “recipe.”

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Agile Philippines Meetup 2018.04

Setting up Cassandra Multi-Site on Google Kubernetes Engine with Casskop

Parallel Programming With CUDA Tutorial (Part-2: Basics)

CS373 Blog, Week 11

Connect Apache Spark to your MongoDB database using the mongo-spark-connector

Eggforce Weekly Writeup #8: Testing

Why and How You Should Run a Beta Community

Gokhan Ozgozen: Reading Other People’s Code Is a Great Way of Learning New Things

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Speedster Saurabh

Speedster Saurabh

Don’t be intimidated by jargon. For example, a model is just a fancy word for “recipe.”

More from Medium

DATA STRUCTURES IN PYTHON

Welcome to the “First Program” in Python? #Python Series-4

What is Super Function in Python?

Rock, Paper, Scissors using Python