PYTHON PROGRAMMING OVERVIEW

Objectives: PYTHON PROGRAMMING OVERVIEW

Complete Python Programming Notes

Complete Python Programming Notes

1. History of Python

Python is a high-level, interpreted programming language created by Guido van Rossum in 1989 at Centrum Wiskunde & Informatica (CWI) in the Netherlands.

  • Named after the British comedy group Monty Python.
  • Designed to emphasize code readability and simplicity.
  • First released in 1991 as Python 0.9.0.
  • Python 2.x released in 2000, became very popular.
  • Python 3.0 released in 2008, introduced many improvements and is the current standard.
  • Python is open-source and maintained by the Python Software Foundation.
  • Widely used in web development, data science, automation, artificial intelligence, and more.

2. Installation and Setup

To start programming in Python, you need to install it on your computer.

  1. Download Python: Visit python.org/downloads and download the latest version.
  2. Install Python: Run the installer. Make sure to check "Add Python to PATH" during installation.
  3. Verify Installation: Open terminal or command prompt and type: python --version or python3 --version.
  4. Choose an IDE or Editor: You can write Python code in editors like VS Code, PyCharm, Sublime Text, or the built-in IDLE.
  5. Run Python Code: You can run Python scripts using the command line: python filename.py.

3. Python Basics

3.1 Hello World

print("Hello, World!")

3.2 Comments

Use # for single-line comments and triple quotes ''' ''' or """ """ for multi-line comments.

# This is a single-line comment
"""
This is a
multi-line comment
"""

3.3 Variables and Data Types

Variables do not require explicit declaration in Python. Types are inferred automatically.

x = 10          # Integer
name = "Alice"    # String
pi = 3.14159      # Float
is_valid = True   # Boolean

3.4 Basic Data Types

  • int: Integer numbers (e.g., 1, -10)
  • float: Floating point numbers (e.g., 3.14, -0.001)
  • str: Strings (e.g., "hello")
  • bool: Boolean values (True or False)
  • list: Ordered collection of items (e.g., [1, 2, 3])
  • tuple: Immutable ordered collection (e.g., (1, 2))
  • dict: Key-value pairs (e.g., {'name': 'Alice'})
  • set: Unordered collection of unique items (e.g., {1, 2, 3})

4. Input and Output

4.1 Output

print("Enter your name:")
print("Hello, Alice!")

4.2 Input

name = input("Enter your name: ")
print("Hello, " + name + "!")

Note: Input from input() is always a string.

5. Operators

  • Arithmetic Operators: +, -, *, /, %, // (floor division), ** (exponentiation)
  • Assignment Operators: =, +=, -=, *=, /=, etc.
  • Comparison Operators: ==, !=, >, <, >=, <=
  • Logical Operators: and, or, not
  • Membership Operators: in, not in
  • Identity Operators: is, is not
a = 10
b = 3
print(a + b)  # 13
print(a ** b) # 1000
print(a > b and b < 5) # True

6. Control Flow Statements

6.1 Conditional Statements

age = 18
if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

6.2 Loops

For Loop
for i in range(5):
    print(i)  # prints 0 to 4
While Loop
count = 0
while count < 5:
    print(count)
    count += 1

6.3 Loop Control Statements

  • break - Exit loop immediately
  • continue - Skip current iteration
  • pass - Do nothing, placeholder

7. Functions

7.1 Defining Functions

def greet(name):
    print("Hello, " + name + "!")

greet("Alice")  # Hello, Alice!

7.2 Return Statement

def add(a, b):
    return a + b

result = add(5, 3)  # result is 8

7.3 Function Arguments

  • Positional arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments: *args, **kwargs
def example(a, b=10, *args, **kwargs):
    print(a, b, args, kwargs)

example(1, 2, 3, 4, name="Alice", age=30)

8. Data Structures

8.1 Lists

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

8.2 Tuples

coordinates = (10, 20)
print(coordinates[1])  # 20

