Python Cheatsheet




Introduction

Python is an interpreted, high-level, dynamic, free, and open-source programming language. Both procedural and object-oriented programming are supported by it.


  • Free and Open Source
  • Object-Oriented Language
  • High-Level Language
  • Extensible feature
  • Interpreted Language:
  • Dynamically Typed Language
  • Allocating Memory Dynamically


Install

Download and Install Python IDE


Basics

# This is s comment
# output "Hello, World!" to the terminal
print("Hello, World!")
view raw python_print.py hosted with ❤ by GitHub


Variables

data = 10 # integer
data = 10.1 # float
data = "string data" # string
data = True # boolean
a,b = 1,22 # many values to multiple variables
a = b = 13 # same value to multiple variables


Variable scope

# global scope
global data
data = 123
def test():
# local scope
data = 4
print(data)
test() # 4
print(data) # 123


Datatypes

# Strings: A sequence of characters enclosed in single or double quotes.
data = "some data"
print(type(data)) # <class 'str'>
# Integers: Whole numbers without a decimal point.
data = 123
print(type(data)) # <class 'int'>
# Floats: Numbers with a decimal point.
data = 123.2
print(type(data)) # <class 'float'>
# Booleans: Represent either True or False.
data = False
print(type(data)) # <class 'bool'>
# Complex Numbers: Numbers with a real and imaginary part.
data = 1+2j
print(type(data)) # <class 'complex'>
# Lists: Ordered, mutable collections of items.
data = [1, 2, 3]
print(type(data)) # <class 'list'>
# Tuples: Ordered, immutable collections of items.
data = (1, 2, 4)
print(type(data)) # <class 'tuple'>
# Dictionaries: Collections of key-value pairs.
data = {'a': 1, 'b': 2}
print(type(data)) # <class 'dict'>
# Frozensets: Immutable sets.
data = frozenset({1, 2, 3})
print(type(data)) # <class 'frozenset'>
# Sets: Unordered collections of unique items.
data = {1, 2, 3}
print(type(data)) # <class 'set'>
# Ranges: Represents a sequence of numbers.
data = range(10)
print(type(data)) # <class 'range'>
# Bytes: Represents a sequence of bytes.
data = b'bytes data'
print(type(data)) # <class 'bytes'>
# Bytearrays: Mutable sequence of bytes.
data = bytearray(34)
print(type(data)) # <class 'bytearray'>
# Memoryview: Used to access the memory of an object.
data = memoryview(bytes(32))
print(type(data)) # <class 'memoryview'>
# None: Represents the absence of a value or a null value.
data = None
print(type(data)) # <class 'NoneType'>


List vs Tuples

# List

  • List are mutable
  • Iterations are time-consuming
  • Lists consume more memory
  • Inserting and deleting items is easier with a list.


# Tuple

  • Tuples are immutable
  • Iterations are comparatively Faster
  • Accessing the elements is best accomplished with a tuple data type.
  • Tuple consumes less memory than the list


Type casting

Sometimes we may need to convert one datatype to another, termed "type casting."

value = int(3.8) # value will be 3
value = float(1) # value will be 1.0
value = str(2) # value will be '2'


Operators

