Certainly! Here are 100 Python interview questions along with their short answers:
Basic Python Questions:
- What is Python?
- Python is a high-level, interpreted programming language known for its simplicity and readability.
- Who created Python, and when?
- Python was created by Guido van Rossum and was first released in 1991.
- What is the latest version of Python?
- As of my last knowledge update in September 2021, the latest stable version was Python 3.9.7.
- What is the difference between Python 2 and Python 3?
- Python 3 introduced many backward-incompatible changes, including print as a function, integer division by default, and improved Unicode support. Python 2 is no longer maintained.
- How do you write a comment in Python?
- Comments in Python start with a
#symbol and extend to the end of the line.
- What is PEP 8?
- PEP 8 is the Python Enhancement Proposal that defines the style guide for writing clean and readable Python code.
- Explain dynamic typing in Python.
- In Python, the data type of a variable is determined at runtime, making it a dynamically typed language.
- What is a Python interpreter?
- A Python interpreter is a program that executes Python code line by line.
- What is the Python Global Interpreter Lock (GIL)?
- The GIL is a mutex that allows only one thread to execute in a Python process at a time, which can limit multi-core CPU utilization.
- How do you exit the Python interpreter?
- You can use the
exit()function or pressCtrl+Zand thenEnteron Windows, orCtrl+Don Unix-based systems.
- You can use the
Data Types and Variables:
- What are the basic data types in Python?
- Python has data types like int, float, str, bool, list, tuple, set, dictionary, and more.
- How do you declare a variable in Python?
- Variables are declared by assigning a value to a name, e.g.,
x = 10.
- Variables are declared by assigning a value to a name, e.g.,
- What is a tuple in Python?
- A tuple is an ordered, immutable collection of elements, often used to group related data.
- Explain the difference between a list and a tuple.
- Lists are mutable, while tuples are immutable. Lists are defined with square brackets, and tuples with parentheses.
- What is the purpose of a dictionary in Python?
- A dictionary is used to store key-value pairs, allowing fast retrieval of values based on their keys.
- How do you check the data type of a variable in Python?
- You can use the
type()function to check the data type of a variable.
- You can use the
- What is the
Nonedata type in Python?Noneis a special data type representing the absence of a value or a null value.
- How do you swap the values of two variables in Python?
- You can swap values with a temporary variable or use tuple packing/unpacking:
a, b = b, a.
- You can swap values with a temporary variable or use tuple packing/unpacking:
- What is string interpolation in Python?
- String interpolation is the process of embedding variable values within strings, often done using f-strings or the
.format()method.
- String interpolation is the process of embedding variable values within strings, often done using f-strings or the
- What is the
isoperator used for in Python?- The
isoperator checks if two variables reference the same object in memory.
- The
Control Structures:
- What is an if statement in Python?
- An
ifstatement is used for conditional execution of code.
- An
- How do you write a for loop in Python?
- You can use a
forloop with therange()function or iterate over elements in an iterable.
- You can use a
- What is a
whileloop in Python used for?- A
whileloop repeatedly executes a block of code as long as a condition is true.
- A
- What is the purpose of the
breakstatement in Python?breakis used to exit a loop prematurely.
- Explain the
continuestatement in Python.continueis used to skip the current iteration of a loop and continue with the next one.
- What is the
passstatement in Python used for?passis a placeholder statement used when no action is required.
- What is a ternary conditional expression in Python?
- A ternary expression is a concise way to write an
if-elsestatement in a single line.
- A ternary expression is a concise way to write an
- What is a generator in Python?
- A generator is a function that returns an iterator, allowing for lazy, memory-efficient processing of large datasets.
- How do you handle exceptions in Python?
- You can use
try...exceptblocks to catch and handle exceptions, orfinallyto ensure cleanup.
- You can use
- What is the purpose of the
assertstatement in Python?assertis used to check if a given condition isTrue, and if not, it raises anAssertionError.
Functions:
- What is a function in Python?
- A function is a block of reusable code that performs a specific task when called.
- How do you define a function in Python?
- Functions are defined using the
defkeyword, followed by the function name and parameters.
- Functions are defined using the
- What is a default argument in a Python function?
- A default argument is a parameter with a predefined value, allowing it to be omitted when calling the function.
- How do you return a value from a function in Python?
- You can use the
returnstatement to return a value from a function.
- You can use the
- What is a lambda function in Python?
- A lambda function is an anonymous, small, and simple function defined using the
lambdakeyword.
- A lambda function is an anonymous, small, and simple function defined using the
- How do you pass a variable number of arguments to a Python function?
- You can use
*argsto pass a variable number of non-keyword arguments and**kwargsfor keyword arguments.
- You can use
- What is a docstring in Python?
- A docstring is a string used to document a function, module, or class, providing information about its purpose and usage.
- What is a recursive function in Python?
- A recursive function is a function that calls itself to solve a problem.
- What is the purpose of the
mapfunction in Python?mapapplies a function to all elements of an iterable and returns an iterator with the results.
- How can you access global variables within a function in Python?
- Use the
globalkeyword to declare a variable as global within a function.
- Use the
Lists, Sets, and Dictionaries:
- What is a list in Python?
- A list is an ordered, mutable collection of elements, often used to store multiple items.
- What is a set in Python?
- A
- What is a dictionary in Python?
- A dictionary is an unordered collection of key-value pairs, used for quick value retrieval.
- How do you add an item to a list in Python?
- You can use the
append()method or list concatenation to add items to a list.
- You can use the
- What is a set comprehension in Python?
- Set comprehension is a concise way to create sets based on an existing iterable, similar to list comprehension.
- How do you access a value in a dictionary using its key?
- You can access a dictionary value by providing its key in square brackets, e.g.,
my_dict['key'].
- You can access a dictionary value by providing its key in square brackets, e.g.,
- What is the purpose of the
getmethod for dictionaries in Python?- The
getmethod allows you to retrieve a value from a dictionary using a key. If the key does not exist, it returns a default value.
- The
- How do you remove a key-value pair from a dictionary in Python?
- You can use the
delstatement or thepop()method to remove a key-value pair.
- You can use the
- What is the difference between a list and a tuple in Python?
- Lists are mutable, while tuples are immutable. Lists are defined with square brackets, and tuples with parentheses.
- What is a dictionary comprehension in Python?
- Dictionary comprehension is a concise way to create dictionaries based on an existing iterable.
Strings and Text Processing:
- What is a string in Python?
- A string is a sequence of characters enclosed in single, double, or triple quotes.
- How do you find the length of a string in Python?
- You can use the
len()function to find the length of a string.
- You can use the
- What is string slicing in Python?
- String slicing is the process of extracting a portion of a string by specifying a range.
- How do you concatenate strings in Python?
- You can use the
+operator or thejoin()method to concatenate strings.
- You can use the
- What is string interpolation in Python?
- String interpolation is the process of embedding variable values within strings, often done using f-strings or the
.format()method.
- String interpolation is the process of embedding variable values within strings, often done using f-strings or the
- How do you reverse a string in Python?
- You can reverse a string using slicing with a step of -1:
my_str[::-1].
- You can reverse a string using slicing with a step of -1:
- What is the
strip()method used for in Python?strip()removes leading and trailing whitespace characters from a string.
- What is the difference between
split()andsplitlines()methods in Python?split()splits a string into a list based on a specified delimiter, whilesplitlines()splits a string into a list of lines.
- How do you replace a substring in a string in Python?
- You can use the
replace()method to replace a substring in a string.
- You can use the
- What is the purpose of the
startswith()andendswith()methods in Python?startswith()checks if a string starts with a specified prefix, andendswith()checks if it ends with a specified suffix.
Classes and Object-Oriented Programming:
- What is a class in Python?
- A class is a blueprint for creating objects that represent real-world entities.
- How do you create an object from a class in Python?
- Objects are created by calling the class as if it were a function, e.g.,
my_object = MyClass().
- Objects are created by calling the class as if it were a function, e.g.,
- What is an instance variable in Python?
- An instance variable is a variable that belongs to an instance (object) of a class.
- What is a constructor in Python?
- A constructor is a special method with the name
__init__, used to initialize object attributes.
- A constructor is a special method with the name
- What is inheritance in Python?
- Inheritance is the mechanism that allows one class to inherit properties and methods from another class.
- What is a method in Python?
- A method is a function defined within a class that can be called on an object of that class.
- What is encapsulation in object-oriented programming?
- Encapsulation is the concept of bundling data and methods that operate on that data into a single unit (class).
- What is method overloading in Python?
- Python does not support method overloading in the traditional sense due to dynamic typing.
- Explain the concept of polymorphism in Python.
- Polymorphism allows objects of different classes to be treated as objects of a common superclass.
- What is a class attribute in Python?
- A class attribute is a variable defined within a class and shared by all instances of the class.
File Handling:
- How do you open a file in Python?
- You can use the
open()function to open a file in various modes (e.g., read, write, append).
- You can use the
- What is the difference between ‘r’, ‘w’, and ‘a’ file modes?
- ‘r’ is for reading, ‘w’ is for writing (creates a new file or overwrites an existing one), and ‘a’ is for appending data to a file.
- How do you read the contents of a file in Python?
- You can use methods like
read(),readline(), or iterate through the file object.
- You can use methods like
- How do you write to a file in Python?
- Use the
write()method orprint()function with a file argument to write data to a file.
- Use the
- How can you close a file in Python?
- Use the
close()method or a context manager (with statement) to automatically close the file.
- Use the
- What is the
withstatement used for in file handling?- The
withstatement is used to ensure proper cleanup and resource management when working with files.
- The
- How do you check if a file exists in Python?
- You can use the
os.path.exists()function or theos.path.isfile()function to check if a file exists.
- You can use the
- How do you delete a file in Python?
- You can use the
os.remove()function to delete a file.
- You can use the
- What is file seek and tell in Python?
seek()is used to change the file position, andtell()returns the current position in the file.
- What is binary file mode (‘b’) in Python?
- ‘b’ is used to open a file in binary mode, allowing you to work with non-text files, like images or executables.
Exception Handling:
- What is an exception in Python?
- An exception is an error or issue that occurs during the execution of a Python program.
- How do you handle exceptions in Python?
- You can use
try...exceptblocks to catch and handle exceptions.
- You can use
- What is the
finallyblock used for in exception handling?- The `finally
` block is used to define code that will be executed regardless of whether an exception is raised or not.
- What is the purpose of the
raisestatement in Python?- The
raisestatement is used to manually raise an exception.
- The
- What are built-in exceptions in Python?
- Python has a range of built-in exceptions like
ZeroDivisionError,TypeError, andValueError.
- Python has a range of built-in exceptions like
- How do you create custom exceptions in Python?
- You can create custom exceptions by defining a new class that inherits from the
Exceptionclass.
- You can create custom exceptions by defining a new class that inherits from the
- What is the
try...except...elseblock used for in Python?- The
elseblock is executed when no exception occurs in thetryblock.
- The
- What is exception chaining in Python?
- Exception chaining allows you to raise a new exception while preserving the original exception’s context.
- What is the purpose of the
assertstatement in Python?assertis used for debugging to check if an expression isTrue, and if not, it raises anAssertionError.
- What is the
exceptstatement without an exception type in Python?- An
exceptstatement without a specified exception type catches any exception that is not explicitly handled by otherexceptblocks.
- An
Modules and Packages:
- What is a module in Python?
- A module is a Python script that contains reusable code, including functions, variables, and classes.
- How do you import a module in Python?
- You can use the
importstatement to import a module, e.g.,import math.
- You can use the
- What is a Python package?
- A package is a collection of related modules organized in directories.
- How do you create a Python package?
- Create a directory containing an
__init__.pyfile, and place your modules in it.
- Create a directory containing an
- What is the purpose of the
__init__.pyfile in a package?__init__.pyis an empty file that marks a directory as a Python package.
- What is the difference between
import moduleandfrom module import something?import moduleimports the entire module, whilefrom module import somethingimports only specific items.
- How can you alias a module or import under a different name?
- You can use the
askeyword to create an alias while importing, e.g.,import math as m.
- You can use the
- What is a built-in module in Python?
- Built-in modules are modules that come with Python and provide essential functionality, like
math,os, andsys.
- Built-in modules are modules that come with Python and provide essential functionality, like
- What is the purpose of the
__name__variable in Python?__name__is a special variable that identifies whether a Python script is being run as the main program or imported as a module.
- How do you install third-party packages in Python?
- You can use a package manager like
pipto install third-party packages, e.g.,pip install package_name.
- You can use a package manager like