8.3 Dictionaries

person = {"name": "Alice", "age": 30}
print(person["name"])  # Alice
person["age"] = 31

8.4 Sets

numbers = {1, 2, 3, 2}
print(numbers)  # {1, 2, 3}

9. Modules and Packages

Modules are Python files with functions, classes, and variables. Packages are collections of modules organized in folders.

Importing Modules

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

from math import pi
print(pi)  # 3.141592653589793

Creating your own module

Create a file called mymodule.py:

def greet():
    print("Hello from mymodule!")

Then import it:

import mymodule
mymodule.greet()

10. Object-Oriented Programming (OOP)

10.1 Classes and Objects

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

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

p1 = Person("Alice", 30)
p1.greet()

10.2 Inheritance

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def study(self):
        print(f"{self.name} is studying.")

s1 = Student("Bob", 20, "S123")
s1.greet()
s1.study()

10.3 Encapsulation

Use underscore to indicate private variables:

class Car:
    def __init__(self, make):
        self._make = make  # convention for private variable

    def get_make(self):
        return self._make

10.4 Polymorphism

Different classes can have methods with the same name.

class Cat:
    def sound(self):
        print("Meow")

class Dog:
    def sound(self):
        print("Woof")

def animal_sound(animal):
    animal.sound()

cat = Cat()
dog = Dog()
animal_sound(cat)
animal_sound(dog)

11. Exception Handling

Exceptions are errors detected during execution. Handle them with try-except blocks.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print("Error:", e)
finally:
    print("Execution completed")

12. File Handling

12.1 Reading a File

with open("file.txt", "r") as file:
    content = file.read()
    print(content)

12.2 Writing to a File

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

12.3 Appending to a File

with open("file.txt", "a") as file:
    file.write("\nThis is a new line.")

13. Popular Python Libraries and Frameworks

  • NumPy: Numerical computing with arrays.
  • Pandas: Data manipulation and analysis.
  • Matplotlib: Plotting and visualization.
  • Scikit-learn: Machine learning.
  • Django: Full-stack web framework.
  • Flask: Lightweight web framework.
  • TensorFlow & PyTorch: Deep learning libraries.
  • Requests: HTTP library for API calls.
  • Beautiful Soup: Web scraping.

14. Practical Examples

14.1 Fibonacci Sequence

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

fibonacci(10)  # 0 1 1 2 3 5 8 13 21 34

14.2 Factorial Using Recursion

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120

14.3 Check Prime Number

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

print(is_prime(17))  # True
print(is_prime(18))  # False

15. How to Run Python Code

There are many ways to run Python code:

  • Using the command line: python filename.py
  • Using interactive shell (REPL): just type python in terminal
  • Using IDEs like VS Code, PyCharm, or IDLE
  • Using online platforms such as Replit, Programiz, or Trinket

16. Summary and Tips for Learning Python

  • Practice regularly by writing small programs.
  • Understand the basics well before moving to advanced topics.
  • Read official documentation at docs.python.org.
  • Explore projects like web apps, data analysis, or automation.
  • Join Python communities and forums for support.
  • Use Python's built-in help() and dir() functions to explore.
  • Debug and test your code thoroughly.
© 2025 Python Programming Notes. Created for learning and reference.
Python Exam Questions & Answers

Python Programming Questions and Answers

1. History of Python

Q1: Who created Python and when?

Answer: Python was created by Guido van Rossum in 1989 at CWI in the Netherlands.

Q2: What are the key features of Python?

Answer:

  • High-level and interpreted language.
  • Emphasizes readability with clean syntax.
  • Supports multiple programming paradigms: procedural, OOP, functional.
  • Dynamic typing and automatic memory management.
  • Large standard library and extensive third-party modules.
  • Open-source and cross-platform.

2. Python Basics

Q3: How do you print "Hello, World!" in Python?

Answer: Use the print() function:

