Python Cheat Sheet

By | September 22, 2019
Python Cheat Sheet
  • Python is a multi-paradigm general-purpose, object-oriented programming language
  • It is a cross-platform programming language so code python file written in one system can be run same on different systems.
  • Easy to learn.
  • Simple Syntax and akin to pseudocode.
  • Automatic Garbage Collection.
  • It is an open-source programming language.

Applications of Python

Python is a very versatile language and it is used in many IT fields such as:

  • Web Development (back-end)
  • Desktop Applications
  • Data Science.
  • Machine Learning
  • Artificial Intelligence.

Major Characteristic of Python

  • Very Simple Programming language.
  • Python has the most libraries.
  • Support Object-Oriented programming
  • Ideal Programming language for a beginner.
  • Robust and Secure
  • Highly Scalable
  • Use Interpreter
  • Dynamic Programming language.
  • Multi-threading.

Python IDE’s

There are many IDE’s on the internet for Python the two most recommended ones are:

  • PyCharm (By Jetbrains)
  • Atom (Powered by GitHub)

Standard Data Types in Python:

Python has two types of Data types:

  • Base Type.
  • Container Type.
Base Type
Data type Name Data Type Syntax Size
Integer Number int 14
Floating Point Numbers float 16
Boolean bool 14
string str 26
bytes b’’ 21
Container Type Data Types
Data type Name Data Type Syntax Example
List (Ordered) list() [1,2,3] or list(range(1,4))
Tuple (Ordered) tuple() (1,2,3)
Dictionary (Unordered) dict() {0:1, 1:2, 2:3}
Set (unordered) set() {1,2,3}

Python Operators

Python has some standard operators which include arithmetic operators too.

Operator Name Operator Example
 Addition or concatenation + 1+2


“hello” + ”world”

Subtraction 40 – 10 à 30
Multiplication * 40 * 10 à 100

[0]*2 à[0,0]

division / 10/5 à 2.0
Floor division // 10 // 5 à2
Modules % 10 % 5 à 0
Exponential ** 2**3 à 8

Python Comparison Operator

There are some operators in python which are used to compare two objects or values and return a Boolean value True and False:

Operator Name Operator Example
Smaller than  < 2 < 3 èTrue
Greater than > 3 > 2 èTrue
Smaller than and equal to <= 2 <= 2 èTrue
Greater than and equal to >= 3 >= 3 èTrue
Not equal to != 2 != 3èTrue
Equal to comparison == 2 ==2 èTrue

Logical Operators

Python has three logical Operators:

  • and
  • or
  • not

Python Identifiers

Identifies are the name given to an object, identifiers can be also known as a variable name. There are some rules associated with an identifier or variable name. Using identifies we can give a name to variables, functions, modules, classes.

Identifiers rule:
  • The first letter of an identifier could be a lowercase or upper case Alphabet or _ (underscore symbol), and it could be followed by any alphabet, digit (0,9) and _.
  • There should be no special symbol in identifier except _.
  • Do not use reserved keywords as an identifier.

Variable Assignment

We use equal to “=” symbol to assign an object to an identifier.

The identifier name should be on the left side and value on the right side of the assignment operator.


x =20

Python Assignment Assignment operator Example
Simple and Single Assignment = x = 20
Assignment to same value = x = y = z =100
Multiple Assignment = x, y, z = 10, 20, 30
Swap values with Assignment operator = x, y  = y, x
Unpacking sequence using assigmnet operator = x, *y = [20,10,30,70]
Assignment operator for increment += x+=20
Assignment operator for Decrement -= x -=20

Python I/O

I/O methods Description
print() To print out the output
input() To take input from the user


>>> print("Hello", end = "**")
>>> print("world")
>>> input("Enter a Number: ")
Enter a Number: 20

By default input() accept value as string.

Type Conversion

Using there are many reserved keywords in python which are used to convert the data type of a variable.

Type Conversion Python Syntax Example
 Float to integer

Numeric string to integer

Boolean to integer

int() int(20.11)



Integer to float

Numeric string to float

Boolean to float

float() float(100)



Integer to string

float to string

Boolean to string

