Python DataSheet

📋 CheatSheet

Python CheatSheet

🕐 10 min read 📄 15 Topics Free Resource by DataSteroid
01

Basics

Showing Output To User

The print() function displays output to the screen.

python
print("Content that you wanna print on screen")

Displaying the value stored in a variable:

python
var1 = "Shruti"
print("Hi my name is: ", var1)

Taking Input From the User

The input() function takes input as a string from the user.

python
var1 = input("Enter your name: ")
print("My name is: ", var1)

To take input as other data types, typecast them:

python
# Integer input
var1 = int(input("Enter the integer value: "))
print(var1)

# Float input
var1 = float(input("Enter the float value: "))
print(var1)

Range Function

Returns a sequence of numbers. int_stop_value is compulsory; start and step default to 0 and 1.

python
range(int_start_value, int_stop_value, int_step_value)

# Display all even numbers from 0 to 100
for i in range(0, 101, 2):
    print(i)
02

Comments & Escape Sequences

Comments

Comments make code more readable. They are not executed by the interpreter.

python
# Single line comment

'''
Multi-line
comment
'''

Escape Sequences

Characters that don’t represent themselves but are translated into special characters inside string literals.

SequenceNameDescription
\nNewlineMoves to a new line
\\BackslashAdds a backslash
\’Single QuoteAdds a single quotation mark
\tTabGives a tab space
\bBackspaceAdds a backspace
\oooOctalRepresents value of an octal number
\xhhHexRepresents value of a hex number
\rCarriage ReturnShifts cursor to beginning of line
python
print("Line1\nLine2")   # newline
print("Tab\there")    # tab
print("Back\\slash")  # backslash
03

Strings

A Python string is a sequence of characters, each accessible by its index. Created using single or double quotes.

python
variable_name = "String Data"

str = "Shruti"
print("string is ", str)

Slicing

Obtains a sub-string from a given string.

python
string_var[start : stop : step]
var_name[1 : 5]  # includes index 1, 2, 3, 4
Start and step values default to 0 and 1 respectively if not mentioned.

String Methods

MethodDescription
.isalnum()True if all characters are alphanumeric
.isalpha()True if all characters are alphabets
.isdecimal()True if all characters are decimals
.isdigit()True if all characters are digits
.islower()True if all characters are lowercase
.isupper()True if all characters are uppercase
.isspace()True if all characters are whitespace
.lower()Converts string to lowercase
.upper()Converts string to uppercase
.strip()Removes leading and trailing spaces
04

Lists

Comma-separated values of any data type in square brackets. Lists are ordered, indexed, mutable — the most flexible collection in Python.

python
var_name = [element1, element2, ...]
my_list = []  # empty list

List Methods

MethodDescription
.index(element)Returns index of first occurrence of the element
.append(element)Adds element at the end
.extend(iterable)Adds all elements of an iterable to the end
.insert(pos, elem)Adds element at the specified position
.pop(position)Removes & returns element at position
.remove(element)Removes first occurrence of the element
.clear()Removes all elements
.count(value)Returns count of elements with specified value
.reverse()Reverses the list in place
.sort(reverse=True|False)Sorts the list
python
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
fruits.insert(1, "kiwi")
fruits.remove("banana")
fruits.sort()
print(fruits)
05

Tuples

Comma-separated values within parentheses. Tuples are ordered, indexed, immutable — the most secured collection in Python.

python
variable_name = (element1, element2, ...)
MethodDescription
.count(value)Returns the number of times value occurs in tuple
.index(value)Searches tuple and returns position of value
06

Sets

A collection that is unordered, unindexed. Duplicate elements are NOT allowed.

python
# Way 1
var_name = {element1, element2, ...}

# Way 2
var_name = set([element1, element2, ...])

Set Methods

MethodDescription
.add(element)Adds an element to the set
.clear()Removes all elements
.discard(value)Removes the specified item
.intersection(s1,s2…)Returns intersection of two or more sets
.issubset(set)Checks if set is a subset of another set
.pop()Removes a random element
.remove(item)Removes the specified element
.union(set1, set2…)Returns union of two or more sets
07

Dictionaries

Ordered, mutable collection of key:value pairs. Duplicate values allowed — duplicate keys are not.

python
# Create
my_dict = {"name": "Suzal", "course": "MCA"}

# Empty
mydict = {}

# Add / Update
my_dict["age"] = 22

# Delete
del my_dict["age"]

Dictionary Methods