print("Hello, World!")
Q4: How do you write comments in Python?

Answer:

  • Single-line comment: starts with #.
  • Multi-line comment: use triple quotes ''' ... ''' or """ ... """.
# This is a single-line comment

"""
This is a
multi-line comment
"""
Q5: What are variables and how do you assign values?

Answer: Variables store data and are assigned using the equals sign =. Python infers the type automatically.

x = 10           # integer
name = "Alice"    # string
pi = 3.14159       # float
is_valid = True    # boolean

3. Data Types and Operators

Q6: List main Python data types.

Answer:

  • int - integers (e.g., 5, -10)
  • float - floating-point numbers (e.g., 3.14)
  • str - strings (e.g., "Hello")
  • bool - boolean (True/False)
  • list - ordered, mutable collections (e.g., [1,2,3])
  • tuple - ordered, immutable collections (e.g., (1,2))
  • dict - key-value pairs (e.g., {"name": "Alice"})
  • set - unordered collections of unique elements (e.g., {1,2,3})
Q7: What is the difference between mutable and immutable types? Give examples.

Answer:

  • Mutable: Objects that can be changed after creation (e.g., lists, dicts, sets).
  • Immutable: Objects that cannot be changed after creation (e.g., int, float, str, tuple).
Q8: Show examples of arithmetic operators in Python.
a = 10
b = 3
print(a + b)   # 13
print(a - b)   # 7
print(a * b)   # 30
print(a / b)   # 3.3333...
print(a // b)  # 3 (floor division)
print(a % b)   # 1 (modulus)
print(a ** b)  # 1000 (exponentiation)

4. Control Flow

Q9: Write an if-else statement to check if a number is positive, negative, or zero.
num = int(input("Enter a number: "))

if num > 0:
    print("Positive")
elif num == 0:
    print("Zero")
else:
    print("Negative")
Q10: Write a for loop that prints numbers from 1 to 5.
for i in range(1, 6):
    print(i)
Q11: Explain the use of break and continue in loops.

Answer:

  • break - exits the loop immediately.
  • continue - skips the rest of the current iteration and moves to the next.
for i in range(5):
    if i == 3:
        break   # stops loop when i == 3
    print(i)

for i in range(5):
    if i == 3:
        continue  # skip printing 3
    print(i)

5. Functions

Q12: How do you define a function in Python?
def greet(name):
    print("Hello, " + name + "!")

greet("Alice")  # Output: Hello, Alice!
Q13: What are default arguments? Give an example.
def greet(name="Guest"):
    print("Hello, " + name + "!")

greet()         # Hello, Guest!
greet("Alice")  # Hello, Alice!
Q14: Explain *args and **kwargs with examples.
def example(*args, **kwargs):
    print("Positional args:", args)
    print("Keyword args:", kwargs)

example(1, 2, 3, name="Alice", age=30)

Output:

Positional args: (1, 2, 3)
Keyword args: {'name': 'Alice', 'age': 30}

6. Data Structures

Q15: How do you add and remove items from a list?
fruits = ["apple", "banana"]
fruits.append("cherry")  # Add at end
print(fruits)  # ['apple', 'banana', 'cherry']

fruits.remove("banana")
print(fruits)  # ['apple', 'cherry']
Q16: What is a dictionary and how do you access its elements?
person = {"name": "Alice", "age": 30}
print(person["name"])  # Alice
person["age"] = 31    # update value

7. Object-Oriented Programming (OOP)

Q17: Define a simple class with a constructor and method.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hi, I'm {self.name} and I'm {self.age} years old.")

p = Person("Alice", 30)
p.greet()
Q18: What is inheritance? Show an example.
class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def study(self):
        print(f"{self.name} is studying.")

s = Student("Bob", 20, "S123")
s.greet()
s.study()

8. Exception Handling

Q19: How do you handle exceptions in Python?
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print("Error:", e)
finally:
    print("Execution finished")

9. File Handling

Q20: Write code to read from and write to a file.
# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

10. Advanced Topics

Q21: What are lambda functions? Provide an example.
square = lambda x: x * x
print(square(5))  # 25
Q22: Explain list comprehensions with an example.
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)  # [1, 4, 9, 16, 25]
Q23: What is a generator? Write a simple generator function.
def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

