FOR TALENT
Blog Explore the trends. Codebrew Stay up to date. Interview Questions Get prepared. Coder Glossary Learn the concepts. Portfolio Showcase your projects. University Preferences Make the right choice. Roadmap Move forward step by step. Cheat Sheets Look up the shortcuts. Free Software Tools Get a hand. Podcast Listen on the go. Salaries Learn what the market pays. AI Tools Explore AI.FOR COMPANIES
Blog HR trends. Codebrew Stay in the loop. HR Webinars Hear from the experts. Case Studies Get inspired. E-book Download the guides. HR Calculation Tools Calculate with ease.
This Python cheat sheet tries to provide basic reference for beginner and advanced developers.
// Hello World
// Basic Commands
// Getting Started Resources
// Primitive Data Types
// Type Checking
print(type(3.14)) # <class "float">
print(isinstance("a", str)) # True
// Type Checking Resources
// Type Conversion Functions
// Type Conversion Resources
// Type Conversion Examples
int("5") # 5
float("3.14") # 3.14
str(5) # "5"
list("abc") # ["a","b","c"]
// Simple List Comprehension
[x*x for x in range(5)] # [0, 1, 4, 9, 16]
// Conditional List Comprehension
[x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
// Nested List Comprehension
matrix = [[1,2],[3,4]]
flattened = [num for row in matrix for num in row] # [1,2,3,4]
// List Comprehension Resources
// if-elif-else
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")
// for Loop
for i in range(3):
print(i)
for i in [1,2,3]:
print(i)
// while Loop
i = 0
while i < 3:
print(i)
i += 1
// Loop Control Keywords
// Loop Control Resources
// Function Definition
def add(a, b):
return a + b
// Default Arguments
def greet(name="World"):
print(f"Hello, {name}")
// *args and **kwargs
def func(*args, **kwargs):
print(args)
print(kwargs)
// Function Attributes
// Function Resources
// Lambda Function
square = lambda x: x * x
print(square(5)) # 25
// map()
nums = [1, 2, 3]
squares = list(map(lambda x: x*x, nums))
// filter()
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))
// reduce()
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
// Class Definition
class Car:
def __init__(self, brand):
self.brand = brand
def start(self):
print(f"{self.brand} is starting")
// OOP Terms
// Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Woof!")
// Classmethod & Staticmethod
class Example:
@staticmethod
def static():
print("Static method")
@classmethod
def cls(cls):
print("Class method")
// Simple Decorator
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
// Using @decorator
@my_decorator
def greet():
print("Hello!")
// Generator Function
def counter():
for i in range(3):
yield i
// Generator Features
// Iterator Protocol
it = iter([1,2,3])
print(next(it)) # 1
// Generator Resources
// Generator Example
def counter():
for i in range(3):
yield i
// try-except
try:
x = 1 / 0
except ZeroDivisionError as e:
print("Error:", e)
// finally and else
try:
x = 1
except:
pass
else:
print("No error!")
finally:
print("Always runs")
// Error Handling Resources
// Common Exceptions
// Reading a File
with open("file.txt", "r") as f:
content = f.read()
// Writing to a File
with open("file.txt", "w") as f:
f.write("Hello!")
// Reading Line by Line
with open("file.txt") as f:
for line in f:
print(line.strip())
// File I/O Resources
// Importing Modules
import math
print(math.sqrt(16))
// Modules Resources
// Importing Modules
import random
print(random.randint(1, 100))
// Common Modules
// Modules Resources
// pip Commands
// Create Virtual Environment
python -m venv venv
source venv/bin/activate
// Packaging & Environment Tools
// Simple Test (unittest)
import unittest
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
// Testing Resources
// Type Hints
def add(a: int, b: int) -> int:
return a + b
// Common Typing Types
// Typing Resources
// Basic Dataclass
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
// Dataclasses Resources
// Using Pathlib
from pathlib import Path
p = Path("file.txt")
print(p.exists())
// Pathlib Resources
// Basic Logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
// Logging Resources
// Basic Argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo")
args = parser.parse_args()
// Argparse Resources
// Basic Async Function
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main())
// Asyncio Resources
// with Statement
with open("file.txt") as f:
data = f.read()
// Context Managers Resources
// Custom Context Manager
from contextlib import contextmanager
@contextmanager
def my_cm():
print("Enter")
yield
print("Exit")
with my_cm():
print("Inside")
// With Statement Resources
// Common Built-ins
Get inspired, learn, join competitions and grow in your job!
Sign up now