LearningTech

📝

Python Basics

Foundational concepts and fundamental questions

1. What is the difference between a module and a package in Python?

Module


A module is a single Python file containing code, such as functions, classes, or variables.

Example: A file named math_utils.py is a module.


# math_utils.py def add(a, b): return a + b

Package


A package is a directory (folder) that contains multiple modules, plus a special file named __init__.py.

This setup tells Python that the folder is a package that can be imported.


Example structure:


utilities/

__init__.py math_utils.py string_utils.py

Simple difference

  • Module = single file.
  • Package = collection of modules organized in a directory.
2. Is Python a compiled or an interpreted language?

Python is both, in a friendly hybrid way.

  • Python source code (.py) is first compiled into bytecode (.pyc).
  • That bytecode is then interpreted by the Python Virtual Machine (PVM).

In essence, Python behaves like a storyteller who first converts your script into a universal script and then performs it line by line.

3. What are the benefits of using Python as a language/tool today?

Python remains a modern favourite for many reasons:


Benefits

1. Readable syntax

Code feels like conversation rather than cryptography.

2. Extensive libraries

Pandas, NumPy, Django, Flask, TensorFlow, PyTorch.

3. Cross-platform support

Write once, run almost anywhere.

4. Strong community support

A huge ecosystem of users and contributors.

5. Rapid development

Less boilerplate; faster prototyping.

6. Versatile

Used for web development, data science, AI, automation, DevOps, scripting.

4. What are global, protected, and private attributes in Python?

Python’s attribute protection system relies on naming conventions, not strict enforcement.


Global Attribute


A variable declared outside functions/classes, accessible everywhere.


x = 10 # global


Protected Attribute


Prefix with a single underscore _attribute.

Indicates: “Internal use; handle with care.”


class A: def __init__(self): self._count = 5

Private Attribute


Prefix with double underscore __attribute.

Python performs name-mangling to restrict direct access.


class A: def __init__(self): self.__secret = "locked"

Accessing it outside:


obj = A()

print(obj._A__secret) # name-mangled access

5. Is Python case sensitive?

Yes, Python treats Variable, variable, and VARIABLE as separate identifiers.

Case affects variables, functions, classes, and even module names.

6. What is Pandas?

Pandas is a powerful open-source data analysis and manipulation library.

It’s like a Swiss-army spreadsheet for Python.


Key features:

  • Fast data structures (Series, DataFrame)
  • Data cleaning, filtering, grouping
  • CSV/Excel/SQL import-export
  • Time-series handling

Example:


import pandas as pd

df = pd.read_csv('sales.csv')

print(df.head())

7. How is exception handling done in Python?

Python uses the try–except–else–finally blocks.


try:

value = 10 / 0

except ZeroDivisionError:

print("You split by zero, and the universe disagreed.")

else:

print("Runs if no exception occurs.")

finally:

print("Runs no matter what.")

Flow:

  • try: risky code
  • except: handle errors
  • else: executes when try succeeds
  • finally: always runs (cleanup, logging)
8. What is the difference between a for loop and a while loop in Python?

For Loop


Used when you know the number of iterations or are looping over a sequence.


for x in [1, 2, 3]:

print(x)

While Loop


Used when iteration depends on a condition.


n = 1

while n < 4:

print(n) n += 1

Essence:

  • for = iterate over items
  • while = iterate until a condition breaks
9. Is indentation required in Python? Why?

Yes, indentation is mandatory.


Python uses indentation to define code blocks instead of braces { }.

It enforces clarity and prevents chaotic code nesting.


Example:


if x > 5:

print("Large")

Without indentation, Python will raise IndentationError.

10. What is the use of self in Python?

self represents the instance of the class inside methods.


It lets methods access:

  • instance attributes
  • other methods
  • current object state

Example:


class Car: def __init__(self, model): self.model = model def show(self): print(self.model)

c = Car("Tesla")

c.show()


Here, self.model belongs to that particular car instance.

11. If you want, I can convert all answers into an interview-ready PDF/HTML, or create a concise one-page revision sheet.

Here comes a crisp, deeply explained set of answers, sprinkled with a bit of imaginative color without drifting away from clarity. Think of it as a neatly carved Python knowledge tablet, glowing softly like a well-behaved REPL prompt.

12. What is the difference between a module and a package in Python?

Module


A module is a single Python file containing code, such as functions, classes, or variables.

Example: A file named math_utils.py is a module.


# math_utils.py def add(a, b): return a + b

Package


A package is a directory (folder) that contains multiple modules, plus a special file named __init__.py.

This setup tells Python that the folder is a package that can be imported.


Example structure:


utilities/

__init__.py math_utils.py string_utils.py

