100 Python Questions and Answers

Basic Python Questions

  1. What is Python?
    Python is an interpreted, high-level, dynamically typed, and garbage-collected programming language.

  2. What are Python’s key features?

    • Easy to learn and use
    • Interpreted and dynamically typed
    • Object-oriented
    • Extensive standard library
  3. How do you write "Hello, World!" in Python?

    print("Hello, World!")
  4. How do you check the Python version?

    import sys print(sys.version)
  5. How do you take user input in Python?

    name = input("Enter your name: ") print("Hello, " + name)
  6. How do you comment in Python?

    • Single-line comment: # This is a comment
    • Multi-line comment:
      """This is a multi-line comment"""
  7. What are Python’s data types?

    • Numeric (int, float, complex)
    • Sequence (list, tuple, range)
    • Text (str)
    • Set (set, frozenset)
    • Mapping (dict)
    • Boolean (bool)
  8. What is the difference between is and == in Python?

    • == checks for value equality.
    • is checks for reference (memory) equality.
  9. How do you declare a variable in Python?

    x = 10 y = "Python"
  10. What is dynamic typing?
    Python does not require explicit variable declarations; the type is assigned dynamically.

Control Flow & Loops

  1. What are conditional statements in Python?

    if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero")
  2. How do you write a for loop?

    for i in range(5): print(i)
  3. How do you write a while loop?

    x = 0 while x < 5: print(x) x += 1
  4. What is the difference between break and continue?

    • break exits the loop.
    • continue skips the current iteration.
  5. How do you use a pass statement?

    for i in range(5): pass # Placeholder for future code

Functions & Scope

  1. How do you define a function in Python?

    def greet(): print("Hello!")
  2. What are function arguments in Python?

    def add(a, b): return a + b
  3. What is the difference between positional and keyword arguments?

    • Positional: add(2, 3)
    • Keyword: add(a=2, b=3)
  4. What is a default argument in Python?

    def greet(name="Guest"): print("Hello, " + name)
  5. What is variable scope in Python?

    • Local: Defined inside a function.
    • Global: Defined outside any function.

Data Structures

  1. What is a list?

    my_list = [1, 2, 3, 4, 5]
  2. How do you access list elements?

    print(my_list[0]) # First element
  3. How do you slice a list?

    print(my_list[1:4]) # [2, 3, 4]
  4. What is a tuple?

    my_tuple = (1, 2, 3)
  5. How do you create a dictionary?

    my_dict = {"name": "Alice", "age": 25}

OOP in Python

  1. How do you define a class in Python?

    class Person: def __init__(self, name): self.name = name
  2. What is an object?

    p = Person("Alice")
  3. What is inheritance in Python?

    class Employee(Person): pass
  4. What is polymorphism?
    Different classes implementing the same method.

  5. What is encapsulation?
    Hiding the internal state of an object.

File Handling

  1. How do you open a file in Python?

    f = open("file.txt", "r")
  2. How do you read a file?

    content = f.read()
  3. How do you write to a file?

    with open("file.txt", "w") as f: f.write("Hello, World!")
  4. How do you close a file?

    f.close()

Error Handling

  1. How do you handle exceptions in Python?

    try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero")
  2. What is finally in exception handling?

    try: x = 1 / 0 except: print("Error") finally: print("This always runs")
  3. How do you raise an exception?

    raise ValueError("Invalid value")

Advanced Python

  1. What are lambda functions?

    add = lambda x, y: x + y
  2. What is a list comprehension?

    squares = [x**2 for x in range(10)]
  3. What is a generator?

    def my_gen(): yield 1 yield 2
  4. What is multithreading?
    Running multiple threads in parallel.

  5. How do you install an external package?

    pip install requests
  6. What is a virtual environment in Python?
    It isolates dependencies for projects.

  7. What is the map function?

    list(map(str, [1, 2, 3]))
  8. What is filter in Python?

    list(filter(lambda x: x % 2 == 0, range(10)))
  9. What is reduce?

    from functools import reduce reduce(lambda x, y: x + y, [1, 2, 3, 4])

Intermediate Python Concepts

  1. What are Python’s built-in data types?

    • int, float, complex, str, list, tuple, dict, set, bool, NoneType.
  2. What is the difference between a list and a tuple?

    • Lists are mutable, whereas tuples are immutable.
  3. How do you reverse a list in Python?

    my_list.reverse() # or reversed_list = my_list[::-1]
  4. How do you sort a list in Python?

    my_list.sort() # Sorts in place sorted_list = sorted(my_list) # Returns a new sorted list
  5. How do you merge two dictionaries?

    dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {**dict1, **dict2}
  6. How do you remove duplicates from a list?

    my_list = list(set(my_list))
  7. What is the difference between remove() and pop() in lists?

    • remove(value): Removes the first occurrence of the specified value.
    • pop(index): Removes the element at the given index.
  8. What is the zip() function used for?

    a = [1, 2, 3] b = ['x', 'y', 'z'] zipped = list(zip(a, b)) # [(1, 'x'), (2, 'y'), (3, 'z')]
  9. How do you check if a key exists in a dictionary?

    if "key" in my_dict: print("Exists")
  10. What is the difference between del and clear() in dictionaries?

    • del my_dict['key']: Removes a specific key-value pair.
    • my_dict.clear(): Removes all key-value pairs.
  11. How do you iterate over a dictionary?

    for key, value in my_dict.items(): print(key, value)

