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

Python Interview Questions

The document contains a comprehensive list of Python basics interview questions along with their answers, covering topics such as Python features, data types, control flow, functions, object-oriented programming, data structures, exception handling, and file handling. Each question is succinctly answered, providing essential information for understanding Python programming concepts. This resource serves as a useful guide for individuals preparing for Python-related interviews.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views27 pages

Python Interview Questions

The document contains a comprehensive list of Python basics interview questions along with their answers, covering topics such as Python features, data types, control flow, functions, object-oriented programming, data structures, exception handling, and file handling. Each question is succinctly answered, providing essential information for understanding Python programming concepts. This resource serves as a useful guide for individuals preparing for Python-related interviews.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Python basics interview questions with

answers:

l
ita
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 key features of Python?

●​ ig
Easy to learn and read: Uses simple syntax similar to English.
ad
●​ Interpreted: Executes code line by line, making debugging easier.
●​ Dynamically Typed: No need to declare variable types.
●​ Object-Oriented: Supports classes and objects.
●​ Extensive Libraries: Provides built-in libraries for various applications.
●​ Platform Independent: Works on multiple operating systems.
ith

3. What is the difference between Python 2 and Python 3?

●​ Python 3 is the latest version and is not backward compatible with Python 2.
●​ print is a function in Python 3 (print("Hello")) but a statement in Python 2
(print "Hello").
an

●​ Integer division in Python 3 (5/2 = 2.5), while Python 2 returns an integer (5/2 = 2).
●​ Unicode handling is improved in Python 3 (str is Unicode by default).

4. What is PEP 8?

PEP 8 is the official Python style guide that provides coding conventions for writing clean and
readable Python code. It covers aspects like indentation, naming conventions, and best
practices.

1
5. What are Python’s data types?

Python has several built-in data types:

l
●​ Numeric types: int, float, complex

ita
●​ Sequence types: list, tuple, range, str
●​ Set types: set, frozenset
●​ Mapping type: dict
●​ Boolean type: bool (True/False)

ig
6. What is the difference between a list and a tuple?

●​ List: Mutable (can be changed), defined using square brackets []. Example: my_list
ad
= [1, 2, 3].
●​ Tuple: Immutable (cannot be changed), defined using parentheses (). Example:
my_tuple = (1, 2, 3).

7. What is the difference between is and == in Python?


ith

●​ == compares the values of two objects.


●​ is compares the memory addresses (object identity).​
Example:
an

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (values are the same)
print(a is b) # False (different memory locations)

2
8. What is the use of the id() function in Python?

The id() function returns the unique memory address of an object.​

l
Example:

ita
x = 10
print(id(x)) # Output: A unique memory address

Python?
ig
9. What is the difference between mutable and immutable objects in

●​ Mutable objects: Can be changed after creation (e.g., list, dict, set).
ad
●​ Immutable objects: Cannot be changed after creation (e.g., int, float, tuple, str).

10. What is the purpose of the type() function in Python?

The type() function is used to check the data type of a variable.​


ith

Example:

x = 5
print(type(x)) # Output: <class 'int'>
an

11. What are the advantages of Python?

●​ Simple and easy to learn


●​ Open-source and community support
●​ Platform-independent
●​ Extensive libraries and frameworks
●​ Supports object-oriented and functional programming

3
12. What is indentation in Python?

Indentation in Python is used to define code blocks. Unlike other languages that use braces {},
Python uses indentation (spaces or tabs) to structure code.

l
ita
13. How do you comment in Python?

●​ Single-line comment: # This is a comment

Multi-line comment: Use triple quotes​



"""
This is a multi-line comment
"""
ig
ad
●​

14. What are Python literals?

Literals are fixed values assigned to variables. Examples:


ith

●​ String literal: "Hello"


●​ Numeric literal: 100, 3.14
●​ Boolean literal: True, False
●​ None literal: None
an

15. What are variables in Python?