# Arithmetic
print(1+2) # Addition: 1 + 2 = 3
print(2-1) # Subtraction: 2 - 1 = 1
print(1*2) # Multiplication: 1 * 2 = 2
print(1/2) # Division: 1 / 2 = 0.5
print(3%2) # Modulus (Remainder): 3 % 2 = 1
print(3**2) # Exponentiation: 3^2 = 9
print(5//2) # Floor Division: 5 // 2 = 2 (rounded down)
# Assignment
x = 12
print(x) # x is assigned the value 12
x += 2
print(x) # Add 2 to x: x = 14
x -= 2
print(x) # Subtract 2 from x: x = 12
x *= 2
print(x) # Multiply x by 2: x = 24
x /= 2
print(x) # Divide x by 2: x = 12.0
x %= 5
print(x) # Modulus of x by 5: x = 2.0
x //= 2
print(x) # Floor divide x by 2: x = 1.0
x **= 2
print(x) # Square x: x = 1.0
# Comparison
print(1==2) # Equal: 1 is not equal to 2, so False
print(1!= 2) # Not Equal: 1 is not equal to 2, so True
print(1>2) # Greater Than: 1 is not greater than 2, so False
print(1<2) # Less Than: 1 is less than 2, so True
print(1>=2) # Greater Than or Equal: 1 is not greater than or equal to 2, so False
print(1<=2) # Less Than or Equal: 1 is less than or equal to 2, so True
# Logical
print(1 and 0) # Logical AND: 1 and 0, so 0 (False)
print(1 or 0) # Logical OR: 1 or 0, so 1 (True)
print(not 1) # Logical NOT: not 1 is False
# Identity
x, y = 1, 1
print(x is y) # Identity operator: x is y, so True
print(x is not y) # Identity operator: x is not y, so False
# Membership
print(1 in [1,2]) # Membership: 1 is in the list [1, 2], so True
print(1 not in [1,2]) # Membership: 1 is in the list [1, 2], so False
# Bitwise
print(1 & 2) # Bitwise AND: 01 & 10 = 00 (0 in binary), so 0
print(1 | 2) # Bitwise OR: 01 | 10 = 11 (3 in binary), so 3
print(1 ^ 2) # Bitwise XOR: 01 ^ 10 = 11 (3 in binary), so 3
print(~2) # Bitwise NOT: ~10 = -11 (-3 in binary), so -3
print(1 << 2) # Left Shift: 01 << 2 = 100 (4 in binary), so 4
print(4 >> 2) # Right Shift: 100 >> 2 = 01 (1 in binary), so 1


Strings

data = "string data"
data = """ Multi line string """
data = ''' Multi line String '''
print(data[1]) # first character of string variable
print(len(data)) # length of string
# Looping through a string
for character in data:
print(character)
# search string
data = "string data"
if "ta" in data:
print("Searched string present")
# string slicing
data = "abcdefghijk"
print(data[2:]) # cdefghijk
print(data[:3]) # abc
print(data[1:4]) # bcd
print(data[1:-3]) # bcdefgh
print(data[-3:-1]) # ij
data = " abc ABC"
# modify strings
print(data.upper()) # convert to uppercase
print(data.lower()) # convert to lowercase
print(data.strip()) # remove whitespace (left/right)
print(data.replace("abc","EFG")) # replace string value
print(data.split(" ")) # split the string with whitespaces , return a list
lower = "abc..."
upper = "ABC..."
# concatenate strings
print(lower+upper) # abc...ABC...
print(lower+"deff") # abc...deff
# concatenate string & number
data = "Roll number is : {}"
print(data.format(30)) # Roll number is : 30
# escape character
data = "here is the way to store \"double quates\" string"
print(data) # here is the way to store "double quotes" string
data = "techworldthink"
# methods
print(data.capitalize()) # Techworldthink
print(data.count('t')) # 2
print(data.find('w')) # return first position of searched string, return -1 if not found
print(data.index('w')) # return first position of searched string, throw a ValueError exception if not found
print(data.isalnum()) # True
print(data.isalpha()) # True
print(data.isdigit()) # False
print(data.islower()) # True
print(data.isupper()) # False
print(data.isnumeric()) # False
# formats
fname = "tech"
lname = "worldthink"
data = "%s %s" %(fname,lname)
print(data) # tech worldthink
data = "{} {}".format(fname,lname)
print(data) # tech worldthink
data = f"{fname} {lname}"
print(data) # tech worldthink


Boolean

print(1>2) # False
print(1<2) # True
print(1==2) # False
print(bool("some string")) # True
print(bool(23)) # True
print(True) # True
print(False) # False
print(bool(0)) # False
print(bool(None)) # False
print(bool("")) # False
print(bool(())) # False
print(bool([])) # False
print(bool({})) # False


Tuple
# create tuple
data = (1,"a",True)
# access
print(data[0]) # 1
# slice
print(data[0:3]) #(1, 'a', True)
# doesn't allow item re-assignment
# immutable - Unchangeable
# data[0] = 12 # it's an error
# concatenate
print(data+data) # (1, 'a', True, 1, 'a', True)
# repeate
print(data*2) # (1, 'a', True, 1, 'a', True)
# tuple with one item - not a tuple
data = ("one item")
print(type(data)) # <class 'str'>
# tuple constructor
data = tuple((1,2,3))
print(type(data)) # <class 'tuple'>
#methods
data = (1,2,3)
print(len(data)) # 3
print(max(data)) # 3
print(min(data)) # 1
print(data.count(2)) # 1
print(data.index(1)) # 0
# loop
data = (1,2,3)
for each in data:
print(each)
view raw python_tuple.py hosted with ❤ by GitHub


List

# create
data = [1,2,3,4,5]
# access
print(data[1]) # 2
# change
data[1] = 13
print(data) # [1, 13, 3, 4, 5]
# methods
# add data to the end of that list
data.append("234")
print(data) # [1, 13, 3, 4, 5, '234']
# insert a value to the specified index
data.insert(0,233)
print(data) # [233, 1, 13, 3, 4, 5, '234']
# to extend a list with another list of data
data.extend([3,2,3,3,3,3])
print(data) # [233, 1, 13, 3, 4, 5, '234', 3, 2, 3, 3, 3, 3]
data = [1,2,3]
# to extend a list with tuple data
data.extend((4,5,6))
print(data) # [1, 2, 3, 4, 5, 6]
# remove specified item
data.remove(6)
print(data) # [1, 2, 3, 4, 5]
# remove value from a specified index
# if the index is not found, it will produce an exception
data.pop(0)
print(data) # [2, 3, 4, 5]
# remove value from the last index
data.pop()
print(data) # [2, 3, 4]
# remove value from the specified index
# if an index is not found, do not produce an exception
del data[2]
print(data) # [2, 3]
# delete list
del data
# clear list values
data = [1,2,3]
data.clear()
print(data) # []
# sort
data = [1,2,3,0]
data.sort()
print(data) # [0, 1, 2, 3]
data.sort(reverse = True)
print(data) # [3, 2, 1, 0]
data.reverse()
print(data) # [0, 1, 2, 3]
#case sensitive based sort
data = ["b","a","A"]
data.sort()
print(data) # ['A', 'a', 'b']
data.sort(key = str.upper)
print(data) # ['A', 'a', 'b']
# custom sorting
data = [2,1,3]
def custom_sort(num):
return abs(100-num)
data.sort(key = custom_sort)
print(data) # [3, 2, 1]
# copy a list
new_data = data.copy()
print(new_data) # [3, 2, 1]
new_data = list(data)
print(new_data) # [3, 2, 1]
# loop
data = [1,2]
for each in data:
print(each)
# list comprehension
#newlist = [expression for item in iterable if condition == True]
# simple
new_data = [each for each in data]
print(new_data) # [1, 2]
# with conditions
new_data = [each for each in data if each%2==0]
print(new_data) # [2]
# join lists
a = [1,2,3]
b = [4,5,6]
c = a+b
print(c) #[1, 2, 3, 4, 5, 6]
view raw python_list.py hosted with ❤ by GitHub


Sets

# unchangeable
# unordered
# duplicates not allowed
# create
data = set((1,2,3))
data = {1,2,4,5}
print(data) # {1, 2, 4, 5}
# length
print(len(data)) # 4
print(type(data)) # <class 'set'>
# access items
for each in data:
print(each,end="") # 1245
if 1 in data:
print("present") # present
# add items
data.add(123)
print(data) # {1, 2, 4, 5, 123}
# add set
data.update({23,233})
print(data) # {1, 2, 4, 5, 233, 23, 123}
data.update([231,2331])
# remove
# if the item doesn't exist, it will raise an error
data.remove(231)
print(data) # {1, 2, 4, 5, 233, 2331, 23, 123}
# if the item doesn't exist, it will not raise an error
data.discard(231)
print(data) # {1, 2, 4, 5, 233, 2331, 23, 123}
# to remove random item
data.pop()
print(data) # {2, 4, 5, 233, 2331, 23, 123}
# to clear a set
data.clear()
print(data) # set()
# to delete a set
del data
# set operations
# return new set
# note: True and 1 are considered the same value in sets
data_1 = {1,2,3}
data_2 = {3,4,5}
print(data_1.union(data_2)) # {1, 2, 3, 4, 5}
# keep only the items that are present in both sets
print(data_1.intersection(data_2)) # {3}
# elements that are NOT present in both
print(data_1.symmetric_difference(data_2)) # {1, 2, 4, 5}
# difference
print(data_1.difference(data_2)) # {1, 2}
# check disjoint set or not
print(data_1.isdisjoint(data_2)) # False
# check subset or not
print(data_1.issubset(data_2)) # False
# keep only the items that are present in both sets
data_1.intersection_update(data_2)
print(data_1) # {3}
# elements that are NOT present in both
data_1.symmetric_difference_update(data_2)
print(data_1) # {4, 5}
view raw python_sets.py hosted with ❤ by GitHub


Dictionary

# Dictionaries
# Ordered
# Changeable
# Duplicates not allowed
# create
data = {
1:"A",
2:"B",
}
print(data) # {1: 'A', 2: 'B'}
print(data[1]) # A
print(len(data)) # 2
print(type(data)) # <class 'dict'>
print(dict(a='aA',b='bB')) # {'a': 'aA', 'b': 'bB'}
# change value
data[1] = "Aa"
print(data) # {1: 'Aa', 2: 'B'}
# update dictionary
data.update({1:"A"})
print(data) # {1: 'A', 2: 'B'}
# adding new items
data[3] = "C"
print(data) # {1: 'A', 2: 'B', 3: 'C'}
data.update({4:"D"})
print(data) # {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
# remove items
data.pop(2) # specify key
print(data) # {1: 'A', 3: 'C', 4: 'D'}
data.popitem() # removes last inserted item
print(data) # {1: 'A', 3: 'C'}
del data[1]
print(data) # {3: 'C'}
data.clear()
print(data) # {}
# loop
data = {
1:"A",
2:"B",
}
for key in data:
print(key,data[key],end=" ") # 1 A 2 B
for value in data.values():
print(value,end=" ") # A B
for key in data.keys():
print(key,end=" ") # 1 2
for key,value in data.items():
print(key,value,end=" ") # 1 A 2
# copy a dictionary
data_copy = data.copy()
print(data_copy) # {1: 'A', 2: 'B'}
data_copy = dict(data)
print(data_copy) # {1: 'A', 2: 'B'}


Control flow statements

# if
x,y = 1,2
if x>y:
print(x)
elif y>x:
print(y)
else:
print(x,y)
# short hand if
if x>y : print(x)
# short hand if else
# Ternary Operators
print(x) if x > y else print(y)
# if + and
if x>y and y<x:
print("Not possible!")
# if + or
if x>y or y<x:
print("possible!")
# if + not
if not y<x:
print("Not possible!")
# pass
for i in range(10):
if i%2==0:
pass
else:
print(i,end=" ") # 1 3 5 7 9
# break
# conditionally breaking the for loop 
for i in range(10):
if i%2==1:
break
else:
print(i,end=" ") # 0
# continue
# to avoid the execution of statements after the continue statement and execute the loop again
for i in range(10):
if i%2==1:
continue
else:
print(i,end=" ") # 0 2 4 6 8


Loops

num = 1
data = [1,2,4]
name = 'tech world think'
# while
while num < 10:
print(num)
num += 1
# for + range()
for num in range(10):
print(num)
# for - list iteration
for each in data:
print(each)
# for + string iteration
for letter in name:
print(letter)
# for else
# Only if there is no break will the else statement work. 
for num in range(3):
print(num)
else:
print("Finished!")
view raw python_loops.py hosted with ❤ by GitHub


Exception handling

# exception handling
try:
file = open('file','r')
except Exception as e:
# If there is a exception then execute this block.
print(e)
else:
# If there is no exception then execute this block.
file.close()
finally:
# finally execute these statements
print("Done!")
# try + except
try:
a,b = 1
except:
print("Exception!")
# try + finally
try:
a = 1
finally:
print("Done!")
# raising an exception
try:
raise IOError("Demo error")
except Exception as e:
print(e)
## Standard exceptions
# SyntaxError
# ZeroDivisionError
# ValueError
# KeyboardInterrupt
# NameError


Functions

# function is a block of code which only runs when its called
# demo function
def demo():
pass
# function without arguments
def send_email(): # function definition
print("Success")
send_email() # function call
# function with arguments
def send_email(to_email):
print(to_email," - Email sent successfully")
send_email("twt@gmail.com")
# function without any return value
def send_email():
print("Success")
send_email()
# function with a return value
def send_email():
return "Success"
print(send_email())
# multiple arguments
def print_name(fname,lname):
print(fname,lname)
print_name("fname","lname")
# arbitary arguments - *args
def print_name(*name):
print(name[0],name[1])
print_name("fname","lname")
# keyword arguments
def print_name(fname,lname):
print(fname,lname)
print_name(fname="fname",lname="lname")
# arbitary keyword arguments - *kwargs
def print_name(**name):
print(name['fname'],name['lname'])
print_name(fname="fname",lname="lname")
# default parameter value
def distance(dis,unit="m"):
print(dis,unit)
distance(100)
# passing list as argument
def print_(data):
print(data)
print_([1,2,3])
# return multiple values
def print_(data):
return [data,data*2]
print(print_([1,2,3]))
#### Builtin Functions ####
# enumerate()
data = [1,2,4]
for row in enumerate(data):
print(row[0],row[1]) # print index & values


Modules

A file with Python definitions and statements is known as a module. Variables, classes, and functions can all be defined in a module. Runnable code may also be included in a module. Code that has been grouped together into modules is simpler to read and utilise.

eg: os, sys

Packages
Python packages can contain several modules. A package is a directory of Python modules that differs from a directory intended to hold numerous Python scripts by including an additional __init .py file. Providing that each relevant directory has its own __init .py file, packages can be nested in various depths.

eg: pandas


Functional Programming
  • For the same input, this function always returns the same result.
  • It will not modify any argument and global variables.
  • Functional languages use recursion to implement iteration.
  • Functions can be Higher-Order and First-Class.
  • We can add new variables, but we cannot change any already existing variables.

If a programming language treats functions as first-class objects, then it is said to support first-class functions.
Higher-order functions are those that either return a function as their result or take one or more functions as arguments.

# higher order functions example
def lower_case(text):
return text.lower()
def print_msge(function_name):
msge = function_name('ABC abc')
print(msge)
print_msge(lower_case)
# lambda
# small anonymous function
# multiple arguments & only one expression
# In situations where an anonymous function is needed for a brief duration, use lambda functions.
converter = lambda currency : currency * 60
print(converter(100))
sum = lambda value_1,value_2 : value_1 + value_2
print(sum(1,2))
# anonymous function inside another function.
def power(num):
return lambda value : value ** num
get_square = power(2)
print(get_square(10))
# lambda - practical example 1
func = [lambda arg=x: arg * 100 for x in range(1, 5)]
for each in func:
print(each(),end=" ") # 100 200 300 400
#------------ Built in Higher order function ---------------
# Map()
# map(fun,iter) - example 1
def multiply(num):
return num * num
numbers = [1,2,3,4,5]
res = map(multiply,numbers)
print(res) # <map object at 0x000001E3F6573D90>
for data in res:
print(data,end=" ") # 1 4 9 16 25
# map - example 2
data = ["ABC","BCD"]
print(list(map(list,data))) # [['A', 'B', 'C'], ['B', 'C', 'D']]
# filter()
def isodd(num):
return True if num % 2 != 0 else False
nums = [1,2,3,4,5,6]
odd = list(filter(isodd,nums))
print(odd) # [1, 3, 5]
# filter() + lambda
result = filter(lambda x: x % 2 != 0, nums)
print(list(result)) # [1, 3, 5]
# reduce
from functools import reduce
def multiply(x,y):
return x*y
print(reduce(multiply,[1,2,3,4])) # 24

Class

A class in Python is a blueprint for creating objects, encapsulating both data (attributes) and behavior (methods) that are associated with those objects. It is a fundamental concept in object-oriented programming (OOP) that allows you to model and structure your code in a way that reflects the real-world entities and relationships within your program, making it more organized, reusable, and maintainable.

# create a class
class TestClass:
# public attributes
data = 123
num = 0
# constructor
def __init__(self,num):
self.num = num
self.num_2 = num
print("This is a constructor")
def __str__(self):
return f"{self.data} - {self.num} - {self.num_2}"
# object method
# self - this parameter is a reference to the current instance.
def get_data(self):
return self.data
# create object of class TestClass
obj = TestClass(456)
print(obj.data) # 123
print(obj.num) # 456
# print an object
print(obj) # 123 - 456
print(obj.get_data()) # 123
# modify object property
obj.data = 89
print(obj.data) # 89
# its a class attribute, so it will set default value
del obj.data
print(obj)
print(obj.num_2)
del obj.num_2
# AttributeError: 'TestClass' object has no attribute 'num_2'
# print(obj.num_2)
# delete object
del obj
view raw python_class.py hosted with ❤ by GitHub

Inheritance

Inheritance in Python is a fundamental concept of object-oriented programming (OOP) that allows one class (the child class or subclass) to derive attributes and methods from another class (the parent class or superclass). This mechanism enables code reuse and the creation of a hierarchical structure of classes, where child classes inherit the characteristics of parent classes while also having the flexibility to add their own attributes and methods. Inheritance is a core principle in OOP, facilitating the organization and extension of code, as well as promoting modularity and reusability.

# Parent class
class Author():
author_name = "" # Class attribute to store author's name
def __init__(self, name):
self.author_name = name # Constructor initializes the author_name attribute
def __str__(self):
return f"{self.author_name}" # String representation of the Author object
# Child class
class Book(Author):
book_name = "" # Class attribute to store book's name
def __init__(self, bname, aname):
# Initialize the Book object, calling the parent class's constructor
super().__init__(aname)
self.book_name = bname
def __str__(self):
return f"{self.author_name} - {self.book_name}" # String representation of the Book object
# Create an object
obj = Book("sherlock", "holmes")
print(obj) # Print the string representation of the Book object
# Output:
# holmes - sherlock

Constructor overriding

In Python, constructor overriding refers to the ability of a subclass (child class) to provide its own implementation of the constructor (__init__ method) inherited from its superclass (parent class). This allows the child class to customize the initialization process by defining its own attributes or behavior specific to the child class, while still having the option to call the constructor of the parent class using the super() function. Constructor overriding is a fundamental aspect of object-oriented programming (OOP) in Python, facilitating code reusability and extensibility in class hierarchies.

# Inheritance without overriding the parent's __init__()
class Parent1():
def __init__(self):
print("Parent constructor invoked")
class Child1(Parent1):
pass
obj1 = Child1()
# Output: "Parent constructor invoked"
# Explanation: In this case, the child class (Child1) does not define its own __init__() method,
# so it inherits the __init__() method from the parent class (Parent1).
# Inheritance with the child class overriding the parent's __init__()
class Parent2():
def __init__(self):
print("Parent constructor invoked")
class Child2(Parent2):
def __init__(self):
print("Child constructor invoked")
obj2 = Child2()
# Output: "Child constructor invoked"
# Explanation: In this case, the child class (Child2) defines its own __init__() method,
# which overrides the __init__() method of the parent class (Parent2).
# Therefore, when you create an instance of Child2, it calls the Child2 constructor.
# Using super() to call the parent class's __init__()
class Parent3():
def __init__(self):
print("Parent constructor invoked")
class Child3(Parent3):
def __init__(self):
super().__init__() # Using super() to call the parent's constructor
print("Child constructor invoked")
obj3 = Child3()
# Output:
# "Parent constructor invoked"
# "Child constructor invoked"
# Explanation: In this case, the child class (Child3) uses super().__init__() to explicitly call
# the constructor of the parent class (Parent3). This allows the child class to inherit and
# extend the behavior of the parent class's constructor.
# Note: The commented out lines like "Parent3.__init__(self)" are an alternative way to call
# the parent class's constructor, but using super() is considered a more Pythonic and flexible approach.




Comments

Post a Comment

Popular Posts