String Manipulation

  1. How do you split a string?

    text = "apple,banana,cherry" fruits = text.split(",") # ['apple', 'banana', 'cherry']
  2. How do you join a list of strings?

    joined = ", ".join(fruits) # "apple, banana, cherry"
  3. How do you check if a string contains a substring?

    if "apple" in text: print("Found")
  4. How do you replace a substring in Python?

    text = text.replace("apple", "orange")
  5. What is string formatting in Python?

    name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.")

Advanced Python Concepts

  1. What are Python decorators?

    • Decorators are functions that modify the behavior of other functions.
    def decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @decorator def say_hello(): print("Hello!") say_hello()
  2. What is the difference between deepcopy() and copy()?

    • copy.copy(): Creates a shallow copy (nested objects are referenced).
    • copy.deepcopy(): Creates a deep copy (nested objects are also copied).
  3. What is the purpose of __init__.py?

    • It marks a directory as a Python package.
  4. What is monkey patching in Python?

    • Dynamically modifying a class or module at runtime.
  5. What is the purpose of the super() function?

    • It calls the parent class’s method inside a subclass.
  6. How do you define an abstract class?

    from abc import ABC, abstractmethod class AbstractClass(ABC): @abstractmethod def abstract_method(self): pass
  7. What is method overloading in Python?

    • Python does not support method overloading directly; instead, default arguments can be used.
  8. What is method overriding?

    • A subclass provides a new implementation of a method inherited from its parent class.
  9. What are metaclasses in Python?

    • Metaclasses define how classes behave.

Python Libraries & Modules

  1. How do you import a module in Python?

    import math
  2. How do you list all installed modules?

    help("modules")
  3. What is sys.argv in Python?

    • It contains command-line arguments passed to a script.
  4. How do you measure execution time in Python?


    import time start = time.time() # Code execution end = time.time() print(f"Time taken: {end - start}")
  5. What is os module used for?

    • To interact with the operating system.
  6. How do you get the current working directory?


    import os print(os.getcwd())
  7. How do you rename a file in Python?


    os.rename("old.txt", "new.txt")
  8. What is the random module used for?


    import random print(random.randint(1, 10))
  9. How do you generate a random float number?


    print(random.uniform(1.0, 10.0))
  10. What is NumPy used for?

    • It is used for numerical computations.
  11. How do you create a NumPy array?


    import numpy as np arr = np.array([1, 2, 3])
  12. What is Pandas used for?

    • Data analysis and manipulation.
  13. How do you read a CSV file using Pandas?

    import pandas as pd df = pd.read_csv("file.csv")

Python Best Practices

  1. What is PEP 8?

    • Python Enhancement Proposal 8 (PEP 8) is a style guide for writing readable code.
  2. What is the Zen of Python?

    import this
  3. Why should you use with when opening files?

    • It automatically closes the file.
  4. What is the purpose of __name__ == "__main__"?

    • It ensures the script runs only when executed directly.
  5. What is duck typing in Python?

    • The type of an object is determined by its behavior.
  6. What is the walrus operator (:=)?

    if (n := len(my_list)) > 5: print(f"List is too long: {n}")
  7. What is the difference between isinstance() and type()?

    • isinstance() considers inheritance, type() does not.
  8. What is a frozen set?

    my_set = frozenset([1, 2, 3])
  9. What are Python f-strings?

    name = "Alice" print(f"Hello, {name}")
  10. How do you handle multiple exceptions?

    try: pass except (TypeError, ValueError) as e: print(e)
  11. What is the collections module used for?

    • It provides specialized data structures like Counter, deque, etc.
  12. What is a namedtuple?

    python
    from collections import namedtuple Point = namedtuple("Point", "x y") p = Point(1, 2)

Would you like more questions on a specific topic? 🚀


  1. What is a lambda function in Python?
  • A lambda function is an anonymous function defined using the lambda keyword.
add = lambda x, y: x + y print(add(2, 3)) # Output: 5
  1. What is the difference between map(), filter(), and reduce()?
  • map(): Applies a function to all elements in an iterable.
  • filter(): Filters elements based on a condition.
  • reduce(): Reduces an iterable to a single value (from functools module).
from functools import reduce numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25] evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4] total = reduce(lambda x, y: x + y, numbers) # 15
  1. What is a Python generator?
  • A generator is a function that returns an iterator using yield, saving memory.
def my_generator(): for i in range(5): yield i gen = my_generator() print(next(gen)) # Output: 0 print(next(gen)) # Output: 1
  1. What is the difference between yield and return?
  • return: Exits the function and returns a value.
  • yield: Pauses function execution and allows it to resume later.