0% found this document useful (0 votes)
3 views16 pages

Python+Programming+Interview+Guide

Uploaded by

thulasikaviya85
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views16 pages

Python+Programming+Interview+Guide

Uploaded by

thulasikaviya85
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

Python

Interview Question &


Answers
Basic Questions
1. What is Python?

Answer: Python is a high-level, interpreted, and general-purpose programming language that emphasizes code readability with its use
of significant indentation.

2. What are the key features of Python?

Answer: Key features include simplicity, portability, extensibility, scalability, built-in libraries, and support for multiple programming
paradigms (procedural, object-oriented, and functional).

3. What are Python's data types?

Answer: The primary data types in Python are integers (int), floating-point numbers (float), strings (str), booleans (bool), lists,
tuples, sets, and dictionaries.

4. What is a Python List?

Answer: A list is a mutable, ordered collection of items that can be of different data types. Lists are defined using square brackets, e.g.,
[1, 2, 3].

5. What is a Tuple?

Answer: A tuple is an immutable, ordered collection of items. It’s defined using parentheses, e.g., (1, 2, 3).
6. What is a Python dictionary?

Answer: A dictionary is an unordered collection of key-value pairs. Each key must be unique and immutable, and values can be of any
data type. It's defined using curly braces, e.g., {'key': 'value'}.

7. What is a set in Python?

Answer: A set is an unordered collection of unique items. It’s defined using curly braces, e.g., {1, 2, 3}.

8. What is the difference between a list and a tuple?

Answer: A list is mutable (can be modified after creation), while a tuple is immutable (cannot be modified).

9. How do you create a list in Python?

Answer: A list is created by placing comma-separated items within square brackets, e.g., my_list = [1, 2, 3].

10. How do you create a tuple?

Answer: A tuple is created by placing comma-separated values within parentheses, e.g., my_tuple = (1, 2, 3).
11. What is a function in Python?

Answer: A function is a block of reusable code that performs a specific task. It is defined using the def keyword.

12. How do you define a function in Python?

Answer: A function is defined using the def keyword, followed by the function name and parentheses, e.g.,
python
Copy code
def my_function():
print("Hello, World!")

13. What is *args in Python?

Answer: *args is used to pass a variable number of non-keyword arguments to a function.

14. What is **kwargs in Python?

Answer: **kwargs allows you to pass a variable number of keyword arguments to a function.
15. What is a lambda function?

Answer: A lambda function is an anonymous function defined using the lambda keyword. It can have any number of arguments but
only one expression.
python
Copy code
lambda x: x + 2

16. What are Python modules?

Answer: A module is a file containing Python definitions and statements. It can be imported into other modules or scripts.

17. How do you import a module in Python?

Answer: You can import a module using the import keyword:


python
Copy code
import math

18. What is a package in Python?

Answer: A package is a collection of modules organized in directories. It allows you to organize your code in a hierarchical way.
19. How do you handle exceptions in Python?

Answer: Python uses the try and except blocks to handle exceptions.
python
Copy code
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

20. What is the finally block in Python?

Answer: The finally block is used to execute code regardless of whether an exception is raised or not.
Intermediate Questions

21. What are Python decorators?

Answer: Decorators are functions that modify the behavior of another function or method. They are used to wrap another function.

22. How do you create a class in Python?

Answer: A class is created using the class keyword:


python
Copy code
class MyClass:
def __init__(self, name):
self.name = name

23. What is an object in Python?

Answer: An object is an instance of a class. It is a collection of variables and functions defined in the class.

24. What is inheritance in Python?

Answer: Inheritance allows one class to inherit the properties and methods of another class.
25. What is polymorphism in Python?

Answer: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It refers to the ability to
define a function or method in multiple forms.

26. What is encapsulation in Python?

Answer: Encapsulation is the concept of restricting access to certain details of an object and exposing only essential parts.

27. What is an abstract class in Python?

Answer: An abstract class cannot be instantiated and is used to define a blueprint for derived classes. It contains one or more abstract
methods that must be implemented in a subclass.

28. What is a generator in Python?

Answer: A generator is a function that returns an iterator. It uses the yield keyword to return values one at a time, preserving the
state between calls.

29. What are Python comprehensions?

Answer: Comprehensions provide a concise way to create lists, dictionaries, and sets by writing expressions inside a loop.
30. What are Python's built-in functions?

Answer: Python has several built-in functions like len(), type(), print(), input(), and sum(), which are used to perform
common tasks.

