Skip to main content
  1. Python Programming/

Python Cheat Sheet

·1061 words·5 mins·
Python Programming Notes
Ifarra
Author
Ifarra
Disturbing the peace!!
Table of Contents

Python Cheat Sheet
#

Python is one of the most popular programming languages, known for its simplicity and versatility. Whether you’re a beginner or an experienced programmer, having a cheat sheet can be incredibly helpful for quick reference. Below is a comprehensive cheat sheet covering essential Python concepts, syntax, and features.

1. Basic Syntax
#

Printing
#

print("Hello, World!")

Comments
#

# This is a single-line comment
"""
This is a 
multi-line comment
"""

Variables and Data Types
#

# Variables
name = "Alice"       # String
age = 30             # Integer
height = 5.5         # Float
is_student = True    # Boolean

# Data Types
type(name)           # <class 'str'>
type(age)            # <class 'int'>

2. Control Structures
#

Conditional Statements
#

if age >= 18:
    print("Adult")
elif age < 13:
    print("Child")
else:
    print("Teenager")

Loops
#

For Loop
#

for i in range(5):
    print(i)

While Loop
#

count = 0
while count < 5:
    print(count)
    count += 1

3. Functions
#

Defining Functions
#

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

Lambda Functions
#

square = lambda x: x * x
print(square(5))

Another Example
#

source : neetcode

def myFunc(n, m):
    return n * m

print(myFunc(3, 4))

# Nested functions have access to outer variables
def outer(a, b):
    c = "c"

    def inner():
        return a + b + c
    return inner()

print(outer("a", "b"))

# Can modify objects but not reassign
# unless using nonlocal keyword
def double(arr, val):
    def helper():
        # Modifying array works
        for i, n in enumerate(arr):
            arr[i] *= 2
        
        # will only modify val in the helper scope
        # val *= 2

        # this will modify val outside helper scope
        nonlocal val
        val *= 2
    helper()
    print(arr, val)

nums = [1, 2]
val = 3
double(nums, val)

4. Data Structures
#

Lists
#

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[1])  # Output: banana

Tuples
#

coordinates = (10.0, 20.0)
print(coordinates[0])  # Output: 10.0

Dictionaries
#

student = {
    "name": "Alice",
    "age": 30,
    "is_student": True
}
print(student["name"])  # Output: Alice

Sets
#

unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers)  # Output: {1, 2, 3, 4}

HashSets
#

source : neetcode

# HashSet
mySet = set()

mySet.add(1)
mySet.add(2)
print(mySet)
print(len(mySet))

print(1 in mySet)
print(2 in mySet)
print(3 in mySet)

mySet.remove(2)
print(2 in mySet)

# list to set
print(set([1, 2, 3]))

# Set comprehension
mySet = { i for i in range(5) }
print(mySet)

HashMaps
#

source : neetcode

# HashMap (aka dict)
myMap = {}
myMap["alice"] = 88
myMap["bob"] = 77
print(myMap)
print(len(myMap))

myMap["alice"] = 80
print(myMap["alice"])

print("alice" in myMap)
myMap.pop("alice")
print("alice" in myMap)

myMap = { "alice": 90, "bob": 70 }
print(myMap)

# Dict comprehension
myMap = { i: 2*i for i in range(3) }
print(myMap)

# Looping through maps
myMap = { "alice": 90, "bob": 70 }
for key in myMap:
    print(key, myMap[key])

for val in myMap.values():
    print(val)

for key, val in myMap.items():
    print(key, val)

5. Modules and Packages
#

Importing Modules
#

import math
print(math.sqrt(16))  # Output: 4.0

Creating a Module
#

Create a file mymodule.py:

def my_function():
    return "Hello from my module!"

Import it:

from mymodule import my_function
print(my_function())

6. File Handling
#

Reading from a File
#

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

Writing to a File
#

with open('file.txt', 'w') as file:
    file.write("Hello, World!")

7. Exception Handling
#

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution completed.")

8. Classes
#

source : neetcode