Simple difference

  • Module = single file.
  • Package = collection of modules organized in a directory.
13. Is Python a compiled or an interpreted language?

Python is both, in a friendly hybrid way.

  • Python source code (.py) is first compiled into bytecode (.pyc).
  • That bytecode is then interpreted by the Python Virtual Machine (PVM).

In essence, Python behaves like a storyteller who first converts your script into a universal script and then performs it line by line.

14. What are the benefits of using Python as a language/tool today?

Python remains a modern favourite for many reasons:


Benefits

1. Readable syntax

Code feels like conversation rather than cryptography.

2. Extensive libraries

Pandas, NumPy, Django, Flask, TensorFlow, PyTorch.

3. Cross-platform support

Write once, run almost anywhere.

4. Strong community support

A huge ecosystem of users and contributors.

5. Rapid development

Less boilerplate; faster prototyping.

6. Versatile

Used for web development, data science, AI, automation, DevOps, scripting.

15. What are global, protected, and private attributes in Python?

Python’s attribute protection system relies on naming conventions, not strict enforcement.


Global Attribute


A variable declared outside functions/classes, accessible everywhere.


x = 10 # global


Protected Attribute


Prefix with a single underscore _attribute.

Indicates: “Internal use; handle with care.”


class A: def __init__(self): self._count = 5

Private Attribute


Prefix with double underscore __attribute.

Python performs name-mangling to restrict direct access.


class A: def __init__(self): self.__secret = "locked"

Accessing it outside:


obj = A()

print(obj._A__secret) # name-mangled access

16. Is Python case sensitive?

Yes, Python treats Variable, variable, and VARIABLE as separate identifiers.

Case affects variables, functions, classes, and even module names.

17. What is Pandas?

Pandas is a powerful open-source data analysis and manipulation library.

It’s like a Swiss-army spreadsheet for Python.


Key features:

  • Fast data structures (Series, DataFrame)
  • Data cleaning, filtering, grouping
  • CSV/Excel/SQL import-export
  • Time-series handling

Example:


import pandas as pd

df = pd.read_csv('sales.csv')

print(df.head())

18. How is exception handling done in Python?

Python uses the try–except–else–finally blocks.


try:

value = 10 / 0

except ZeroDivisionError:

print("You split by zero, and the universe disagreed.")

else:

print("Runs if no exception occurs.")

finally:

print("Runs no matter what.")

Flow:

  • try: risky code
  • except: handle errors
  • else: executes when try succeeds
  • finally: always runs (cleanup, logging)
19. What is the difference between a for loop and a while loop in Python?

For Loop


Used when you know the number of iterations or are looping over a sequence.


for x in [1, 2, 3]:

print(x)

While Loop


Used when iteration depends on a condition.


n = 1

while n < 4:

print(n) n += 1

Essence:

  • for = iterate over items
  • while = iterate until a condition breaks
20. Is indentation required in Python? Why?

Yes, indentation is mandatory.


Python uses indentation to define code blocks instead of braces { }.

It enforces clarity and prevents chaotic code nesting.


Example:


if x > 5:

print("Large")

Without indentation, Python will raise IndentationError.

21. What is the use of self in Python?

self represents the instance of the class inside methods.


It lets methods access:

  • instance attributes
  • other methods
  • current object state

Example:


class Car: def __init__(self, model): self.model = model def show(self): print(self.model)

c = Car("Tesla")

c.show()


Here, self.model belongs to that particular car instance.

22. If you want, I can convert all answers into an interview-ready PDF/HTML, or create a concise one-page revision sheet.

Here comes a full-powered, interview-ready set of answers, crafted with clarity and a light sparkle. Think of this as a Python knowledge atlas: structured, concise, and memorable.

23. How does Python manage memory? Explain reference counting and garbage collection.

Python uses a private heap for all objects and data structures. The Python Memory Manager handles allocation and deallocation automatically.


Reference Counting


Every object has a counter that tracks how many references point to it.


Example:


a = [1, 2, 3]

b = a # reference count increases


When the count drops to zero, Python frees the object immediately.


Garbage Collection


Python also has a cyclic garbage collector to clean up reference cycles (e.g., objects referencing each other).


Example:


import gc

gc.collect()


It detects unreachable cycles and clears them.

24. Does Python support multiple inheritance?

Yes, Python supports multiple inheritance.


class A: pass class B: pass class C(A, B): pass

Python resolves method conflicts using the MRO (Method Resolution Order), following the C3 linearization algorithm.

25. How is memory management done in Python?

Memory management relies on:

  • A private heap
  • The Python Memory Manager
  • Automatic garbage collection
  • Reference counting
  • Memory pools provided by pymalloc for faster allocations

Programmers don’t manually manage memory.