English
+370 5 205 5502 sales@monovm.com

Python Cheat Sheet

Python is an object-oriented, high-level programming language with dynamic semantics. In this article, we will share some quick reference codes that might be helpful for Python geeks.

18 Oct, 21 by Susith Nonis 9 min Read

List of content you will read in this article:

Python is an object-oriented, high-level programming language with dynamic semantics. It is an interpreted language. Its high-level data structures, along with dynamic typing and dynamic binding, make it highly appealing for rapid application creation, machine learning, and usage as a scripting language to link existing components. In this article, we will share some quick reference codes that might be helpful for Python geeks.

Basic math operations

>>> 1 + 1  #addition
2

>>> 5 // 2     #integer division
2

>>> 5 / 2     #floating point division
2

>>> 5 * 2     #multiply two numbers
10

>>> 5 ** 2     #power of a number
2

>>> 5 % 2     #modulo operation
1

Print a message on the screen

>>> print("Hello")
Hello

Print ZEN of Python on screen

The Zen of Python is a collection of 19 "guiding principles" for developing computer programmes that affect the Python programming language's architecture. Tim Peters, a software developer, wrote this collection of principles in 1999.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Assigning a variable with some value

>>> a = 2
>>> print(a)
2
>>> a
2

>>> a = "Hello"
>>> print(a)
Hello
>>> a
'Hello'

Assigning various types into variable

>>> a=2        #assigning an integer to a variable
>>> print(a)
2
>>> a
2

>>> a = "Hello Learner"  #assigning a string to a variable
>>> print(a)
Hello Learner
>>> a
'Hello Learner'

>>> a = 'a'  #assigning a character to a variable
>>> print(a)
a
>>> a
'a'

Printing types of data contained in a variable

>>> a = "Hello Learner"  #assigning a string to a variable
>>> type(a)
<class 'str'>
>>> a=2
>>> type(a)
<class 'int'>

Single Line comments

# This is a comment

Docstrings

def fun():
    """
    This is a docstring
    """

print()

>>> print('Hello!')
'Hello!'

len()

>>> len('Hey')
3

input()

>>> input('Enter some string')
Enter some string

Typecasting functions

>>> a='2'
>>> a=int(a)
>>> type(a)
<class 'int'>

>>> a=2
>>> a=str(a)
>>> type(a)
<class 'str'>

Flow control statements

>>> 1 == 1
True

>>> 2 != 1
True

>>> 1 == 1
True

>>> 3 > 1
True

>>> "one" == "two"
False

Boolean operations

>>> True and True
True

>>> True or False
False

>>> not True
False

Conditional statements

var = 'Python'
if var == 'Python':
    print('Hi, Python')
else:
    print('Hi, someone')

name = 'Python'
if name == 'Python':
    print('Hi, Python')
elif name == 'Java':
    print('You are Java')
else:
    print('You are neither Java nor Python.')

idx = 0
while idx < 10:    #loop runs from 0 to 9
    print('Hello')
    idx = idx + 1

for i in range(0,4,2):    #start loop from 0, upto 4 with step size of 2
  print('Hello')

Break statement