for num in count_up_to(5):
    print(num)

11. Popular Libraries and Frameworks

Q24: Name some popular Python libraries for data science.

Answer: NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, PyTorch.

Q25: What is Flask used for?

Answer: Flask is a lightweight web framework for building web applications in Python.

12. Practical Coding Examples

Q26: Write a Python function to check if a string is a palindrome.
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

print(is_palindrome("Racecar"))  # True
print(is_palindrome("Python"))   # False
Q27: Write a program to find the factorial of a number using recursion.
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120
Q28: Write a Python program to find the largest number in a list.
numbers = [10, 34, 2, 99, 4]
largest = numbers[0]
for num in numbers:
    if num > largest:
        largest = num
print("Largest number is", largest)
© 2025 Python Q&A Notes - Created for Exam Preparation

13. More Practical Coding Examples (Q29 - Q60)

Q29: Write a Python program to merge two dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Using the update() method
dict1.update(dict2)
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}

# Using dictionary unpacking (Python 3.5+)
merged = {**dict1, **dict2}
print(merged)
# Output: {'a': 1, 'b': 3, 'c': 4}
Q30: Write a Python program to count the frequency of each word in a text.
text = "apple banana apple strawberry banana apple"
words = text.split()
freq = {}

for word in words:
    freq[word] = freq.get(word, 0) + 1

print(freq)
# Output: {'apple': 3, 'banana': 2, 'strawberry': 1}
Q31: Write a function to compute the nth Fibonacci number.
def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(7))  # Output: 13
Q32: Implement a simple calculator using functions.
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error! Division by zero."
    return x / y

print(add(5, 3))       # 8
print(subtract(10, 4)) # 6
print(multiply(2, 3))  # 6
print(divide(10, 0))   # Error! Division by zero.
Q33: Write a Python program to read a CSV file and print its contents.
import csv

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

Note: 'data.csv' should be a valid CSV file in the working directory.

Q34: Write a Python class to represent a bank account with deposit and withdrawal methods.
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"Deposited ${amount}. New balance is ${self.balance}.")

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds!")
        else:
            self.balance -= amount
            print(f"Withdrew ${amount}. New balance is ${self.balance}.")

account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
account.withdraw(1500)
Q35: Write a program to catch division by zero errors gracefully.
try:
    a = 10
    b = 0
    result = a / b
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
else:
    print("Result:", result)
Q36: What is the difference between == and is operators?

Answer:

  • == checks if the values of two variables are equal.
  • is checks if two variables point to the same object in memory.
a = [1, 2, 3]
b = a
c = list(a)

print(a == c)  # True (values are equal)
print(a is c)  # False (different objects)
print(a is b)  # True (same object)
Q37: Explain list slicing with examples.
my_list = [0, 1, 2, 3, 4, 5, 6]

print(my_list[1:5])   # [1, 2, 3, 4]
print(my_list[:3])    # [0, 1, 2]
print(my_list[4:])    # [4, 5, 6]
print(my_list[::2])   # [0, 2, 4, 6] (every second element)
print(my_list[::-1])  # [6, 5, 4, 3, 2, 1, 0] (reversed list)
Q38: What is a generator? Write a simple example.
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for i in countdown(5):
    print(i)
# Output: 5 4 3 2 1
Q39: Explain the difference between shallow copy and deep copy.

Answer:

  • Shallow copy: copies the object but references nested objects.
  • Deep copy: copies the object and recursively copies nested objects.
import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0][0] = 99
print(shallow)  # [[99, 2], [3, 4]] (affected)
print(deep)     # [[1, 2], [3, 4]] (unaffected)
Q40: How do you create and activate a virtual environment in Python?

