Introduction

Python is a popular and easy-to-learn programming language. It is used in many fields such as web development, data analysis, automation, artificial intelligence, and more. This cheatsheet covers the most important and commonly used concepts in Python. It is helpful for beginners and also for experienced developers who want to revise the basics quickly.

1. Variables

  • Definition : Variables are used to store values.

Code
  
    name = "Alice"
age = 25
  • Note : You do not need to declare the data type in Python.

2. Data Types

  • Common types : int , float , str , bool , list , tuple , dict , set

Code
  
    num = 10             # int
price = 5.5          # float
name = "Tom"         # str
is_valid = True      # bool

3. Lists

  • Definition: A list is a collection of items. It is mutable (can be changed).

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

4. Tuples

  • Definition: A tuple is similar to a list, but is immutable (cannot be changed).

Code
  
    colors = ("red", "green", "blue")
print(colors[0])  # red

5. Dictionaries

  • Definition: A dictionary stores data in key-value pairs.

Code
  
    student = {"name": "John", "age": 20}
print(student["name"])  # John

6. Sets

  • Definition: A set is a collection of unique items.

Code
  
    nums = {1, 2, 3, 2}
print(nums)  # {1, 2, 3}

7. Conditional Statements

  • Used for: Decision making in code.

Code
  
    age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")

8. Loops

  • For loop: Used to repeat actions.

Code
  
    for i in range(5):
    print(i)
  • While loop: Runs while a condition is true.

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

9. Functions

  • Definition: A block of code that runs when called.

Code
  
    def greet(name):
    print("Hello", name)

greet("Alice")

10. Classes and Objects

  • Definition: Used in object-oriented programming.

Code
  
    class Person:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("Hi, I am", self.name)

p = Person("David")
p.say_hello()

11. Exception Handling

  • Used to: Handle errors without stopping the program.

Code
  
    try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

12. List Comprehension

  • Definition: A short way to create a new list.

Code
  
    squares = [x*x for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

13. Importing Modules

  • Used to: Use built-in or external code libraries.

Code
  
    import math
print(math.sqrt(16))  # 4.0

14. File Handling

  • Reading a file

Code
  
    with open("file.txt", "r") as f:
    content = f.read()
  • Writing to a file

Code
  
    with open("file.txt", "w") as f:
    f.write("Hello, world")

15. Lambda Functions

  • Definition : A small anonymous function.

Code
  
    add = lambda x, y: x + y
print(add(3, 5))  # 8

16. Map, Filter, Reduce

  • map(): Applies a function to all items.

Code
  
    nums = [1, 2, 3]
squared = list(map(lambda x: x*x, nums))
  • filter(): Filters items based on a condition.

Code
  
    even = list(filter(lambda x: x % 2 == 0, nums))
  • reduce(): Reduces a list to a single value.

Code
  
    from functools import reduce
total = reduce(lambda x, y: x + y, nums)

17. Global and Local Variables

Code
  
    x = 10  # global

def test():
    y = 5  # local
    print(x + y)

test()

18. String Formatting

Code
  
    name = "Tom"
age = 20
print(f"My name is {name} and I am {age} years old.")

19. Type Conversion

Code
  
    x = "123"
y = int(x)  # converts to integer

20. Built-in Functions

  • Some common ones: len() , type() , str() , int() , input() , print() , sum() , sorted()

21. Enumerate

  • Used to: Get index and value while looping.

Code
  
    colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(index, color)

22. Zip

  • Used to: Combine multiple iterables (like lists).

Code
  
    names = ["Alice", "Bob"]
scores = [85, 90]
for name, score in zip(names, scores):
    print(name, score)

23. Docstrings

  • Used to: Write documentation inside functions/classes.

Code
  
    def greet():
    """This function prints a greeting"""
    print("Hello")
  • Access using: print(greet.__doc__)

24. args and kwargs

  • Used to: Pass a variable number of arguments.

Code
  
    def add(*args):
    return sum(args)

def show(**kwargs):
    print(kwargs)

add(1, 2, 3)
show(name="Tom", age=30)

25. Virtual Environment (venv)

  • Used to: Create an isolated environment for a Python project.

Code
  
    python -m venv env
  • Activate: env\Scripts\activate (Windows) or source env/bin/activate (Linux/Mac)

26. List Methods

  • Common methods:

Code
  
    a = [1, 2, 3]
a.append(4)
a.remove(2)
a.pop()
a.sort()
a.reverse()

27. Dictionary Methods

Code
  
    d = {"a": 1, "b": 2}
d.keys()
d.values()
d.items()
d.get("a")

28. Comprehensions with Conditions

Code
  
    evens = [x for x in range(10) if x % 2 == 0]

29. Range

  • Used to: Generate a sequence of numbers.

Code
  
    range(5)         # 0 to 4
range(1, 6)      # 1 to 5
range(1, 10, 2)  # step by 2

30. Type Hints (Python 3.5+)

  • Used to: Show expected types in functions.

Code
  
    def add(x: int, y: int) -> int:
    return x + y

31. Unpacking

  • Used to: Assign values from a list/tuple to variables.

Code
  
    a, b = [1, 2]

32. Ternary Operator

  • Short way to write if-else :

Code
  
    result = "Yes" if x > 5 else "No"

33. Chained Comparisons

Code
  
    x = 10
if 5 < x < 15:
    print("x is between 5 and 15")

34. Generators

  • Used to: Create iterators using yield keyword.

Code
  
    def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

35. Decorators

  • Used to: Modify the behavior of a function.

Code
  
    def decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@decorator
def greet():
    print("Hello")

greet()

36. Context Manager (with statement)

  • Used to: Handle resources like files.

Code
  
    with open("file.txt") as f:
    data = f.read()

37. Assertions

  • Used to: Check conditions during development.

Code
  
    x = 5
assert x > 0, "x must be positive"

38. The __name__ == "__main__" Block

  • Used to: Run code only when a script is executed directly.

Code
  
    if __name__ == "__main__":
    print("Running directly")

39. Using pass , break , continue

  • pass : Placeholder for empty blocks

  • break : Exit a loop

  • continue : Skip to next loop iteration

Code
  
    for i in range(5):
    if i == 3:
        continue
    print(i)

40. Global Keyword

  • Used to: Change a global variable inside a function.

Code
  
    x = 10

def modify():
    global x
    x = 20

41. is vs ==

  • == checks if values are equal.

  • is checks if both variables point to the same object in memory.

Code
  
    a = [1, 2]
b = [1, 2]
print(a == b)  # True
print(a is b)  # False

42. Python Comments

  • Single-line: # This is a comment

  • Multi-line (not officially a comment, but used):

Code
  
    """
This is
a multiline comment
"""

43. Command Line Arguments with sys.argv

Code
  
    import sys
print(sys.argv[1])  # First command-line argument

44. Using dir() and help()

  • dir(obj) shows all attributes/methods of an object.

  • help(obj) gives the docstring/documentation.

Code
  
    dir(str)
help(str)

45. Using __init__ and __str__ in Classes

Code
  
    class Car:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Car name: {self.name}"

46. Private Variables (by Convention)

Code
  
    class Example:
    def __init__(self):
        self._protected = "Warning only"
        self.__private = "Strongly private"

47. Python Slicing

Code
  
    text = "abcdef"
print(text[1:4])   # 'bcd'
print(text[:3])    # 'abc'
print(text[::-1])  # reverse string

48. Set Operations

Code
  
    a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))        # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b))   # {1, 2}