Variables are used to store values. Python variables are dynamically typed, meaning no need
for explicit declaration.


Example:

x = 10

4
name = "Python"

16. What are Python identifiers?

Identifiers are names given to variables, functions, classes, etc. They must start with a letter or

l
underscore (_) but cannot use Python keywords.

ita
17. How do you assign multiple values to variables in Python?

Python allows multiple assignments in one line:

a, b, c = 1, 2, 3

ig
ad
18. What are reserved keywords in Python?

Reserved keywords are predefined words in Python. Examples: if, else, def, return,
class, try, except, lambda.

19. What is type conversion in Python?


ith

Type conversion changes a variable’s data type.

●​ Implicit: x = 5 + 3.0 (integer 5 converts to float 5.0).


●​ Explicit: x = int("10") (string "10" converts to integer 10).
an

20. What is the difference between del and None?

●​ del deletes a variable from memory.


●​ None is a special object that represents the absence of a value.

5
Data Types and Operators

21. What are different number types in Python?

l
●​ int (e.g., 10)

ita
●​ float (e.g., 3.14)
●​ complex (e.g., 2 + 3j)

22. How do you check the type of a variable?

Use type():

x = 10
print(type(x)) # Output: <class 'int'>
ig
ad
23. What are Python string operations?

Python strings support concatenation (+), repetition (*), slicing ([:]), and built-in functions like
ith

.upper(), .lower(), .replace().

24. What are Python membership operators?

●​ in: Checks if a value exists in a sequence.


an

●​ not in: Checks if a value does not exist.​


Example:

print("a" in "apple") # True

25. What are Python identity operators?

●​ is: Checks if two objects refer to the same memory location.


●​ is not: Checks if two objects refer to different memory locations.

6
26. How does Python handle division?

●​ / (floating-point division)
●​ // (floor division, rounds down)

l
ita
27. What is the difference between == and is?

●​ == compares values.
●​ is compares object identity (memory address).

28. What is the difference between + and +=?

●​ + creates a new object.


ig
●​ += modifies the existing object (if mutable).
ad
29. How do you format strings in Python?

Using format():
ith

name = "Alice"
print("Hello, {}".format(name))

Or f-strings:
an

print(f"Hello, {name}")

7
30. What are f-strings?

F-strings (f"Hello, {name}") are a modern way to format strings efficiently.

l
Control Flow and Loops

ita
31. What is the difference between if, elif, and else?

●​ if checks a condition.
●​ elif (else if) checks additional conditions.

ig
●​ else executes when none of the conditions are met.

32. What are Python loop types?


ad
●​ for loop (iterates over sequences).
●​ while loop (runs as long as the condition is true).

33. How does a for loop work?


ith

It iterates over sequences (lists, tuples, strings):

for i in range(5):
print(i)
an

34. What is range() used for?

range(start, stop, step) generates a sequence of numbers.​


Example: range(1, 10, 2) → [1, 3, 5, 7, 9].

35. What is the break statement?

It exits a loop immediately.

36. What is the continue statement?

8
It skips the rest of the loop body and moves to the next iteration.

37. What is the pass statement?

A placeholder statement that does nothing.

l
38. How do you use else with loops?

ita
An else block in loops executes only if the loop completes without break.

for i in range(5):
print(i)
else:
print("Loop finished")
ig
ad
39. What is a nested loop?

A loop inside another loop.

40. What is list comprehension?


ith

A concise way to create lists.​


Example:

squares = [x**2 for x in range(5)]


an

Functions and Modules

41. What is a function?

A function is a reusable block of code.

42. How do you define a function in Python?

Using def:

9
def greet():

print("Hello")

43. What are function arguments?

l
ita
●​ Positional arguments (order matters).
●​ Keyword arguments (name="Alice").
●​ Default arguments (age=25).
●​ Arbitrary arguments (*args, **kwargs).

ig
44. What is the difference between return and print?

●​ return gives a value back to the caller.