Answer:

# Create a virtual environment named 'venv'
python -m venv venv

# Activate (Windows)
venv\Scripts\activate

# Activate (Unix/Mac)
source venv/bin/activate

Virtual environments help manage dependencies and isolate projects.

Q41: What are *args and **kwargs? Give an example usage.
def func(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

func(1, 2, 3, name="Alice", age=30)
# args: (1, 2, 3)
# kwargs: {'name': 'Alice', 'age': 30}
Q42: What is duck typing in Python?

Answer: Duck typing means an object's suitability is determined by the presence of methods and properties, not by its type. If it walks like a duck and quacks like a duck, it is treated as a duck.

def quack(duck):
    duck.quack()

class Duck:
    def quack(self):
        print("Quack!")

class Person:
    def quack(self):
        print("I'm pretending to quack!")

quack(Duck())   # Quack!
quack(Person()) # I'm pretending to quack!
Q43: Explain Python’s memory management and garbage collection.

Answer:

  • Python uses reference counting to keep track of objects.
  • When an object’s reference count hits zero, it is deleted.
  • Garbage collector handles cyclic references that reference counting misses.
  • Python’s gc module can be used to interact with the garbage collector.
Q44: What are decorators in Python? Provide a simple example.
def decorator(func):
    def wrapper():
        print("Before the function runs.")
        func()
        print("After the function runs.")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()
# Output:
# Before the function runs.
# Hello!
# After the function runs.
Q45: Explain map(), filter(), and reduce() functions with examples.
numbers = [1, 2, 3, 4, 5]

# map() - apply function to all items
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# filter() - filter items based on condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

# reduce() - apply function cumulatively
from functools import reduce
sum_all = reduce(lambda a, b: a + b, numbers)
print(sum_all)  # 15
Q46: What is the purpose of the with statement in file handling?

Answer: The with statement ensures that resources are properly managed. For files, it automatically closes the file after the block executes, even if exceptions occur.

with open("file.txt", "r") as f:
    data = f.read()
# file is automatically closed here
Q47: What is multithreading and multiprocessing? When to use each?

Answer:

  • Multithreading: Multiple threads within the same process share memory. Useful for I/O-bound tasks.
  • Multiprocessing: Multiple processes with separate memory spaces. Useful for CPU-bound tasks.
Q48: Explain the difference between a module and a package.

Answer:

  • Module: A single Python `.py` file containing code.
  • Package: A directory containing multiple modules and an `__init__.py` file.
Q49: How can you handle missing keys in a dictionary?
my_dict = {'a': 1}

# Using get() with default
value = my_dict.get('b', 0)
print(value)  # 0

# Using defaultdict from collections
from collections import defaultdict
dd = defaultdict(int)
print(dd['missing'])  # 0
Q50: How do you debug Python code?

Answer: Use print statements, Python's built-in pdb debugger, or IDE debuggers to step through code and inspect variables.

import pdb

def buggy_func(x):
    pdb.set_trace()  # program pauses here
    return x / 0  # will cause error

buggy_func(10)
Q51: Explain what is PEP 8.

Answer: PEP 8 is the official Python style guide that defines best practices for writing readable Python code, including naming conventions, indentation, spacing, and more.

Q52: Write a Python program to find all prime numbers between 1 and 100.
for num in range(2, 101):
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num, end=" ")
Q53: How do you create a Python package?

Answer: Create a directory with an __init__.py file (can be empty). Put modules (.py files) inside the directory. Import using the package name.

Q54: What is the Global Interpreter Lock (GIL) in Python?

Answer: The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes at once. It simplifies memory management but limits true multi-threading in CPU-bound programs.

Q55: How do you document Python functions?
def add(a, b):
    """Add two numbers and return the result.

    Args:
        a (int): First number.
        b (int): Second number.

    Returns:
        int: Sum of a and b.
    """
    return a + b
