Skip to main content

Command Palette

Search for a command to run...

Learning Update: Python Recursion & Docstrings

Updated
•1 min read•View as Markdown

Today, I learned about docstrings and recursion in Python.

I understood how docstrings are used to explain what a function does and how they improve code readability using tools like help().

I also practiced a few basic recursion problems, such as:

  • Printing numbers (1 to N and N to 1)

  •   def print_1_to_n(n):
    
          if n == 0:   # Base Case.
              return
          print_1_to_n(n - 1)   # Recursive Case
          print(n)
    
  •   def print_n_to_1(n):
    
          if n == 0:   # Base Case
              return
    
          print(n)  # Since this comes before the recursive call, numbers print in reverse order
          print_n_to_1(n-1)   # Recursive Case
    
  • Finding the sum of first N natural numbers

def sum_of_natural_numbers(n):
    if n == 0:
        return 0    else:
        sum = n + sum_of_natural_numbers(n-1)
  • Calculating factorial using recursion

  •   def fact_rec(num):
          if num == 1:
              return 1
          else:
              factorial = num * fact_rec(num - 1)
              return factorial
    

These exercises helped me understand the importance of base cases and how a function calls itself to solve a problem step by step.

📌 Key takeaway: Recursion can feel confusing at first, but practicing simple problems makes it much easier to understand.

Looking forward to learning more and improving my Python fundamentals.

Suggest what should I learn next.