●​ print displays output but does not return a value.
ad
45. What is a lambda function?

An anonymous function:
ith

square = lambda x: x**2


print(square(4)) # Output: 16

46. What are default arguments in functions?


an

Default arguments have predefined values if no argument is provided.

def greet(name="Guest"):
print(f"Hello, {name}")
greet() # Output: Hello, Guest

10
47. What is the difference between *args and **kwargs?

l
●​ *args: Passes multiple arguments as a tuple.

ita
●​ **kwargs: Passes multiple keyword arguments as a dictionary.

def demo(*args, **kwargs):


print(args) # Tuple
print(kwargs) # Dictionary

48. What is variable scope in Python?


ig
ad
●​ Local Scope: Inside a function.
●​ Global Scope: Outside a function.
●​ Enclosing Scope: Nested functions.
●​ Built-in Scope: Predefined Python functions.

49. What is a recursive function?


ith

A function that calls itself.

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

50. How do you import modules in Python?

Use import:

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

11
51. What is the difference between import and from import?

l
●​ import module_name: Imports the entire module.

ita
●​ from module_name import function: Imports specific functions.

from math import sqrt


print(sqrt(16)) # Output: 4.0

52. What are built-in modules in Python?

ig
Examples: os, sys, math, datetime, random, json.
ad
53. What is the difference between a module and a package?

●​ Module: A single Python file (.py).


●​ Package: A collection of modules with an __init__.py file.
ith

54. What is the __name__ == "__main__" construct?

It ensures a script runs only when executed directly, not when imported.

55. How do you create a virtual environment in Python?


an

bash
python -m venv myenv

Object-Oriented Programming (OOP)

56. What is OOP?

Object-Oriented Programming (OOP) is a paradigm that uses objects and classes.

12
57. What are the four pillars of OOP?

l
1.​ Encapsulation

ita
2.​ Inheritance
3.​ Polymorphism
4.​ Abstraction

58. How do you define a class in Python?

class Car:
def __init__(self, brand):
self.brand = brand
ig
ad
59. What is self in Python classes?

self represents the instance of the class.


ith

60. What is the difference between a class and an object?

●​ Class: A blueprint.
●​ Object: An instance of a class.
an

61. What is a constructor in Python?

A constructor (__init__()) initializes an object.

62. What is inheritance in Python?

A class can inherit methods from another class.

class Car:
def drive(self):
print("Driving")

13
class Tesla(Car):
pass

l
63. What is polymorphism in Python?

ita
Same method, different implementations.

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self): ig
ad
return "Bark"

64. What is method overriding?

A subclass redefines a method from the parent class.


ith

65. What is method overloading?

Python does not support true method overloading, but it can be achieved using default
arguments.
an

Data Structures in Python

66. What are Python data structures?

●​ List ([])
●​ Tuple (())
●​ Set ({})

14
●​ Dictionary ({key: value})

67. What is the difference between a list and a set?

●​ List: Ordered, allows duplicates.


●​ Set: Unordered, no duplicates.

l
ita
68. How do you create a dictionary?
my_dict = {"name": "Alice", "age": 25}

69. How do you access dictionary keys and values?


print(my_dict.keys())

ig
# Get keys
print(my_dict.values()) # Get values
ad
70. How do you remove duplicates from a list?

my_list = [1, 2, 2, 3]
unique_list = list(set(my_list))
ith

71. How do you sort a list?


numbers = [3, 1, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3]
an

72. What is list slicing?

Extracting parts of a list using [:].

nums = [0, 1, 2, 3]
print(nums[1:3]) # Output: [1, 2]

15
73. What is the difference between copy() and deepcopy()?

●​ copy(): Creates a shallow copy (references nested objects).


●​ deepcopy(): Creates a deep copy (new memory for nested objects).

l
ita
74. How do you iterate through a dictionary?

for key, value in my_dict.items():


print(key, value)

75. How do you reverse a list?