class MyClass:
    # Constructor
    def __init__(self, nums):
        # Create member variables
        self.nums = nums
        self.size = len(nums)
    
    # self key word required as param
    def getLength(self):
        return self.size

    def getDoubleLength(self):
        return 2 * self.getLength()

myObj = MyClass([1, 2, 3])
print(myObj.getLength())
print(myObj.getDoubleLength())

9. Arrays
#

source : neetcode

# Arrays (called lists in python)
arr = [1, 2, 3]
print(arr)

# Can be used as a stack
arr.append(4)
arr.append(5)
print(arr)

arr.pop()
print(arr)

arr.insert(1, 7)
print(arr)

arr[0] = 0
arr[3] = 0
print(arr)

# Initialize arr of size n with default value of 1
n = 5
arr = [1] * n
print(arr)
print(len(arr))

# Careful: -1 is not out of bounds, it's the last value
arr = [1, 2, 3]
print(arr[-1])

# Indexing -2 is the second to last value, etc.
print(arr[-2])

# Sublists (aka slicing)
arr = [1, 2, 3, 4]
print(arr[1:3])

# Similar to for-loop ranges, last index is non-inclusive
print(arr[0:4])

# But no out of bounds error
print(arr[0:10])

# Unpacking
a, b, c = [1, 2, 3]
print(a, b, c)

# Be careful though
# a, b = [1, 2, 3]

# Loop through arrays
nums = [1, 2, 3]

# Using index
for i in range(len(nums)):
    print(nums[i])

# Without index
for n in nums:
    print(n)

# With index and value
for i, n in enumerate(nums):
    print(i, n)

# Loop through multiple arrays simultaneously with unpacking
nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
for n1, n2 in zip(nums1, nums2):
    print(n1, n2)

# Reverse
nums = [1, 2, 3]
nums.reverse()
print(nums)

# Sorting
arr = [5, 4, 7, 3, 8]
arr.sort()
print(arr)

arr.sort(reverse=True)
print(arr)

arr = ["bob", "alice", "jane", "doe"]
arr.sort()
print(arr)

# Custom sort (by length of string)
arr.sort(key=lambda x: len(x))
print(arr)


# List comprehension
arr = [i for i in range(5)]
print(arr)

# 2-D lists
arr = [[0] * 4 for i in range(4)]
print(arr)
print(arr[0][0], arr[3][3])

# This won't work
# arr = [[0] * 4] * 4

10. Math
#

source : neetcode

# Division is decimal by default
print(5 / 2)

# Double slash rounds down
print(5 // 2)

# CAREFUL: most languages round towards 0 by default
# So negative numbers will round down
print(-3 // 2)

# A workaround for rounding towards zero
# is to use decimal division and then convert to int.
print(int(-3 / 2))


# Modding is similar to most languages
print(10 % 3)

# Except for negative values
print(-10 % 3)

# To be consistent with other languages modulo
import math
from multiprocessing import heap
print(math.fmod(-10, 3))

# More math helpers
print(math.floor(3 / 2))
print(math.ceil(3 / 2))
print(math.sqrt(2))
print(math.pow(2, 3))

# Max / Min Int
float("inf")
float("-inf")

# Python numbers are infinite so they never overflow
print(math.pow(2, 200))

# But still less than infinity
print(math.pow(2, 200) < float("inf"))

Useful Libraries
#

  • NumPy: For numerical computations.
  • Pandas: For data manipulation and analysis.
  • Matplotlib: For data visualization.
  • Requests: For making HTTP requests.
  • Flask/Django: For web development.

Article Reference - Click this
#

Related

Two Sum - Leetcode
·794 words·4 mins
Python Leetcode Leetcode-Easy Notes
How to sove Two Sum problem from Leetcode and its explaination
Guide to Data Structures and Algorithms
·794 words·4 mins
Data Structures Algorithms Notes
Data Structures and Algorithms (DSA) form the foundation of computer science and software development.
Sorting algorithms
·1267 words·6 mins
Data Structures Algorithms Notes
Sorting algorithms play a crucial role in data processing and organization, Understanding types of sorting algorithms is essential.