Scaler Topics - Python Cheat Sheet
Scaler Topics - Python Cheat Sheet
PYTHON
CHEAT SHEET
Python 3.11
Output: True
Introduction
Easy to learn
Python 0.9.0 Feb 1991 Python 3.6 Dec 2016
Scripting Web Development Python 1.0 Jan 1994 Python 3.6.5 Mar 2018
and Automation
Python Python 2.0 Oct 2000 Python 3.7.0 May 2018
Python 2.7.0 Jul 2010 Python 3.8 Oct 2019
Abundant Libraries Supports Graphics
and Frameworks and Visualizations Python 3 Dec 2008 Python 3.11 Oct 2022
Extensible and Portable
Environment Setup
Download Windows Python Installer from 1. Select the Install launcher for all users checkbox
https://www.python.org/downloads/ Run the Executable Installer 2. Select the Add python.exe to PATH checkbox
Install Now
Customize installation
(Happy with default features)
Next
Verify Installation
# Output
3.10
01 Cheatsheet
Basics
Python Variables
Code
Heap Memory
Output
10 5.5 Hello
string = "abc"
list_var = [1, "a", 2.2]
tuple_var = (1, "a", 2.2)
Integer Float Complex No
dict_var = {"key": "value"}
set_var = {1, 2, 3}
bool_var = True Strings List Tuple
02 Cheatsheet
Operators
Arithmetic Operators
Code
print(5 + 3) # Addition,Output: 8
print(5 - 3) # Subtraction,Output: 2
print(5 * 3) # Multiplication,Output: 15
print(5 / 3) # Division, Output:1.6666666666666667
Assignment Operators
print(x) # Output: 2
x //= 3
2 8
X X
Comparison Operators
Code
print(5 3) # Equal, Output: False
print(5 3) # Not equal, Output: True
03 Cheatsheet
Logical Operators (and/or/not)
Code
print(True and False) # Logical AND, Output: False
print(True or False) # Logical OR, Output: True
print(not True) # Logical NOT, Output: False
X and Y X or Y
True True
False False
X= True Y= True True
X= True Y= True False
False False
True True
False False
True True
Not X
False True
X= True
True False
Identity Operators
Code
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # Output: True Identity operator compares the objects rather than their values.
print(x is y) # Output: False Both objects should have same memory location.
04 Cheatsheet
Membership Operators
Code
x = 'Hello world'
Bitwise Operators
Pluck it out
Code Convert to Binary
5 >> 1 0 0 0 0 0 1 0 1 >> 1
print(5 & 3) # Bitwise AND,Output: 1
print(5 | 3) # Bitwise OR,Output: 7
print(5 ^ 3) # Bitwise XOR,Output: 6
0 0 0 0 0 0 1 0
print(~5) # Bitwise NOT, Output: -6
print(5 >> 1) # Bitwise Right Shift,
Output: 2
print(5 << 1) # Bitwise Left Shift, Insert a bit
Output: 10 same as the leftmost bit
05 Cheatsheet
Control Flow
If...Else If..Elif..Else
age = 22 age = 22
if (age < 18): [Condition False] x if (age < 12): [Condition False]
x print("Teenager!") print("Child")
else: elif (age < 18): [Condition False]
x
print("Adult!") print("Teenager")
elif (age < 40): [Condition True]
print("Adult")
else: [Ignored]
print("Old age")
print("End");
for loop
Code
5 * 1 = 5
for i in range(1, 6): 5 * 2 = 10
Output
print("5 *", i, "=", i * 5) 5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
Initialization
i = 1
Condition Update
i <= 5 i = i + 1
False True
These two steps are performed using
Statements the range function and "in" membership operator.
print("5 *", i, "=", i * 5)
End for
06 Cheatsheet
While loop
Code
5 * 1 = 5
i = 1 5 * 2 = 10
Output
while i <= 5:
val = 5 * i 5 * 3 = 15
print("5 *", i, "=", i * 5) 5 * 4 = 20
5 * 5 = 25
i = i + 1
Initialization
i = 1
Condition
i < 5
False
True
Statements
val = 5 * i;
print("5 *", i, "=", i * 5)
i = i + 1
End while
07 Cheatsheet
Break and Continue
Code Code
i = 0 i = 0 0
while i <= 5: 0 while i <= 5:
1
Output 1 Output
if (i == 4): if (i == 4): 2
break 2 continue
3
3
print(i) print(i) 5
i = i + 1 i = i + 1
Initialization Initialization
i = 0 i = 0
Condition Condition
i < 5 i < 5
pass statement
Code
Output
for i in range(5): Nothing will happen,
pass it's a null operation
08 Cheatsheet
Functions
Defining a Function
Code
function name
def keyword Arguments to the function
def findSquare(a):
colon(:) ends
Function val = a * a the definition
Body return val
def findSquare(a):
val = a * a
Function return val
Call
Return value
v = 5
sq = findSquare(v)
Lambda Functions
Code
x becomes 5
5**2 = 25
is returned
09 Cheatsheet
Scope of Variables
// Random function
def fun():
The 'var' is a local variable: Visible
var = 2 within the function block only.
print(var * 3)
}
Not visible outside the function.
print(var)
Throws error.
output
Reason: 'var' is not defined outside
the function.
Visible inside
Here, the 'var' is a global variable. var = 2 the function
It is visible in the entire program.
// Random function
def fun():
print("Printing global variable from fun:", var)
}
Output
10 Cheatsheet
Modules
Importing a Module
Code
import math Outputs all the defined
print(math.sqrt(16)) names in the math
module
from...import Statement
dir() Function
Code
import math
Outputs all the defined names in the math module
print(dir(math))
Output
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose',
'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan',
'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
11 Cheatsheet
Data Structures
Lists
Declaration
Method 1: Create an empty list
arr = []
arr[4] = 55
Elements 1 4 22 13 55
Indices 0 1 2 3 4
Miscellaneous:
Slice a list:
c = arr.count(2) # Counts the elements with value = 2.
print(arr[1:]) # Returns all elements from index 1 to the last.
12 Cheatsheet
Tuples
Declaration
Method 1: Create an empty tuple
tup = ()
Slice a tuple:
# Output:
(5, 1, 8)
(3, 5)
(5, 1)
Miscellaneous:
print(min(tup))
print(max(tup))
print(sum(tup)) # Self explanatory
# Output
0
0
1
8
17
13 Cheatsheet
Set
Sets are unordered. Set elements are unique. Duplicate elements are not allowed.
A set itself may be modified, but the elements contained in the set must be of an immutable type.
Declaration
Method 1: Create an empty set
st = set()
st.pop()
# Output # Removes a random element from the set
{1, 4, 5, 6, 7, 9, 10, 16} print(st)
# Output
{1, 4, 6, 7, 9, 10, 16}
{1, 4, 6, 7, 9, 16}
{4, 6, 7, 9, 16}
Miscellaneous:
print(len(st)) # Output: 5
st_copy = st.copy()
print(st_copy) # {16, 4, 6, 7, 9}
st.clear()
print(st) # Output: set()
14 Cheatsheet
Dictionary
In Python, a dictionary is an unordered collection of key-value pairs, where each key is unique within the dictionary.
It is also known as an associative array or a hash map in other programming languages.
Declaration
Method 1: Create an empty dictionary
st = {}
dt = { dt["orange"] = "orange"
"apple": "green", dt.update({"pomegranate": "red"})
"banana": "yellow",
"pear": "pink",
print(dt)
"Lemon": "lime"
} # Output
{
"apple": "green",
"banana": "yellow",
"pear": "pink",
"Lemon": "lime",
"orange": "orange",
"pomegranate": "red",
}
dt.clear()
print(dt)
15 Cheatsheet
File Handling
Code
with open('filename.txt', 'r') as file:
print(file.read()) # Outputs the content of the file
File Methods
Code
with open('filename.txt', 'r') as file:
print(file.readline()) # Outputs the first line of the file
Writing to a File
Code
with open('filename.txt', 'w') as file: Hello, world! Updated file content.
file.write('Hello, world!')
Code
import json
data = {'Name': 'Zophie', 'Species': 'cat', 'age': '7'}
json_data = json.dumps(data) # Converts into JSON string
16 Cheatsheet
Object-Oriented Programming
Code
class MyClass:
x = 5
Class blueprint
Default Constructor
def __init__(self): A constructor to create an object with name
attribute equal to the passed value.
pass
17 Cheatsheet
Object Methods
Code
1. Constructors are special or specific methods used by a class to
class MyClass:
perform task such as initiating variables, performing startup
task and that needs to be done when an instance of a class is
def __init__(self, name):
generated.
self.name = name
2. When you don't provide any constructor, then automatically a
default constructor is created for you.
obj1 = MyClass("Alice")
3. Whenever you create an object of a class, a constructor is called.
obj2 = MyClass("Bob")
obj3 = MyClass("Harry")
def __init__(self):
name: Alice name: Bob name: Harry
pass
obj1 obj2 obj3
Inheritance
1. Inheritance is the process by which an object of one class acquires the properties of another class.
2. Reusable code
3. It resembles real life models.
4. Base class: The class which is inherited is called the base class.
5. Derived class: The class which inherits is called derived class.
Code
class Parent:
def func(self):
print("This is a function of the parent class.")
class Child(Parent):
pass
obj = Child()
obj.func() # Output: This is a function of the parent class.
18 Cheatsheet
Encapsulation
1. Data and the methods which operate on that data are defined inside a single unit. This concept is called encapsulation.
2. No manipulation or access is allowed directly from outside the capsule or class.
Code
class MyClass:
def __init__(self):
self.__private_var = "I'm private!"
def access_private_var(self):
return self.__private_var
obj = MyClass()
print(obj.access_private_var()) # Output: I'm private!
Erroneous Code
class MyClass:
def __init__(self):
self.__private_var = "I'm private!"
def access_private_var(self):
return self.__private_var
obj = MyClass()
print(obj.__private_var) # Output: I'm private!
Throws Error!
19 Cheatsheet
Polymorphism
1. Data and the methods which operate on that data are defined inside a single unit. This concept is called encapsulation.
2. No manipulation or access is allowed directly from outside the capsule or class.
Code
class Cat:
def sound(self):
return "meow"
class Dog:
def sound(self):
return "woof"
make_sound
class Pig:
def sound(self):
cat_obj dog_obj pig_obj
return "oink"
def make_sound(animal):
print(animal.sound()) meow woof oink
cat_obj = Cat()
dog_obj = Dog()
pig_obj = Pig()
20 Cheatsheet
Errors and Exception Handling
Syntax Errors
Code
while True print('Hello world')
# Syntax error: invalid syntax
Exceptions
Code
print(10 * (1/0)) ZeroDivisionError: division by zero
Try...Except
Code
try:
print(10 * (1/0))
except ZeroDivisionError:
print("Division by zero occurred!")
Code
try:
print("Hello")
Hello
except:
Nothing went wrong
print("Something went wrong")
else:
print("Nothing went wrong")
21 Cheatsheet
The Finally Clause
Code
try:
print(10 * (1/0))
except ZeroDivisionError:
Division by zero occurred!
print("Division by zero occurred!")
This line will always be executed
finally:
print("This line will always be executed")
try
else
finally
22 Cheatsheet
Python Standard Library
math Module
Code Output
import math Square root of 16 is: 4.0
2 raised to the power 3 is: 8.0
# Square Root Absolute value of -10 is: 10.0
print("Square root of 16 is:", math.sqrt(16)) Ceiling value of 2.3 is: 3
Floor value of 2.3 is: 2
# Power
Value of PI is: 3.141592653589793
print("2 raised to the power 3 is:", math.pow(2, 3))
Value of Euler's number is: 2.718281828459045
Cosine of PI is: -1.0
# Absolute
Sine of PI/2 is: 1.0
print("Absolute value of -10 is:", math.fabs(-10))
Tangent of 0 is: 0.0
print("Ceiling value of 2.3 is:", math.ceil(2.3)) Common logarithm (base 10) of 100 is: 2.0
# Floor
print("Floor value of 2.3 is:", math.floor(2.3))
# PI
print("Value of PI is:", math.pi)
# Trigonometric functions
print("Cosine of PI is:", math.cos(math.pi))
print("Sine of PI/2 is:", math.sin(math.pi/2))
print("Tangent of 0 is:", math.tan(0))
# Logarithm (base e)
print("Natural logarithm of 1 is:", math.log(1))
23 Cheatsheet
datetime Module
Code
import datetime
Output
24 Cheatsheet
os Module
Code
import os
# Remove a directory
os.rmdir('new_dir') # removes the directory named 'new_dir'
print("Files and directories in '", cwd, "' after removing directory:")
print(os.listdir(cwd))
25 Cheatsheet
random Module
Code
import random
# Shuffle a list
random.shuffle(my_list)
print("List [1, 2, 3, 4, 5] after shuffling:", my_list)
Output
26 Cheatsheet
Advanced Topics
Generators
print(sq_nums)
Output
1
4
9
16
25
How it works!
No
Return the value
to the caller
27 Cheatsheet
Decorators
Example
Consider a function which divides two numbers.
Now, you want to add one functionality which checks if b is non-zero without changing divide function.
def make_useful(divide_func):
if b == 0:
print("Denominator must be non-zero")
return None
return divide_func(a, b)
return better_divide
@make_useful
def divide(a, b):
return a / b
28 Cheatsheet
Context Managers
Example
with open("filename.txt") as f: Creates a file descriptor f used to
data = f.read() access a file resource.
file_descriptors = []
for fl in range(10000):
file_descriptors.append(open('filename.txt', 'w'))
With Context Managers, a resource is handled properly by calling the __enter__() and __exit__() methods by default.
class FileManager():
def __init__(self, filename, mode):
self.file = None
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode) # Open the file
return self.file # return the file descriptor
# loading a file
with FileManager('test.txt', 'w') as f:
f.write('Test') # Execute this code after __enter__() method finishes.
29 Cheatsheet