49. Using all() and any()

Code
  
    nums = [1, 2, 3]
print(all(x > 0 for x in nums))  # True
print(any(x > 2 for x in nums))  # True

50. Chained Function Calls

Code
  
    def add(x):
    return x + 1

def multiply(x):
    return x * 2

print(multiply(add(3)))  # 8

51. NamedTuple (from collections )

Code
  
    from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(1, 2)
print(p.x, p.y)

52. Defaultdict

Code
  
    from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
print(d)  # defaultdict(<class 'int'>, {'a': 1})

53. Counter

Code
  
    from collections import Counter
c = Counter("banana")
print(c)  # {'a': 3, 'n': 2, 'b': 1}

54. Date and Time

Code
  
    import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

55. Regular Expressions (Regex)

Code
  
    import re
text = "abc123"
match = re.search(r"\d+", text)
print(match.group())  # 123

56. JSON Handling

Code
  
    import json
data = {"name": "Tom", "age": 20}
json_str = json.dumps(data)
parsed = json.loads(json_str)

57. Using __slots__ (Memory Optimization in Classes)

Code
  
    class Person:
    __slots__ = ['name', 'age']
    def __init__(self, name, age):
        self.name = name
        self.age = age

58. Using type() to Create Classes Dynamically

Code
  
    MyClass = type("MyClass", (object,), {"x": 5})
obj = MyClass()
print(obj.x)

59. Using eval() and exec()

  • eval() evaluates an expression.

  • exec() runs dynamic code.

Code
  
    x = 10
print(eval("x + 5"))  # 15

⚠️ Avoid using eval() or exec() with user input due to security risks.

60. Unit Testing (with unittest )

Code
  
    import unittest

class TestAdd(unittest.TestCase):
    def test_sum(self):
        self.assertEqual(2 + 3, 5)

if __name__ == "__main__":
    unittest.main()

Conclusion

If you're serious about mastering Python:

  • For backend development: Learn Flask , FastAPI , or Django .

  • For data work: Learn NumPy , Pandas , Matplotlib , Seaborn .

  • For automation: Learn Selenium , PyAutoGUI , Requests .

  • For testing: Learn pytest .

This is now a complete Python cheatsheet for practical use, projects, interviews, and continued learning.