Python Cheat Sheet

Posted in /   /  

Python Cheat Sheet

Vinay Khatri
Last updated on June 25, 2022

    Python is one of the most popular programming languages and its popularity is growing more and more. One of the best things about Python is that you can use it for a wide variety of purposes, such as web development, software development, game development, etc. Here are some of the key highlights of the Python programming language:

    • Python is a multi-paradigm, general-purpose, object-oriented programming language.
    • It is a cross-platform programming language, which means that a Python file can run across multiple platforms or operating systems in the same way.
    • It is easy to learn.
    • Simple syntax and akin to pseudocode.
    • Comes with the Automatic Garbage Collection feature.
    • Open-source and free to use.

    In this Python cheat sheet, we will cover a wide range of Python concepts that you should remember as a Python developer. Also, we have provided relevant examples to help you understand the concepts better. Now, let's start this Python cheat sheet by discussing the applications and characteristics of Python.

    Applications of Python

    Python is a highly versatile language and it has applications in many IT fields such as:

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

    Characteristics of Python

    Following are the major characteristics of Python:

    • Simple programming language.
    • Python has the most libraries.
    • Supports object-oriented programming.
    • Robust and secure.
    • Highly scalable.
    • Uses interpreter.
    • Dynamic programming language.
    • Supports multi-threading.

    Best Python IDE’s

    There are many IDEs available for Python, however, the following ones are the most recommended:

    • PyCharm (By Jetbrains)
    • Atom (Powered by GitHub)
    • Visual Studio Code (By Microsoft)
    • Spyder
    • Jupyter Notebook

    Online Python Compilers or Interpreters

    We can use online Python compilers or interpreters to run a Python source code on any device without installing the Python. Following is a list of the best online Python compilers:

    • OnlineGDB
    • Replit
    • Ideone
    • JDoodle

    Python Implementations

    The most widely used Python3 offered by python.org is CPython, which is written in the C programming language. Apart from CPython, there are many other implementations of Python, such as the ones listed below:

    • IronPython (Runs on .NET)
    • Jython (Runs on Java Virtual Machine)
    • PyPy
    • Stackless Python (CPython Branch that supports micro threads )
    • MicroPython (Runs on Micro Controller)

    Standard Data Types in Python

    Python has two 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

    Base Data Types Examples

    #integer (int): It represents all the integer numbers 
    a = 23
    
    #float (float): It represents all the decimal or floating point numbers 
    b = 23.0
    
    #Boolean (bool): It represents two Boolean values - True and False
    c = True
    d = False
    
    #string (str): It represent a sequence of chracters
    e = 'Hello World'
    f = "Hello World"
    g = '''Hello World'''
    h = """Hello World"""
    
    #bytes (bytes): It is a sequence of Byte chracters 
    i = b"3"

    Container Type

    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}

    Container Types Examples

    #List (list): A list is a mutable sequence of items.
    a = [1,2,3,4,5]
    
    #Tuple (tuple): A tuple is an unmutable sequence of items
    b = (1,2,3,4,5)
    
    #Dictionary (dict): Dictionary store items in the form of key:value pairs
    c = {'x1':10, 'x2':40 ,'y1':3, 'y2':19}
    
    #Set(set): A set is an unorder collection of unique items 
    d = {1,2,3,4,5,6,7}

    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 [ ]. Example:

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

    Python lists support indexing. With the help of indexing, we can access a specific element of a list. Example:

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

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

    lst [start :  end : steps]

    Example:

    >>> 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:
        pass
    for index, value enumerate(lst):
        pass
    • Add Elements in a list
    lst.append(600)
    lst.insert(0,50)
    • Remove 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:
        print(True)
    • List Comprehension
    lst_2 = [i for i in lst ]
    • Condition inside a 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"]
    zip(a,b)
    • 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

    Operation Description
    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

    A tuple in Python is similar to a list. However, the only difference between a tuple and a list is that 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
    print(tup[1])

    Python Arrays

    Python does not have inbuilt support for arrays, but it has a standard library for the array data structure.

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

    Python Sets

    A Python set is similar to a set in mathematics.  Also, a Python set does not hold duplicate items and we can perform the basic set operations on set data types.

    • Create a Set
    s = {1,2,3,4,5,6,7}
    s2 = {1,3,6,9}

    Basic Set Operations

    Operation Name Operator Example
    Union | s1 | s2
    Intersection & s1 & s2
    Difference - s1 - s2
    Asymmetric Difference ^ s1 ^ s2

    Dictionary

    A dictionary is a collection of key-value pairs , 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)]
    dict(lst)
    • Accessing Dictionary Elements

    We use a key to access its corresponding value in the dictionary.

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

    Python String Escape Characters

    An Escape character allows us to insert illegal characters in a string, such as a tab, single quote inside a single quote string, etc.

    Escape character Prints as
    \' Single quote
    \" Double quote
    \t Tab (4 spaces)
    \n Newline
    \\ Backslash

    Python String Formatting

    With string formating, we can put variables data value inside strings.

    • String formatting using f prefix

    The latest versions of Python support string formating using the f prefix.

    Example

    a = 2
    b = 3
    
    print(f"The value of a is {a} and the value of b is {b}")

    Output

    The value of a is 2 and the value of b is 3
    • String formatting using format method

    The string object also supports the format method to format a string value.

    Example

    a = 2
    b = 3
    
    print("The value of a is {0} and the value of b is {1}".format(a, b))

    Output

    The value of a is 2 and the value of b is 3

    Python Operators

    Python Arithmetic Operators

    There are various arithmetic operators in Python that are listed in the table below:

    Operator Name Operator Example
    Addition or concatenation + 1+2  #3
    Subtraction 40 – 10  #30
    Multiplication * 40 * 10 #400
    division / 10/5   #2.0
    Floor division // 10 // 5  #2
    Modulo % 10 % 5  #0
    Exponential ** 2**3  #8

    Python Arithmetic Operators Example

    a = 2
    b = 4
    
    #addition operator
    print('a+b = ', a+b)
    
    #subtraction operator
    print('b-a = ', b-a)
    
    #multiplication operator
    print('a*b = ', a*b)
    
    #division operator
    print('a/b = ', a/b)
    
    #floor division
    print('a//b = ', a//b)
    
    #modulo operator
    print('a%b = ', a%b)
    
    #Exponential operator
    print('a**b = ', a**b)

    output

    a+b = 6
    b-a = 2
    a*b = 8
    a/b = 0.5
    a//b = 0
    a%b = 2
    a**b = 16

    Python Comparison Operators

    There are several operators in Python that you can use to compare two objects or values and return a Boolean value, i.e. True or 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

    Python Comparison Operator Examples

    a = 2
    b = 4
    
    #smaller than operator
    print('a<b = ', a<b)
    
    #greater than operator
    print('a > b = ', a>b)
    
    #smaller than and equal to operator
    print('a<=b = ', a<=b)
    
    #greater than and equal to operator
    print('a>=b = ', a>=b)
    
    #not equal to division
    print('a!=b = ', a!=b)
    
    #Equal to comparion operator
    print('a==b = ', a==b)

    Output

    a<b = True
    a > b = False
    a<=b = True
    a>=b = False
    a!=b = True
    a==b = False

    Logical Operators

    Python has three logical operators:

    • and (returns True if and only if both the conditions are True)
    • or (returns True if either of the conditions is True)
    • not (returns True if the condition is False and vice versa)

    Logical Operators Examples

    #and operator 
    print('2>1 and 2>=2: ',2>1 and 2>=2 )
    
    #or operator
    print('2<1 or 2<=2: ',2<1 or 2<=2 )
    
    #not operator 
    print('not(2 > 3):', not(2 > 3))

    Output

    2>1 and 2>=2: True
    2<1 or 2<=2: True
    not (2 > 3): True

    Python Identifiers and Keywords

    An identifier is a name given to an object. Identifiers are also known as variable names. There are some rules associated with an identifier or variable name. By using identifiers, we can give a name to variables, functions, modules, and classes.

    Identifiers Rules

    • The first letter of an identifier could be a lowercase or uppercase alphabet or _ (underscore symbol), and it could be followed by any alphabet, digit (0,9) and _.
    • There should be no special symbol in an identifier except _ (underscore).
    • You cannot use reserved Python keywords as identifiers.

    Python Keywords

    Keywords are the reserved names in Python, and there are a total of 33 keywords in Python 3 that are listed below:

    False else import pass
    None break except in raise
    True class finally is return
    and continue for lambda try
    as def from nonlocal while
    assert del global not with
    elif if or yield

    Variable Assignment

    We use the equal to "=" symbol to assign an object to an identifier. The identifier name should be on the left side and the value on the right side of the assignment operator. Example x =20

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

    Python I/O

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

    Example

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

    By default input() accepts a value as a string.

    Type Conversion

    There are many reserved keywords in Python you can use 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) int("200") int(True)
    Integer to float Numeric string to float Boolean to float float() float(100) float("100.6") float(True)
    Integer to string float to string Boolean to string str() str(100) str(100.00) str(True)
    ASCII Code to character chr() chr(64) # @
    Character to ASCII code ord() ord('@') # 64
    Convert a container data type and a string to a list list() list('Hello') #['Hello']
    Convert a container datatype to a dict dict() dict([(1,2), (2,3)])  #{1:2, 2:3}
    Convert a container data type to a set set() set([1,2,3,4,5,5])   #{1,2,3,4}

    Indexing Calling in Python

    In Python, string, list, and tuple objects support indexing calling. An index is an integer number. Indexes of the items within an object are available from 0 to n-1 , where n is the total number of items or characters present in the object. Example:

    >>> 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]
    600

    Boolean Logic in Python

    In Python, we often encounter Boolean values when we deal with comparison operators and conditional statements.

    Types of Boolean

    There are two types of Boolean values:

    • True
    • False
    Boolean Operator Description Example
    False In Python, False, 0, empty container data type, and None are treated as Boolean False. bool(0) # False bool([]) # False bool({}) # False bool(None) # False
    True Anything except 0, None, and empty data type in Python are considered as Boolean True. bool(100) # True

    Generator Comprehension

    Like a list comprehension, we have generator comprehension for which we use parenthesis () instead of square brackets [].

    Example

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

    Python File Handling

    To read or write data to a file, we can use the Python context manager with keyword. By using the with keyword and open function, we can open a file in different modes mentioned in the table below:

    Mode Description
    r Read mode
    r+ Read and Write mode
    w Write mode
    w+ Write and Read mode
    rb Read in binary mode
    rb+ Read and write in binary mode
    wb Write in binary mode
    wb+ Write and read in binary mode
    a Append mode
    ab Append in binary mode
    a+ Append and read mode
    ab+ Append and read in binary mode
    x Exclusive creation of file mode.

    Example 1

    To open and read from a file

    with open('data.txt', 'r') as file:
        #read the complete file as a string
        print(file.read())

    Example 2

    Open and write into  a file

    #write into the file
    with open('data.txt', 'w') as file:
        #write into a file
        print(file.write('Hi there.. welcome to techgeekbuzz'))

    Example 3

    Open and append into  a file

    #append into the file
    with open('data1.txt', 'a') as file:
        #write into a file in append mode
        print(file.write('Hi there.. welcome to techgeekbuzz'))

    Packages and Modules in Python

    A package in Python is a collection of multiple Python modules. On the other hand, a Python module is a Python file that contains source code. To define a Python package, we have to create an empty __ini__.py file in the package directory. To use the modules from different packages, we have to import them into our script using from and import keywords.

    Modules Name and Import

    Purpose Syntax
    To Import the complete module import module
    To Import a complete module with all its objects from module import *
    Import specific objects or classes from a module from module import name_1, name_2
    Import modules from a package from package_name import module

    Python Math Module

    Math is the most important and widely used standard module of Python. It provides many methods related to mathematical operations.

    Math Module E xample

    from math import *

    cos() cos(90) -0.4480736161291701
    sin() sin(200) -0.8732972972139946
    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

    A conditional statement in Python consists of 3 keywords - if, elif, and else. Example

    if x == 1: 
        print("a")
    elif x == 2: 
        print("b")
    else:  
        print("c")

    Python Ternary operator

    Python Ternary operator is a shorthand to write the conditional statement as a single line of code.

    Example

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

    Loops

    There are two loops statements available in Python:

    • for loop
    • while loop

    Example

    #for loop

    for n in range(10):
        print(n)

    #while loop

    while n < 10:
        print(n)
        n += 1

    Break

    It is a statement used inside the loop statement to terminate the loop flow and exit from the loop immediately.

    Example

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

    Continue

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

    Example

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

    Function

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

    Example

    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):
        print(user)
    save_user(first_name= "Sam", last_name="smith")

    Exception Handling

    With exception handling, we deal with runtime errors. There are many keywords associated with exception handling, such as the ones mentioned in the following table:

    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.

    Example

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

    Python Class

    Classes enable Python to make use of object-oriented programming concepts.

    • Create a class
    class Employee:
        pass
    • Create a constructor for a class:

    The constructor is a special method of classes that gets executed automatically during the object creation of a class.

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

    Magic Methods of class

    Magic Method 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 a private attribute, we write its name starting with __ (double underscore). Example

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

    Inheritance

    With inheritance, we can use the methods and properties of another class:

    Example

    class Employee:
        def __init__(self):
            self.id = 20
    class Manager(Employee):
        def __init__(self):
            self.__sal= 200000

    Multiple Inheritance

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

    Basic Generic Operations on Containers

    Operator Description
    len(lst) Item 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

    Virtual Environment in Python

    A Python virtual environment creates an isolated environment for a project where we can install and uninstall packages, frameworks, and libraries without affecting the actual Python environment. To create a Python environment, we can use the built-in Python venv module.

    python -m venv myProject

    The above terminal command will generate a new virtual environment in the directory myProject . After creating the virtual environment, we need to activate it. The activation script of the virtual environment exists inside the virtual environment's Script directory.

    my_project\Scripts\activate

    The above command will activate the newly created virtual environment in the myProject directory. To deactivate the environment, we can simply execute the deactivate command on the terminal or command prompt.

    To Sum it Up All

    We hope that this comprehensive Python Cheat Sheet will help you learn various important concepts in Python. Also, with this cheat sheet, you can easily go through the important aspects of Python that are essential for writing Python code. If you have any suggestions or queries related to this Python cheat sheet, you can share them with us in the comments section below. People are also reading:

    Leave a Comment on this Post

    0 Comments