Q56: What are Python's special (dunder) methods? Give examples.

Answer: Special methods begin and end with double underscores and allow customization of class behavior.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

v = Vector(1, 2)
print(v)  # Output: Vector(1, 2)
Q57: How do you use list comprehensions with conditions?
numbers = [1, 2, 3, 4, 5, 6]
evens = [x for x in numbers if x % 2 == 0]
print(evens)  # [2, 4, 6]
Q58: What are Python’s built-in functions to inspect objects?

Answer: type(), dir(), help(), isinstance(), id().

Q59: How do you handle command-line arguments in Python?
import sys

print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
Q60: What is the difference between Python lists and arrays?

Answer:

  • Lists are built-in Python data structures that can hold heterogeneous data types.
  • Arrays (from array module) hold homogeneous data types and are more memory efficient.

13. Advanced Topics Continued

Q61: What are Python decorators and how do they work? Provide an example.

Answer: Decorators are functions that modify the behavior of other functions or methods without changing their code.

def decorator_func(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator_func
def say_hello():
    print("Hello!")

say_hello()

# Output:
# Before function call
# Hello!
# After function call
Q62: What is the use of the with statement and context managers?

Answer: The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks, like opening and closing files automatically.

with open('file.txt', 'r') as f:
    content = f.read()
# file is automatically closed here
Q63: What are comprehensions in Python? Give examples of list, dict, and set comprehensions.
# List comprehension
squares = [x**2 for x in range(5)]  # [0,1,4,9,16]

# Dictionary comprehension
square_dict = {x: x**2 for x in range(5)}  # {0:0,1:1,2:4,3:9,4:16}

# Set comprehension
square_set = {x**2 for x in range(5)}  # {0,1,4,9,16}
Q64: Explain multithreading and multiprocessing in Python. When would you use each?

Answer:

  • Multithreading: Runs multiple threads in the same process to handle I/O-bound tasks concurrently. Limited by the GIL for CPU-bound tasks.
  • Multiprocessing: Runs separate processes for CPU-bound tasks, bypassing GIL for true parallelism.

14. Libraries & Frameworks Continued

Q65: How do you install external Python packages?

Answer: Use pip package manager:

pip install package_name
Q66: What is a virtual environment and why is it important?

Answer: A virtual environment isolates project dependencies so that each project can have its own package versions, avoiding conflicts.

# Create virtual env
python -m venv env

# Activate (Windows)
env\Scripts\activate

# Activate (Linux/Mac)
source env/bin/activate

15. Best Practices and Conceptual Questions

Q67: What does it mean to write Pythonic code?

Answer: Writing Pythonic code means following Python's idioms and best practices for clear, concise, readable, and efficient code.

Q68: What is PEP 8?

Answer: PEP 8 is the official Python style guide that recommends coding standards to improve code readability.

Q69: How can you improve code performance in Python?

Answer: Use efficient data structures, built-in functions, avoid unnecessary loops, use generators, and optimize algorithms.

Q70: Explain common debugging techniques in Python.

Answer: Use print statements, Python debugger (pdb), IDE debuggers, logging module, and unit testing.

Q71: What are docstrings and how do you write them?

Answer: Docstrings are string literals used to document modules, classes, and functions. They use triple quotes immediately after the definition.

def add(a, b):
    """Return the sum of a and b."""
    return a + b

16. Practical Advanced Coding Examples

Q72: Write a generator that yields even numbers up to n.
def even_numbers(n):
    for i in range(0, n+1, 2):
        yield i

for num in even_numbers(10):
    print(num)
Q73: Write a decorator that logs function calls.
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args {args} kwargs {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_calls
def add(a, b):
    return a + b

add(5, 7)
Q74: Write a Python program to flatten a nested list.
def flatten(lst):
    flat_list = []
    for item in lst:
        if isinstance(item, list):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

print(flatten([1, [2, [3, 4], 5], 6]))  # [1,2,3,4,5,6]
Q75: Explain list slicing with examples.
lst = [0,1,2,3,4,5]

print(lst[1:4])    # [1, 2, 3]
print(lst[:3])     # [0, 1, 2]
print(lst[3:])     # [3, 4, 5]
print(lst[-3:-1])  # [3, 4]
print(lst[::2])    # [0, 2, 4]

17. Conceptual & Miscellaneous

Q76: What is duck typing?

Answer: Duck typing is a dynamic typing philosophy in Python where the object's suitability is determined by the presence of certain methods and properties, not the object's actual type.

Q77: What is the difference between a module and a package?

Answer: A module is a single Python file containing code. A package is a collection of modules organized in directories with an __init__.py file.

Q78: How does Python's garbage collector work?

Answer: Python uses reference counting and a cyclic garbage collector to free memory occupied by objects that are no longer in use.

Q79: What are dunder (double underscore) methods? Give examples.

Answer: Dunder methods are special methods with double underscores that provide operator overloading and object behavior customization, e.g., __init__, __str__, __repr__.

Q80: What is the difference between shallow copy and deep copy?
import copy

lst1 = [[1,2], [3,4]]
shallow = copy.copy(lst1)
deep = copy.deepcopy(lst1)

lst1[0][0] = 9
print(shallow)  # [[9,2], [3,4]]  # affected by change
print(deep)     # [[1,2], [3,4]]  # not affected

18. Final Questions (Q81 - Q95)

Q81: Why is Python called an interpreted language?

Answer: Because Python code is executed line-by-line by an interpreter without prior compilation to machine code.

Q82: What does it mean that Python is dynamically typed?

Answer: Variable types are determined at runtime, and you don’t need to declare them explicitly.

Q83: How does Python manage memory?

Answer: Python manages memory automatically via reference counting and garbage collection.

Q84: What is the difference between list.append() and list.extend()?
lst = [1,2]
lst.append([3,4])  # [1,2,[3,4]]
lst.extend([5,6])  # [1,2,[3,4],5,6]
Q85: How do you create a virtual environment?
python -m venv env
source env/bin/activate  # Linux/Mac
env\Scripts\activate     # Windows
Q86: How do you debug Python code?

Answer: Using print statements, Python’s pdb debugger, IDE tools, or logging module.

Q87: What is the Global Interpreter Lock (GIL)?

Answer: A mutex that allows only one thread to execute Python bytecode at a time, limiting true multithreading in CPU-bound tasks.

Q88: What is the difference between == and is?

Answer: == checks value equality, is checks object identity (if two variables point to the same object).

Q89: Explain how to handle missing keys in a dictionary.
my_dict = {'a':1}
print(my_dict.get('b', 'Not found'))  # returns 'Not found' instead of error
Q90: What is recursion? Give an example.
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n-1)

print(factorial(5))  # 120
Q91: What is the difference between a module and a package?

Answer: A module is a single Python file (.py), while a package is a directory with __init__.py containing multiple modules.

Q92: How do you document a Python function?
def add(a, b):
    """Add two numbers and return the result."""
    return a + b
Q93: Write a Python program to read user input until 'exit' is typed.
while True:
    data = input("Enter data (type 'exit' to quit): ")
    if data.lower() == 'exit':
        break
    print("You entered:", data)
Q94: Explain list slicing with step.
lst = [0,1,2,3,4,5,6,7,8,9]
print(lst[1:8:2])  # [1, 3, 5, 7]
Q95: What is a Python generator and why use it?

Answer: Generators produce items one at a time and only when needed, saving memory compared to returning a full list.

19. Bonus Questions (Q96 - Q120)

Q96: What are Python’s built-in data structures and their time complexities?

Answer:

  • List: O(1) for append/pop at end, O(n) for search or insert/remove in middle.
  • Dict: Average O(1) for lookup, insert, delete (hash table).
  • Set: Similar to dict, average O(1) for add, remove, contains.
  • Tuple: Immutable list, O(1) access.
Q97: Explain Python’s argument passing mechanism.

Answer: Python uses call by object reference (also called call by assignment). Mutable objects can be changed inside a function; immutable objects cannot.

Q98: What is the difference between staticmethod and classmethod?
class MyClass:
    @staticmethod
    def static_method():
        print("Static method called")

    @classmethod
    def class_method(cls):
        print(f"Class method called for {cls}")

MyClass.static_method()  # No cls or self
MyClass.class_method()   # Receives cls as class reference
Q99: How do you handle exceptions with else and finally?
try:
    print("Try block")
except Exception:
    print("Except block")
else:
    print("Else block (if no exception)")
finally:
    print("Finally block (always executes)")
Q100: How do you merge two dictionaries?
# Python 3.9+
dict1 = {'a': 1}
dict2 = {'b': 2}
merged = dict1 | dict2
print(merged)  # {'a': 1, 'b': 2}

# Before 3.9
merged = {**dict1, **dict2}
Q101: What is a namedtuple?

Answer: An immutable, lightweight object type from the collections module with named fields for better readability.

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)  # 1 2
Q102: What is monkey patching in Python?

