0% found this document useful (0 votes)
64 views6 pages

Advanced Python Cheat Sheet Guide

This document is an extended cheat sheet for Python, covering essential topics such as variables, data structures, control flow, functions, classes, and modules. It also includes advanced concepts like decorators, context managers, regular expressions, async/await, type hints, and testing. Additionally, it provides information on popular libraries and debugging techniques, making it a comprehensive reference for Python programming.

Uploaded by

Hridoy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views6 pages

Advanced Python Cheat Sheet Guide

This document is an extended cheat sheet for Python, covering essential topics such as variables, data structures, control flow, functions, classes, and modules. It also includes advanced concepts like decorators, context managers, regular expressions, async/await, type hints, and testing. Additionally, it provides information on popular libraries and debugging techniques, making it a comprehensive reference for Python programming.

Uploaded by

Hridoy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Extended Cheat Sheet

1️⃣ Variables and Basic Types

x = 10 # int
y = 3.14 # float
name = "Alice" # str
flag = True # bool
nothing = None # NoneType

2️⃣ Data Structures

Lists

fruits = ["apple", "banana"]


[Link]("cherry")
fruits[0]
fruits[1:3]

Tuples

point = (2, 3)
x, y = point

Sets

colors = {"red", "green"}


[Link]("blue")

Dictionaries

person = {"name": "Bob", "age": 25}


person["name"]
[Link]("city", "Unknown")

3️⃣ Operators
• Arithmetic: + - * / // % **
• Comparison: == != < <= > >=
• Logical: and or not
• Membership: in not in

1
• Identity: is is not

4️⃣ Control Flow

If/Elif/Else

if x > 0:
...
elif x == 0:
...
else:
...

Loops

for i in range(5):
...
while condition:
...
break, continue, else

5️⃣ Functions

def add(a, b):


return a + b

def greet(name="World"):
print(f"Hello, {name}!")

6️⃣ Classes & OOP

class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
return f"{[Link]} makes a sound"

class Dog(Animal):
def speak(self):
return f"{[Link]} barks"

2
7️⃣ Modules & Packages

# [Link]
def foo():
...

# usage
import mymodule
from mymodule import foo

8️⃣ File Handling

with open("[Link]", "r") as f:


data = [Link]()

with open("[Link]", "w") as f:


[Link]("Hello")

9️⃣ Comprehensions

squares = [x**2 for x in range(10)]


unique_chars = {c for c in "hello"}
squares_map = {x: x**2 for x in range(5)}

🔟 Exception Handling

try:
risky_code()
except ValueError as e:
print(e)
finally:
cleanup()

1️⃣1️⃣ Built-ins & Useful Functions

len(), sum(), min(), max(), sorted()


enumerate(), zip(), map(), filter()
all(), any(), dir(), help()

3
1️⃣2️⃣ Iterators & Generators

nums = iter([1, 2, 3])


next(nums)

def countdown(n):
while n > 0:
yield n
n -= 1

1️⃣3️⃣ Decorators

def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper

@my_decorator
def say_hi():
print("Hi")

1️⃣4️⃣ Context Managers

from contextlib import contextmanager

@contextmanager
def open_resource():
print("Open")
yield
print("Close")

with open_resource():
pass

1️⃣5️⃣ Regular Expressions

import re
pattern = [Link](r'\d+')
result = [Link]("123 abc 456")

4
1️⃣6️⃣ Async / Await

import asyncio

async def task():


await [Link](1)

[Link](task())

1️⃣7️⃣ Type Hints

def add(x: int, y: int) -> int:


return x + y

from typing import List, Dict, Optional

1️⃣8️⃣ Testing

import unittest

class TestMath([Link]):
def test_add(self):
[Link](add(2, 3), 5)

if __name__ == "__main__":
[Link]()

1️⃣9️⃣ Virtual Environments

python -m venv venv


source venv/bin/activate # Unix
venv\Scripts\activate # Windows

2️⃣0️⃣ Packaging

pip install wheel


python [Link] sdist bdist_wheel

5
2️⃣1️⃣ Popular Libraries

NumPy

import numpy as np
a = [Link]([1, 2, 3])
[Link](a)

Pandas

import pandas as pd
df = [Link]({"A": [1, 2]})
[Link]()

Matplotlib

import [Link] as plt


[Link]([1,2,3],[4,5,6])
[Link]()

2️⃣2️⃣ Debugging & Performance

# Debugging
import pdb; pdb.set_trace()

# Timing
import timeit
[Link]('sum(range(100))', number=1000)