str() str(100)



ASSIC Code to character chr() chr(64) à @
Character to ASSIC code ord() ord(‘@’) à 64
Convert a container data type and a string to a list list() list(“Hello”)
Convert a container datatype to a dict dict() dict([(1,2), (2,3)])
Convert a container data type to a set set() set([1,2,3,4,5,5])

Indexing Calling in Python

In python String, List and tuple objects support indexing calling.


>>> lst = [100, 200, 300, 400, 500 ,600]
>>> # all items of list
>>> lst[:]
[100, 200, 300, 400, 500, 600]
>>> #all items of list from index point 1 to last
>>> lst[1:]
[200, 300, 400, 500, 600]
>>> # Index slicing
>>> lst[::2]
[100, 300, 500]
>>> # reverse the elements of a list
>>> lst[::-1]
[600, 500, 400, 300, 200, 100]
>>> # last element of the list
>>> lst[-1]

Boolean Logic in Python

In python, we often encounter with Boolean values when we deal with comparison operator conditional statements.

Types of Boolean

In python there are two types of Booleans:

  • True
  • False
Boolean Operator Description Example
False In python False, 0, empty container data type and None Treat as False value. bool(0) à False

bool([]) à False

bool({}) à False

bool(None) à False

True Anything except 0, None and empty data type in python considered as True Boolean bool(100) à True

Modules Name and Import

Use Syntax
Import the complete module import module
Import complete modules with its all objects from module import *
Import specific objects or class from a modules from module import name_1, name_2
Import specific module and give a temporary name from module import name_1 as nam

Python Math Module

Math is the most important and widely used standard module of python, it provides many methods related to mathematics.

Math Module Example

from math import *

cos() cos(90)


sin() sin(200)


pi 3.141592653589793
pow() pow(2,3) à 8.0
ceil() ceil(12.1) à13
floor() floor(12.9) à12
round() round(12.131,2) à12.13
abs() abs(-29) à 29

Conditional Statement

Python Conditional statement consists of 3 keywords if, elif and else.


if x == 1: 
elif x == 2: 
# Ternary operator
x = “a” if n > 1 else “b”
# Chaining comparison operators
if 20 <= age < 45:


There are two loops statements present in python:

  • for loop
  • while loop


for n in range(10):
while n < 10:
    n += 1

It is a statement used inside the loop statement, and it is used to terminate the loop flow and exist from the loop immediately.


for n in range(10):
    if n > 5:

Continue is the opposite of break, it is also used in loop statements and directly jump to the next iteration.


for n in range(10):
    if n > 5 and n < 7:


To create a user-defined function in python we use the def keyword and to exit from a function we return a value using the return keyword.


def add(a, b):  
    return a + bb
# Keyword arguments
add(2, 4)
# Variable number of arguments
def multiply(*numbers):
    for number in numbers:
        print (number)
multiply(1, 2, 3, 4)
# Variable number of keyword arguments
def save_user(**user):
save_user(first_name= “Sam”, last_name="smith")

Python List

A list is a collection of different data types, and it stores all elements in a contagious memory location.

Create a list

To create a list we use square brackets [ ].


lst = [100, 200, 300, 400, 500]

List support indexing, with the help of indexing we can access the specific element of the list.


>>> lst =[100, 200, 300, 400, 500]
>>> lst[0]
>>> lst[3]
List Slicing

With list slicing, we can access a sequence of elements present in the list.

lst [start :  end : steps]


>>> lst[1:3]
[200, 300]
>>> lst[2:1000]
[300, 400, 500]
>>> lst[1:5:2]
[200, 400]
List Unpacking
a, b, *c = lst
Loop through a List:
for i in lst:
for index, value enumerate(lst):
Adding Elements in the list:
Removing Elements from a list
lst.pop()               #pop out last element
lst.pop(0)            #pop out element at index 0
lst.remove(200)                 #remove 200
del lst[3:]             #delete list all element from index 3
If condition with a list
if 200 in lst:
List Comprehension

lst_2 = [i for i in lst ]