Answer: Dynamically changing or extending a class or module at runtime without modifying the original source code.

Q103: Explain the difference between shallow and deep copy with an example.
import copy
lst = [[1,2], [3,4]]

shallow_copy = copy.copy(lst)
deep_copy = copy.deepcopy(lst)

lst[0][0] = 99

print(shallow_copy)  # [[99, 2], [3, 4]]
print(deep_copy)     # [[1, 2], [3, 4]]
Q104: What is the difference between filter(), map(), and reduce()?

Answer:

  • filter(): Filters items based on a function returning True or False.
  • map(): Applies a function to all items in an iterable.
  • reduce(): Repeatedly applies a function to items to reduce them to a single value (from functools).
Q105: How can you implement a singleton pattern in Python?
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)  # True
Q106: How do you sort a list of dictionaries by a key?
people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)
Q107: What is a Python iterator and iterable?

Answer: An iterable is an object you can loop over (e.g., list, tuple). An iterator is an object with a __next__() method that returns items one by one.

Q108: How to create a custom iterator?
class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

for c in Counter(1, 3):
    print(c)
Q109: Explain the difference between a generator and a list.

Answer: Generators yield items on demand and use less memory. Lists hold all items in memory.

Q110: How can you handle command-line arguments in Python?
import sys

print("Arguments:", sys.argv)  # List of command-line arguments