while True:
    print('What are you studying)
    inp = input()
    if inp == 'Nothing':
        break
print('The end')

Continue statement

while True:
    print('What are you studying)
    inp = input()
    if inp == 'Nothing':
        continue
    else:
    print("Good")

def fun():
    print('I am called')
fun() 

def getValue(n):
    if n == 2:
        return 'It is 2'
    else:
        return 'It is not 2'
what = getValue(2)
print(what)

One of the most used data structures in Python is a list, which is an ordered and mutable Python container. To make a list, put the components inside square brackets [] and separate them with commas.

Creating arrays

>>> arr = ['A', 'B']
>>> arr
['A', 'B']

Indexing arrays

>>> arr = ['A', 'B']
>>> arr[0]
'A'

>>> arr = ['A', 'B']
>>> arr[-1]
'B'

List slicing

>>> arr = ['A', 'B', 'C']
>>> arr[0:2]
['A', 'B']

Appending to a list

>>> arr = ['A', 'B']

>>> arr.remove('B')

Remove an element from the list

>>> arr = ['A', 'B']
>>> arr.remove('B')

Sorting a list

>>> arr = [2, 1]
>>> arr.sort()
>>> arr
[1, 2]

Strings in Python are arrays of bytes that represent Unicode characters. Python lacks character data types. Most of the functions that work with lists can also be used with strings in Python.

Indexing 

>>> string = 'Hello!'
>>> string[0]
'H'

upper() and lower() methods

>>> string = 'Hello!'
>>> string = spam.upper()
>>> string
'HELLO!'

>>> string = "HEY"
>>> string = string.lower()
>>> string
'hey'

join() and split()

>>> ', '.join(['A', 'B', 'C'])
'A, B, C'

>>> 'HeyKMan'.split('K')
['Hey', 'Man']

String Manipulation

>>> print("Hello!\nHow are you?\nI\'m great")
Hello!
How are you?
I'm great

Tuples are a data structure in Python that stores an ordered series of values. Tuples are immutable. This indicates that the values of a tuple cannot be changed.

a = ('A', 1)
>>> a[0]
'A'

>>> tuple(['A', 'B'])
('A', 'B')

In Python, a dictionary is an unordered collection of data values that are used to store data values similar to a map. Unlike other Data Types that contain only a single value as an element, a dictionary maintains a key, value pair.

Creating dictionary

hash = {'key1': 'value1', 'key2': 'value2'}

Indexing in dictionaries

>>> hash = {'key1': 'value1', 'key2': 'value2'}
>>> hash['key1']
'value1'

Iterating dictionaries

>>> hash = {'key1': 'value1', 'key2': 'value2'}
>>>
>>> for k, v in hash.items():
>>>     print('Key: {} Value: {}'.format(k, str(v)))
Key: key2 Value: value2
Key: key1 Value: value1

A set is an unordered collection of items with no duplicates. Set can be used to eliminate duplicate entries. Set objects are also capable of performing mathematical operations such as union, intersection, difference, and symmetric difference. The sets cannot be indexed.

Initializing sets

>>> s = {1, 2, 3, 2, 3, 4}
>>> s
{1, 2, 3, 4}

Adding to sets

>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

Removing from sets

>>> s = {1, 2, 3}
>>> s.remove(3)
>>> s
{1, 2}

Sets Union

union() will create a new set that contains all the elements from the sets provided.

>>> s1 = {1, 2, 3}
>>> s2 = {3, 4, 5}
>>> s1.union(s2)
{1, 2, 3, 4, 5}

Sets Intersection

The intersection will return a set containing only the elements that are common to all of them.

>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s3 = {3, 4, 5}
>>> s1.intersection(s2, s3)
{3}

Lambda Functions

>>> sum = lambda x, y: x + y
>>> sum(1, 2)
3

List comprehension

>>> a = [1, 2, 3]
>>> [i for i in a]
[1, 2, 3]

Sets comprehension

>>> Set = {"a", "b"}
>>> {s.upper() for s in Set}
{"A", "B"}

Exception Handling

try:
        result = x // y
        print("Answer is :", result)
    except ZeroDivisionError:
        print("Cannot divide by zero")

try:
    k = 5//0 
except ZeroDivisionError:  
    print("Cannot divide by zero")
finally:
    print('This is always executed')

A module is a Python object with arbitrarily named attributes that you can import and use in your codes. Simply speaking, a module is a file consisting of some useful Python code. 

You can import a module using the below syntax in your script.

import module_name

Below are some useful modules that can be helpful to you while coding.

  • itertools
  • re (Regular Expression)
  • logging
  • functools
  • math

Susith Nonis

I'm fascinated by the IT world and how the 1's and 0's work. While I veture into the world of Technology I try to share what I know in the simplest way possible. Not a fan of coffee, a sweet addict and a self accredited 'master chef'.