# Profiling
import cProfile
[Link]('my_function()')

This cheat sheet should serve as a solid extended reference across beginner to advanced Python topics!

Common questions

Powered by AI

Python facilitates asynchronous programming using `async` and `await` keywords. The `async def` syntax defines an asynchronous function, and `await` pauses the function's execution until a given coroutine completes. This model allows Python to handle IO-bound and high-level structured network code efficiently, enabling concurrency without the typical complexity of thread management. For example, `async def task(): await asyncio.sleep(1)` schedules an asynchronous task with `asyncio.run(task())`, which can significantly improve program responsiveness and resource utilization .

The `unittest` module in Python provides a rich framework for testing code, supporting test case creation, setup, execution, and reporting. It follows a simple model where test functions are methods of a subclass of `unittest.TestCase`. For instance, a test for an `add` function might look like `class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5)`. The advantages of `unittest` include automation, the ability to run tests grouped in test suites, and integration with build systems. It helps in identifying errors early, improving code reliability, and maintaining consistent behavior across modifications .

Python's context managers, accessed using the `with` statement, ensure resources are properly managed, avoiding leaks by guaranteeing cleanup actions are executed. They handle entry and exit actions automatically, as seen in file operations: `with open("file.txt", "w") as f: f.write("Hello")`. Custom context managers can be created using the `contextlib.contextmanager` decorator to manage non-file resources, providing the same robust usage control. This mechanism enhances reliability of resources handling in a predictable manner .

Python's built-in functions like `len()`, `sum()`, and `sorted()` provide efficient, optimized ways to perform common operations. `len()` returns the length of a container, `sum()` adds numeric iterables, and `sorted()` returns a sorted list from iterable inputs. These functions enhance code efficiency by using internally optimized algorithms. They also improve readability and maintainability by abstracting complex operations into simple, intuitive calls. Using built-in functions ensures compatibility with different data types and language updates, adhering to the Pythonic principle of simplicity and clarity .

List comprehensions offer a concise way to create lists, which can lead to more readable and typically more efficient code compared to traditional loops. They enable in-line iteration with an expression, for example, `[x**2 for x in range(10)]` creates a list of squares in one line. Unlike loops, which require multiple lines and possibly temporary variables, comprehensions allow filtering and transformation in a single, nested structure .

Python supports object-oriented programming (OOP) through classes and objects, enabling encapsulation, inheritance, and polymorphism. A class in Python is a blueprint for creating objects. It includes a constructor method `__init__` to initialize object states, and methods for defining behaviors. For example, an `Animal` class might have a `speak` method that is overridden by a derived `Dog` class to specialize its behavior: `Dog(Animal): def speak(self): return f"{self.name} barks"` .

In Python, decorators are a powerful feature for modifying the behavior of functions or methods. They are applied by prefixing a function definition with `@decorator_name`. A decorator function takes a function as an argument and returns a new function, often internally wrapping the original. For instance, `def my_decorator(func): def wrapper(*args, **kwargs): print("Before") result = func(*args, **kwargs) print("After"); return result; return wrapper`. The `@my_decorator` before the `say_hi` function modifies it to print additional messages before and after execution. Decorators are typically used for logging, authentication, enforcing access control, and other cross-cutting concerns .

Type hints in Python, introduced in PEP 484, are annotations that specify the expected data type of variables and function return values using hints like `def add(x: int, y: int) -> int:`. While type hints do not provide runtime type enforcement, they significantly improve code clarity and facilitate static analysis tools like `mypy` to detect type-related errors. This enhances code quality, comprehensibility, and maintainability, particularly in large codebases where ensuring interface contracts can prevent bugs and improve developer productivity .

Virtual environments in Python are used to create isolated environments for projects, ensuring that dependencies are not shared across projects. This isolation is crucial to managing module versions and compatibility issues. For instance, using `venv`, you can create a new virtual environment with `python -m venv venv`, and activate it with `source venv/bin/activate`. This setup helps maintain distinct environments for projects with differing requirements, improves project management by preventing dependency conflicts, and supports cleaner deployment processes .

Python handles exceptions using `try`, `except`, and `finally` blocks, allowing the programmer to manage errors gracefully. For example, if a `ValueError` occurs in `try` block, the `except` block will handle it: `try: risky_code() except ValueError as e: print(e)`. The `finally` block is executed no matter what, useful for cleanup actions. This mechanism helps avoid program crashes and handle errors in a controlled way, ensuring reliability and robustness of code .

You might also like