# Or use argparse for advanced parsing
Q111: What are Python’s built-in functions for type conversion?

Answer: int(), float(), str(), bool(), list(), tuple(), dict(), set().

Q112: What is list unpacking? Provide an example.
a, b, *rest = [1, 2, 3, 4, 5]
print(a)    # 1
print(b)    # 2
print(rest) # [3, 4, 5]
Q113: How do you reverse a string in Python?
s = "Hello"
print(s[::-1])  # "olleH"
Q114: What are f-strings? Show an example.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Q115: How do you check if a key exists in a dictionary?
my_dict = {'a': 1, 'b': 2}
if 'a' in my_dict:
    print("Key exists")
Q116: What is the difference between isinstance() and type()?

Answer: isinstance() checks inheritance too, type() checks exact type.

Q117: How can you measure execution time of a code snippet?
import time

start = time.time()
# code block
end = time.time()
print("Execution time:", end - start, "seconds")
Q118: Explain the difference between a list and a tuple.

Answer: Lists are mutable; tuples are immutable. Tuples can be used as dictionary keys.

Q119: What is the purpose of the pass statement?

Answer: pass is a null statement used as a placeholder when syntax requires a statement but no action is needed.

Q120: How do you raise an exception in Python?
raise ValueError("Invalid input")

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1.2::