Day 1 Python 2024

Day 1/30 Python + DSA quick revision

Syntax

Python syntax is designed to be readable and straightforward. Here are some key points:

  1. Indentation: Python uses indentation to define code blocks. Consistent use of 4 spaces per indentation level is the norm.

     if True:
         print("Hello, World!")
     >>Hello, World!
    
  2. Comments: Use # for single-line comments and triple quotes for multi-line comments.

     # This is a single-line comment
     """
     This is a
     multi-line comment
     """
    
  3. Statements: Python typically uses one statement per line.

     a = 1
     b = 2
     c = a + b
    

Data Types

Python supports various data types, including:

  1. Numeric Types:

    • int (e.g., 5)

    • float (e.g., 3.14)

    • complex (e.g., 1 + 2j)

  2. Sequence Types:

    • str (e.g., "Hello")

    • list (e.g., [1, 2, 3])

    • tuple (e.g., (1, 2, 3))

  3. Mapping Type:

    • dict (e.g., {"name": "Alice", "age": 25})
  4. Set Types:

    • set (e.g., {1, 2, 3})

    • frozenset (immutable set)

  5. Boolean Type:

    • bool (e.g., True, False)
  6. None Type:

    • None

Variables

Variables in Python are dynamically typed. You don't need to declare them before using them.

x = 10
y = 3.14
name = "Alice"

Loops

Python supports two main types of loops: for and while.

  1. For Loop:

     for i in range(5):
         print(i)
    
     >>0
     1
     2
     3
     4
     5
    
  2. While Loop:

     count = 0
     while count < 5:
         print(count)
         count += 1
     >>0
     1
     2
     3
     4
    
  3. Loop Control Statements:

    • break: Exits the loop

    • continue: Skips the current iteration and proceeds to the next

    • pass: Does nothing; a placeholder for future code

    for i in range(10):
        if i == 5:
            break
        print(i)
    >>0
    1
    2
    3
    4

Functions

Functions are defined using the def keyword. They can take parameters and return values.

  1. Defining Functions:

     def greet(name):
         return f"Hello, {name}!"
    
     print(greet("Alice"))
    
     >>Hello, Alice!
    
  2. Default Arguments:

     def greet(name="Guest"):
         return f"Hello, {name}!"
    
     print(greet())
     print(greet("Bob"))
    
     >>Hello, Guest!
     >>Hello, Bob!
    
  3. Variable-Length Arguments:

     def add(*args):
         return sum(args) #Sum is built-in function
    
     print(add(1, 2, 3))
     >>6
    
  4. Keyword Arguments:

     def display_info(**kwargs):
         for key, value in kwargs.items():
             print(f"{key}: {value}")
    
     display_info(name="Alice", age=25, city="New York")
    
     >>name: Alice
     age: 25
     city: New York
    
  5. Lambda Functions:

     add = lambda x, y: x + y
     print(add(2, 3))
    
     >>5
    

Key Points for Interviews

  • Understanding List Comprehensions:

      squares = [x**2 for x in range(10)]#list has[]
      print(squares)
      >>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    
  • Working with Dictionaries:

      student = {"name": "John", "age": 20}#Dictionary has {}
      print(student["name"])
      >>John
    
  • Handling Exceptions:

      try:
          result = 10 / 0
      except ZeroDivisionError:
          print("Cannot divide by zero!")
    
      >>Cannot divide by zero!
    
  • Understanding Python's Object-Oriented Programming:

      class Person:
          def __init__(self, name, age):
              self.name = name
              self.age = age
    
          def greet(self):
              return f"Hello, my name is {self.name}."
    
      alice = Person("Alice", 30)
      print(alice.greet())
    
  • File I/O Operations:

      with open('sample.txt', 'w') as file:
          file.write('Hello, world!')
    
      with open('sample.txt', 'r') as file:
          content = file.read()
          print(content)
    

Familiarizing yourself with these concepts and practicing coding problems can help you prepare effectively for Python-related interview questions.