ig
ad
my_list = [1, 2, 3]
print(my_list[::-1])
ith

Exception Handling

76. What is an exception in Python?


an

An error that occurs during execution.

77. How do you handle exceptions?

Using try-except:

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

16
l
ita
78. What is finally in exception handling?

Runs whether an exception occurs or not.

try:
x = 1 / 0
except:
print("Error") ig
ad
finally:
print("Execution completed")

79. What are built-in exceptions in Python?


ith

Examples: ZeroDivisionError, TypeError, ValueError, IndexError.

80. How do you raise an exception?

raise ValueError("Invalid value")


an

File Handling

81. How do you open a file in Python?


file = open("data.txt", "r")

82. What are file modes?

17
●​ "r": Read
●​ "w": Write (overwrite)
●​ "a": Append
●​ "r+": Read & Write

l
ita
83. How do you write to a file?
with open("data.txt", "w") as file:
file.write("Hello")

84. How do you read from a file?

with open("data.txt", "r") as file: ig


ad
content = file.read()

85. What is with in file handling?

It ensures proper file closure.


ith

Miscellaneous

86. What is the difference between JSON and Python dictionaries?


an

JSON keys must be strings, whereas dictionary keys can be any hashable type.

87. How do you parse JSON in Python?


import json
data = json.loads('{"name": "Alice"}')

88. How do you generate random numbers in Python?

import random

18
print(random.randint(1, 10))

89. What is the map() function?

Applies a function to all items in an iterable.

l
ita
90. How do you check memory usage in Python?

Using sys.getsizeof().

ig
91. What is the difference between is and == in Python?

●​ is checks whether two variables refer to the same memory location (identity
ad
comparison).
●​ == checks whether the values are equal (value comparison).

a = [1, 2, 3]
ith

b = [1, 2, 3]
print(a == b) # True (values are equal)
print(a is b) # False (different memory locations)
an

92. What is a lambda function in Python?

A lambda function is an anonymous (unnamed) function using the lambda keyword.

square = lambda x: x * x
print(square(5)) # Output: 25

19
93. What is list comprehension?

A concise way to create lists in Python.

squares = [x*x for x in range(5)]

l
print(squares) # Output: [0, 1, 4, 9, 16]

ita
94. What is a Python decorator?

ig
A decorator is a function that modifies another function without changing its structure.

def decorator(func):
ad
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
ith

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

say_hello()

Output:

Before function call


Hello!
After function call

20
95. What is pass in Python?

l
pass is a placeholder when a statement is required but no action is needed.

ita
def my_function():
pass # Placeholder for future implementation

96. What is None in Python?


ig
None is a special constant representing the absence of a value.
ad
x = None
print(x is None) # Output: True
ith

97. What is zip() in Python?

zip() combines multiple iterables into pairs.


an

names = ["Alice", "Bob"]


ages = [25, 30]
combined = zip(names, ages)
print(list(combined)) # Output: [('Alice', 25), ('Bob', 30)]

98. How do you swap two variables in Python?

21
a, b = 5, 10
a, b = b, a
print(a, b) # Output: 10, 5

l
ita
ig
99. What is the difference between deepcopy() and copy()?

●​ copy(): Creates a shallow copy (changes in nested objects affect the copy).
●​ deepcopy(): Creates a deep copy (nested objects are also copied separately).
ad
import copy

list1 = [[1, 2], [3, 4]]


ith

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

list1[0][0] = 99
an

print(shallow_copy) # [[99, 2], [3, 4]] (affected)


print(deep_copy) # [[1, 2], [3, 4]] (not affected)

100. How do you merge two dictionaries in Python?

dict1 = {"a": 1, "b": 2}


dict2 = {"c": 3, "d": 4}

22
merged = {**dict1, **dict2}
print(merged) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

l
ita
ig
ad
ith
an

23
an
ith
ad
ig
ita
l

24
an
ith
ad
ig
ita
l

25
an
ith
ad
ig
ita
l

26

You might also like