MethodDescription
len(dict)Returns count of key:value pairs
.clear()Removes all elements
.get(key)Returns the value of the specified key
.items()Returns list of tuples for each key-value pair
.keys()Returns list of all keys
.values()Returns list of all values
.update(iterable)Updates dict with specified key-value pairs
08

Conditional Statements

The if, elif and else statements implement selection constructs in Python.

Python uses indentation (spaces/tabs) instead of curly braces to define blocks of code.
python
# if
if(condition):
    statements

# if-else
if(condition):
    statements
else:
    statements

# if-elif-else
if (condition):
    statements
elif (condition):
    statements
else:
    statements

Nested Example

python
a = 15; b = 20; c = 12
if(a>b and a>c):
    print(a, "is greatest")
elif(b>c and b>a):
    print(b, "is greatest")
else:
    print(c, "is greatest")
09

Loops

For Loop

Processes items of any sequence one by one.

python
for variable in sequence:
    statements

# Print 1 to 100
for i in range(1, 101):
    print(i)

While Loop

Repeats as long as the condition is true.

python
while condition:
    loop-body

i = 1
while(i <= 100):
    print(i)
    i = i + 1

Break & Continue

python
# break — exits the loop
for i in range(1, 10):
    if i == 5:
        break
    print(i)

# continue — skips current iteration
for i in [2,3,4,6]:
    if (i % 2 != 0):
        continue
    print(i)
10

Functions

A block of code that performs a specific task. Makes code organised and reusable.

python
# Define
def my_function():
    #statements

# Call
my_function()

Return Statement

python
return [value/expression]

Arguments

python
def my_function(arg1, arg2, argn):
    #statements
my_function(arg1, arg2, argn)

# Example
def add(a, b):
    return a + b
x = add(7, 8)
print(x)  # 15
11

File Handling

Python provides functions to read, write, and manipulate files.

python
var_name = open("filename", "mode")

File Modes

  • r Read content from file
  • w Write content into file
  • a Append to existing content
  • r+ Read and write — previous data overridden
  • w+ Write and read — overrides existing data
  • a+ Append and read — won’t override existing data

Read & Write Functions

python
read()       # returns one big string
readlines()  # returns a list of all lines
readline     # returns one line at a time

write()      # writes a string to the file
writelines() # writes a list of strings

var_name.close()  # always close after use!
12

Exception Handling

An exception is an unusual condition that interrupts the normal flow of a program.

python
# try-except
try:
    [Statement body block]
    raise Exception()
except ExceptionName:
    [Error processing block]

# try-except-else
try:
    #statements
except:
    #statements
else:
    # runs if no exception raised

# finally — always runs
try:
    #statements
except:
    #statements
finally:
    # compulsorily executed
13

Object Oriented Programming (OOP)

A programming approach that focuses on using objects and classes to represent real-world entities.

python
# Class definition
class MyClass:
    pass

# Object creation
obj = MyClass()

# Class with constructor
class MyClass:
    def __init__(self):
        self.name = "DataSteroid"

    def print_me(self):
        print(self.name)

Inheritance

A derived/child class uses properties of a base/parent class — promotes code reusability.

python
class Base_class:
    pass
class Derived_class(Base_class):
    pass
TypeDescription
SingleOne derived class from one base class
MultipleOne derived class from multiple base classes
MultilevelDerived class from another derived class
HierarchicalMultiple derived classes from one base class
14

Iterators & Generators

Iterator

Creates an iterator over an iterable. Returns elements one at a time using next().

python
iter_list = iter(['Harry', 'Aakash', 'Rohan'])
print(next(iter_list))  # Harry
print(next(iter_list))  # Aakash
print(next(iter_list))  # Rohan

Generator

Uses yield to generate values on the fly without storing all values in memory.

python
def my_gen():
    n = 1
    print('First')
    yield n
    n += 1
    print('Second')
    yield n
    n += 1
    print('Third')
    yield n

Filter Function

python
filter(function, iterable)
# Extracts items from iterable that satisfy the function condition

issubclass

python
issubclass(obj, classinfo)
# Returns True if obj is a subclass of classinfo
15

Decorators

Modify the behavior of a function or class. Called before the definition of the function to be decorated.

python
# property (getter)
@property
def name(self):
    return self.__name

# setter
@name.setter
def name(self, value):
    self.__name = value

# deleter
@name.deleter
def name(self, value):
    print('Deleting..')
    del self.__name
SC

Suzal Chouhan

Student & founder of DataSteroid. Teaching Data Science the simple way — because I've been confused too, and I know exactly how it feels. Follow along on YouTube.

Leave a Comment

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