31. What is self in Python?

Answer: self refers to the instance of the class and is used to access variables and methods within the class.

32. What is the __init__ method in Python?

Answer: __init__ is a constructor method that is called when an object is instantiated. It initializes the object's attributes.

33. What is the difference between shallow copy and deep copy?

Answer: A shallow copy copies only the outer object, whereas a deep copy copies the outer object and all nested objects.

34. What is None in Python?

Answer: None represents the absence of a value. It is similar to null in other programming languages.
35. What are Python's magic methods?

Answer: Magic methods (or dunder methods) are special methods that start and end with double underscores, like __init__,
__str__, __repr__, and __len__.

36. What is the Global Interpreter Lock (GIL)?

Answer: The GIL is a mutex in CPython that protects access to Python objects, preventing multiple threads from executing Python
bytecode at once.

37. How does Python manage memory?

Answer: Python uses an automatic memory management system with reference counting and garbage collection to manage memory.

38. What is slicing in Python?

Answer: Slicing is a way to access a subset of elements from sequences like lists, tuples, and strings.
python
Copy code
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
39. What is the difference between break and continue?

Answer: break exits the loop entirely, while continue skips the current iteration and moves to the next one.

40. What is the difference between return and yield?

Answer: return exits the function and sends a value back to the caller, while yield pauses the function, returning a value and
saving the function's state for later use.

41. What is list unpacking in Python?

Answer: List unpacking allows multiple variables to be assigned from a list of values.
python
Copy code
a, b, c = [1, 2, 3]

42. How do you reverse a list in Python?

Answer: You can reverse a list using the reverse() method or slicing.
python
Copy code
my_list.reverse()
my_list[::-1]
43. What is the difference between is and ==?

Answer: is checks for object identity (whether they are the same object), whereas == checks for value equality.

44. What is a Python @staticmethod?

Answer: @staticmethod defines a method that does not operate on the instance or class and can be called without creating an
instance.

45. What is a @classmethod?

Answer: @classmethod defines a method that takes cls (the class) as the first parameter and operates on the class rather than an
instance.
Advanced Questions

46. What is the with statement in Python?

Answer: The with statement simplifies exception handling and ensures that resources like files are properly closed after use.
python
Copy code
with open('file.txt', 'r') as file:
content = file.read()

47. What is a metaclass in Python?

Answer: A metaclass is a class of a class that defines how a class behaves. Classes are instances of metaclasses.

48. What is a Python namedtuple?

Answer: namedtuple is a subclass of tuples which allows for named fields, making code more readable.
python
Copy code
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
.
49. What is duck typing in Python?

Answer: Duck typing is a concept where the type or class of an object is less important than the methods it defines. If an object can
perform an action, its type doesn't matter.

50. What is monkey patching in Python?

Answer: Monkey patching refers to modifying or extending a module or class at runtime.

51. What is the purpose of enumerate() in Python?

Answer: enumerate() adds a counter to an iterable and returns it as an enumerate object, making it easy to access both index and
value during iteration.

52. How do you merge two dictionaries in Python?

Answer: You can merge two dictionaries using the update() method or dictionary unpacking (**).
python
Copy code
dict1.update(dict2)
merged_dict = {**dict1, **dict2}
53. What is the difference between range() and xrange() in Python?

Answer: In Python 2, range() returns a list, whereas xrange() returns a generator. In Python 3, range() behaves like xrange().

54. What is zip() in Python?

Answer: zip() combines two or more iterables into tuples. Each tuple contains one element from each iterable.

55. What is a closure in Python?

Answer: A closure is a nested function that retains access to the variables in its enclosing scope even after the outer function has
finished executing.

56. What is the dir() function in Python?

Answer: dir() returns a list of the attributes and methods of an object.

57. What is help() in Python?

Answer: help() is a built-in function that provides a detailed explanation of modules, functions, classes, and methods.
58. What are Python's built-in types for text and binary data?

Answer: Python uses str for text data and bytes for binary data.

59. What is memory management in Python and how is it handled?

Answer: Python manages memory using an automatic garbage collector and reference counting for efficient memory allocation and
deallocation.

60. How do you read and write files in Python?

Answer: You can read and write files using the open() function in modes like r (read), w (write), and a (append). Here's an example
of writing to a file:
python
Copy code
with open('file.txt', 'w') as file:

file.write('Hello, World!')

You might also like