1. What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.


2. What are the main features of Python?

  • Simple and Easy to Learn: Python has a clear and straightforward syntax.
  • Interpreted Language: Python executes code line by line.
  • Dynamically Typed: Variables don’t need explicit declaration.
  • Extensive Libraries: Provides a vast standard library for various tasks.
  • Cross-Platform: Runs on multiple operating systems.
  • Object-Oriented: Fully supports object-oriented programming.

3. Explain the difference between static and dynamic typing.

  • Static Typing: Variable types are defined at compile-time (e.g., Java, C++).
  • Dynamic Typing: Variable types are determined at runtime (e.g., Python).
# Dynamic typing example in Python
x = 10        # x is an integer
x = "Python"  # x is now a string

4. What are the basic data types in Python?

  • Numeric: int, float, complex
  • Sequence: list, tuple, range
  • Text: str
  • Set Types: set, frozenset
  • Mapping: dict
  • Boolean: bool
  • Binary: bytes, bytearray, memoryview

5. How do you create a list in Python?

# Creating a list
my_list = [1, 2, 3, 4, "Python"]

6. What is a tuple in Python?

A tuple is an immutable sequence of items.

# Creating a tuple
my_tuple = (1, 2, 3, "Python")

7. Explain the difference between a list and a tuple.

  • List: Mutable, allows modification.
  • Tuple: Immutable, cannot be modified.

8. What is a dictionary in Python?

A dictionary is a collection of key-value pairs.

# Creating a dictionary
my_dict = {"name": "Python", "version": 3.9}

9. How do you create a dictionary in Python?

See the above example. Use curly braces {} with key-value pairs separated by a colon.


10. What is a set in Python?

A set is an unordered collection of unique items.

# Creating a set
my_set = {1, 2, 3, 3, 4}  # Duplicate values are ignored

11. What are the different types of control structures in Python?

  • Conditional Statements: if, elif, else
  • Loops: for, while
  • Control Transfer: break, continue, pass

12. Explain the if-else statement in Python.

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

13. How do you use the for loop in Python?

# Example of a for loop
for i in range(5):
    print(i)

14. What is the while loop in Python?

# Example of a while loop
x = 0
while x < 5:
    print(x)
    x += 1

15. Explain the break and continue statements in Python.

  • Break: Terminates the loop.
  • Continue: Skips to the next iteration.
for i in range(5):
    if i == 3:
        break  # Exits the loop
    print(i)

for i in range(5):
    if i == 3:
        continue  # Skips the current iteration
    print(i)

16. What is a function in Python?

A function is a block of reusable code designed to perform a specific task.


17. How do you define a function in Python?

def greet(name):
    return f"Hello, {name}!"

18. What are the different types of function arguments in Python?

  • Positional Arguments
  • Default Arguments
  • Keyword Arguments
  • Arbitrary Arguments (*args, **kwargs)

19. Explain the return statement in Python.

The return statement exits a function and optionally passes back a value.

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

20. How do you use the lambda function in Python?

A lambda function is an anonymous function.

# Lambda function example
square = lambda x: x**2
print(square(5))  # Output: 25

21. What is object-oriented programming in Python?

OOP is a paradigm that uses classes and objects to structure code.


22. Explain the concept of classes and objects in Python.

  • Class: A blueprint for creating objects.
  • Object: An instance of a class.

23. How do you define a class in Python?

class Dog:
    def __init__(self, name):
        self.name = name

dog = Dog("Buddy")

24. What is inheritance in Python?

Inheritance allows a class to inherit attributes and methods from another class.


25. Explain the concept of polymorphism in Python.

Polymorphism allows objects of different classes to be treated as objects of a common superclass.


26. How do you read a file in Python?

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

27. What is the difference between the read() and readline() methods?

  • read(): Reads the entire file.
  • readline(): Reads one line at a time.

28. How do you write a file in Python?

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

29. What is the difference between the write() and writelines() methods?

  • write(): Writes a string to the file.
  • writelines(): Writes a list of strings to the file.

30. Explain the concept of file modes in Python.

File modes include:

  • r: Read
  • w: Write
  • a: Append
  • r+: Read and write

31. What is exception handling in Python?

Exception handling manages runtime errors to prevent crashes.


32. Explain the try-except block in Python.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

33. How do you raise an exception in Python?

raise ValueError("Invalid input!")

34. What is the finally block in Python?

The finally block executes regardless of exceptions.


35. Explain the concept of exception propagation in Python.

Exceptions are passed up the call stack until caught.


36. What is a module in Python?

A module is a file containing Python code (functions, classes, etc.).


37. How do you import a module in Python?

import math

38. What is a package in Python?

A package is a collection of modules.


39. Explain the concept of namespace in Python.

A namespace is a container for identifiers to avoid name conflicts.


40. How do you create a package in Python?

Create a directory with an __init__.py file.


41. What is a stack in Python?

A stack is a data structure that follows LIFO.


42. Explain the concept of a queue in Python.

A queue is a FIFO data structure.


43. How do you implement a linked list in Python?

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

44. What is a tree in Python?

A hierarchical data structure where nodes have parent-child relationships.


45. Explain the concept of a graph in Python.

A graph is a collection of nodes (vertices) and edges.


46. What is a generator in Python?

A generator produces items lazily using yield.


47. Explain the concept of a decorator in Python.

A decorator modifies functions or methods.


48. How do you use the map() function in Python?

nums = [1, 2, 3]
squares = map(lambda x: x**2, nums)
print(list(squares))

49. What is the filter() function in Python?

Filters elements based on a condition.


50. Explain the concept of asynchronous programming in Python.

It allows tasks to run concurrently, improving performance with async and await.