3 min read

    Python for DSA — Basics

    PythonDSABasics

    1. Basics

    💡 Why this matters for DSA Every DSA solution starts with variables, conditions, and loops. This is the foundation.


    1.0 What is Python?

    Python is a high-level, interpreted language. It reads like English, which makes it the most popular language for DSA practice.

    Installation & Running Code

    • Download from python.org (check "Add to PATH" during install)
    • Verify: python --version in terminal
    • Run a file: python filename.py
    • Or use the interactive REPL by typing python in terminal

    ✅ Tip: You can run all code snippets on pythontutor.com (visualizes execution step-by-step) without installing anything.


    1.1 Variables & Data Types

    Python is dynamically typed — you don't need to declare the type.

    python
    # Basic types you'll use daily in DSA
    age = 25               # int
    pi = 3.14              # float
    name = "Manik"         # str
    is_valid = True        # bool
    
    TypeExampleUsed for
    int42, -1, 0Counters, indices, numbers
    float3.14, 0.5Division results, percentages
    str"hello", 'a'String problems, char processing
    boolTrue, FalseFlags, conditions

    Type checking (useful when debugging):

    python
    type(42)      # <class 'int'>
    isinstance(42, int)  # True
    

    1.2 Input & Output

    python
    # Reading input (always comes as a string)
    n = int(input())              # single integer
    a, b = map(int, input().split())  # multiple ints
    arr = list(map(int, input().split()))  # list of ints
    
    # Output
    print("Hello")
    print(f"The answer is {42}")   # f-strings (use these!)
    

    ✅ Tip — For competitive programming / DSA practice:

    python
    import sys
    data = sys.stdin.read().split()  # fast input
    

    1.3 Basic Operators

    Arithmetic

    python
    +    -    *    /    //    %    **
    
    OperatorDoesExample
    +Addition3 + 2 = 5
    -Subtraction5 - 3 = 2
    *Multiplication3 * 4 = 12
    /Float division7 / 2 = 3.5
    //Integer div7 // 2 = 3
    %Modulo7 % 2 = 1
    **Exponent2 ** 3 = 8

    ⚠️ Watch out: / always returns a float. Use // when you need an integer result.

    Comparison (result is always bool)

    python
    ==    !=    <    >    <=    >=
    

    Logical

    python
    and    or    not
    
    python
    x = 10
    if x > 5 and x < 20:   # True
        print("yes")
    

    1.4 Comments

    python
    # Single line comment
    
    """
    Multi-line comment / docstring
    (rarely used in DSA, good for explanations)
    """
    

    1.5 type() & Typecasting

    python
    int("42")        # 42
    str(42)          # "42"
    float("3.14")    # 3.14
    bool(1)          # True
    bool(0)          # False
    bool("")         # False
    bool("hello")    # True
    

    ✅ Tip — Falsy values in Python: 0, 0.0, "", [], None, False → all evaluate to False in conditions.


    Practice Drill

    python
    # Try these:
    # 1. Read two integers and print their sum
    # 2. Read a string and print its length
    # 3. Check if a number is even or odd
    # 4. Swap two variables without a temp variable
    
    💡 Click for Solutions
    python
    # 1. Sum of two integers
    a = int(input())
    b = int(input())
    print(a + b)
    
    # 2. String length
    s = input()
    print(len(s))
    
    # 3. Even or odd
    n = int(input())
    if n % 2 == 0:
        print("Even")
    else:
        print("Odd")
    
    # 4. Swap without temp
    a, b = 5, 10
    a, b = b, a
    print(a, b)  # 10 5
    


    ← Syllabus | Next → Strings