Condition inside list comprehension
lst_3 = [i for i in lst if i %3 ==0]
Zip function to combine two lists
a = [1,2,3]
b = ["i", "j","k"]
Map and Filter on a list
str_lst = list(map(str,lst))
list_3_div = list (filter (lambda x : x%3 ==0 , lst))
List Operations
Operations Descriptions
lst.append(val) Add items at the end
lst.extend(seq) Add sequence at the end
lst.insert(indx,val) Add value at a specific index
lst.remove(val) To delete the specific value from a list
lst.pop() To remove the last value from the list
Lst.sort() To sort the list

Python Tuples

Tuples in python similar to a list, the only difference is tuples are immutable.

Create a tuple:
tup =  (1,2,3,4,5,6)
Convert a list into a tuple
lst = [1,2,3,4,5,6]
tup= tuple(lst)
Indexing In tuple

Python Arrays

Python does not have inbuilt support for arrays but it has standard libraries to for array data structure. Array is a very useful tool to perform mathematical concepts.

Create an Array:
from array import array
arr = array('i' , [1,2,4])

Python Sets

Python set is similar to the mathematic sets, a python set does not hold duplicates items and we can perform the basic set operation on set data types.

Create a Set:
s = {1,2,3,4,5,6,7}
s2 = {1,3,6,9}
Basic Set operation
Operations Name Operator Example:
Union | s1 | s2
Intersection & s1 & s2
Difference s1 – s2
Asymmetric Difference ^ s1 ^ s2


Dictionary is a collection of key: value pair and the key could only be an immutable data type.

Create a dictionary:
dic = {1:2, 3:6 , 4:8, 5:10}
Convert a list into a dictionary:
lst = [(1,2), (2,4), (3,6)]
Accessing Dictionary Elements

We use the key to access the corresponding value.  

>>> dic = {"hello": "greet", "go":"there"}
>>> dic['go']
Looping Through a dictionary:
for key, value in dic.items():

Generator Comprehension

Like a list comprehension, we have generator comprehension in generator comprehension we use parenthesis () instead of sq. brackets [].


values = (x * 2 for x in range(10000))
for x in values:

Exception Handling:

In exception handling we deal with runtime error there are many keywords associated with exception handling:

keyword Description
try Normal processing block
except Error processing block
finally Final block executes for both tries or except.
raise To throw an error with a user-defined message.


# Handling Exceptions
    #try block
except (ValueError, ZeroDivisionError):
    #except block
  # no exceptions raised
  # cleanup code

Python Class

Class provides the Object-Oriented programming concepts to python.

Create a class
class Employee:
Create a constructor for a class:

The constructor is the special method of class which executes automatically during the object creation of the class.

class Employee:
    def __init__(self):
        self.val = 20
Magic Methods of class
Magic methods Description
__str__() String representation of the object
__init__() Initialization or Constructor of the class
__add__() To override addition operator
__eq__() To override equal to method
__lt__() To override less than operator
Class Private members:

Conventionally to declare an attribute private we, write it name starting with __ double underscore.


class Employee:
    def __init__(self):
        self.val = 20
        self.__sal =40000

An inheritance we can use the methods and property of another class:


class Employee:
    def __init__(self): = 20
class Manager(Employee):
    def __init__(self):
        self.__sal= 200000
Multiple Inheritance:
class Employee:
    def __init__(self): = 20
class Manager:
    def __init__(self):
        self.__sal= 200000
class Sam(Employee, Manager):
    def __init__(self):

Basic Generic Operations on Containers

Operators Description
len(lst) Items count
min(lst) To find the minimum item
max(lst) To find the maximum item
sorted(lst) List sorted copy
enumerate (c) Iterator on (index, item)
zip(lst_1,lst_2) Combine two list
all(c) If all items are True it returns True else false
any(c) True at least one item of c is true else false

People Also Read:

Author: Paridhi Joshi

Paridhi Joshi is an expert web content manager with significant experience in content creation. Professionally she is dedicated to staying up to date with the latest trends and technologies in content writing and committed to bringing state-of-the-art web approaches to the workplace. She is an efficient multi-tasker who can complete multiple projects under strict deadlines.

Leave a Reply

Your email address will not be published. Required fields are marked *