Best Python interview questions

  • Post category:python
  • Reading time:27 mins read

Python interview questions for freshers

1. What is python ?

Python is a high-level programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability with its clean and easy-to-understand syntax, making it a popular choice for beginners and experienced developers alike.

Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming. It has a comprehensive standard library that provides tools and modules for various tasks such as file I/O, networking, web development, and data manipulation.

Python’s versatility has led to its widespread adoption in various fields, including web development, data analysis, artificial intelligence, scientific computing, and automation. Its large and active community continuously develops new libraries and frameworks, expanding its capabilities and making it suitable for a wide range of applications.

2. What are key features of python ?

Key features of python are-

  • Easy to Learn and Read
  • Versatile
  • Interpreted and Interactive
  • Object-Oriented
  • Community and Documentation

3. What are all domains where python can be used?

  • Web Development: Frameworks like Django and Flask.
  • Data Science and Machine Learning: Libraries like NumPy, Pandas, Matplotlib, Scikit-Learn, and TensorFlow.
  • Automation and Scripting: Used for tasks ranging from system administration to testing.
  • Artificial Intelligence: Widely used in AI research and development.

You may also like


4. What is dynamically typed language?

A dynamically typed language is a programming language where variables are not bound to a specific data type at compile time but rather at runtime. In dynamically typed languages, the type of a variable is determined while the program is executing, based on the value assigned to it.

In contrast to statically typed languages, where variables must be explicitly declared with their data type (such as int, float, string, etc.) before they can be used, dynamically typed languages allow variables to be assigned values of any type without prior declaration. This flexibility makes dynamically typed languages more concise and easier to work with in certain situations.

Examples of dynamically typed languages include Python, JavaScript, Ruby, and PHP. These languages provide dynamic typing to allow developers to write code more quickly and with less explicit type handling, but it also comes with potential pitfalls, such as runtime type errors that may not be caught until execution.

To know more about Python variables, visit https://proedu.co/python/python-variables/

# No Data Type declaration is required for a variable creation in python.
message = "Hello Proedu!"
marks = 100

print(message)
print(marks)

# Output
Hello Proedu!
100

5. What are python data types?

Python provides several built-in data types that are commonly used. Here’s an overview of some of the main data types:

Basic Data Types

  1. Integer (int): Whole numbers, both positive and negative, without any decimal point. Example: 42, -3
  2. Floating Point (float): Numbers with a decimal point. Example: 3.14, -0.001
  3. Complex Numbers (complex): Numbers with a real and an imaginary part. Example: 3 + 4j, 1.5 - 2.5j
  4. Boolean (bool): Represents one of two values: True or False.
  5. String (str): A sequence of characters enclosed in single, double, or triple quotes. Example: "hello", 'world', """multi-line string"""

Collection Data Types

  1. List (list): Ordered, mutable collections of items (which can be of mixed types). Example: [1, 'apple', 3.14]
  2. Tuple (tuple): Ordered, immutable collections of items (which can be of mixed types). Example: (1, 'apple', 3.14)
  3. Set (set): Unordered collections of unique items. Example: {1, 2, 3, 4}
  4. Dictionary (dict): Unordered collections of key-value pairs. Example: {'name': 'Alice', 'age': 30}

Specialized Data Types

  1. Range (range): Represents an immutable sequence of numbers. Example: range(0, 10)
  2. Bytes (bytes): Immutable sequences of bytes (8-bit values). Example: b'hello'
  3. Bytearray (bytearray): Mutable sequences of bytes. Example: bytearray(b'hello')
  4. Memoryview (memoryview): Provides a way to access the internal data of an object that supports the buffer protocol without copying. Example: memoryview(b'hello')

None Type

  1. None: Represents the absence of a value or a null value. Example: None

6. Is Python a compiled language or an interpreted language?

Python is primarily an interpreted language, which means that its code is executed by an interpreter rather than being compiled into machine code ahead of time. However, Python has elements of both interpreted and compiled languages.

Interpreted Nature

Python code is executed line-by-line by the Python interpreter. This means that the code is parsed and executed in real time, rather than being converted into a standalone executable file.

Compiled Aspects

  1. Bytecode Compilation:
    • When a Python script is run, it is first compiled to bytecode (a lower-level, platform-independent representation of the source code). This bytecode is stored in .pyc files in the __pycache__ directory.
    • Bytecode compilation is an intermediate step and is typically invisible to the user. The Python interpreter then executes this bytecode.
  2. Just-In-Time Compilation (JIT):
    • Some implementations of Python, like PyPy, use Just-In-Time compilation to improve performance. This means that parts of the bytecode can be compiled to machine code at runtime, leading to faster execution.

Summary

  • Interpreted Language: Python is primarily considered an interpreted language because its source code is executed by an interpreter.
  • Bytecode Compilation: Python code is first compiled to bytecode, which is then interpreted.
  • JIT Compilation: Some Python implementations use JIT compilation to enhance performance, blurring the line between interpreted and compiled behavior.

In essence, while Python has elements of both interpreted and compiled languages, it is most commonly described as an interpreted language due to its direct execution model and interactive capabilities.

7. How to write a comment in python?

There are two types of comments you can use:

Single-Line Comments

Single-line comments start with the hash character (#). Everything after the # on that line is considered a comment and is ignored by the Python interpreter.

# This is a single-line comment.
print("Hello, Proedu.co!")  
# This is another comment.

Multi-Line Comments

While Python does not have a specific syntax for multi-line comments, you can use multi-line strings (triple quotes) to achieve a similar effect. Although these strings are technically not comments and will be stored as docstrings if placed at the beginning of a class, function, or module, they can be used elsewhere to serve as comments.

"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Hello, Proedu.co!")  

Docstrings

Docstrings are a special kind of comment used to describe the purpose of a function, class, or module. They are placed as the first statement in the function, class, or module.

def my_function():
    """
    This is a docstring.
    It explains what the function does.
    """
    print("Hello, Proedu.co!")

8. What are mutable and immutable datatypes in python?

In Python, data types can be classified as mutable or immutable based on whether their value can be changed after they are created.

Mutable Data Types

Mutable data types are those whose values can be changed in place after they are created. This means you can alter, add, or remove elements without creating a new object. Examples – List, Dictionary, Set, bytearray.

# Modifying the existing list.
my_list = [1, 2, 3]
my_list[0] = 100
my_list.append(100)

# Modifying the existing dictionary.
my_dict = {"name": "Shivaay", "age": "6"}
my_dict["city"] = "Haridwar"

# Modifying the existing set.
my_set = {1, 2, 3}
my_set.add(4)
my_set.update({5, 6, 7})


byte_array = bytearray(b"Hello Proedu.co")
byte_array[14] = 33
print(byte_array)

Immutable Data Types

Immutable data types are those whose values cannot be changed once they are created. Any modification to an immutable object results in the creation of a new object. Examples – int, float, string, tuple, frozenset, bytes.

# Creates a new integer object on increment.
count = 100
count1 = count + 1

# Creates a new float object
marks = 90.5
marks1 = 90.5 * 2

# Creates a new string object
message = "Hello"
new_message = message + " Proedu.co!!!"

# Creates a new tuple object
my_tuple = (1, 2, 3)
new_tuple = my_tuple + (4,)

# Immutable frozenset
my_frozenset = frozenset([1, 2, 3])

# Creates a new bytes object
my_bytes = b'hello'
new_bytes = my_bytes + b' Proedu.co!!!'  

9. Are arguments passed by value or by reference in Python?

In Python, When you pass an argument to a function, Python assigns the reference of the object to the corresponding parameter in the function (Pass by reference).

10. What is the difference between a List and Set in Python?

In Python, List and Set are both data structures used to store collections of items, but they have different characteristics and use cases. Here are the key differences between them:

LISTSET
OrderLists are ordered collections, meaning that the elements have a defined order, and each element can be accessed by its index.Sets are unordered collections. The elements do not have a defined order, and there is no index assigned to any element.
DuplicatesLists can contain duplicate elements. The same value can appear multiple times in different positions within the list.Sets do not allow duplicate elements.
Indexing and SlicingLists support indexing and slicing. You can access, modify, and slice elements using indices.Sets do not support indexing, slicing, or other sequence-like behavior because they are unordered.
MutableLists are mutable, meaning that their elements can be changed after the list is created. You can add, remove, or modify elements.Sets are mutable, meaning that elements can be added or removed after the set is created. However, the elements themselves must be immutable (e.g., numbers, strings, tuples).
Common MethodsSome common methods for lists include append(), extend(), insert(), remove(), pop(), sort(), reverse(), and index().Some common methods for sets include add(), remove(), discard(), pop(), clear(), union(), intersection(), difference(), and issubset().
PerformanceLists are generally better suited for accessing elements by index, iteration, and operations that rely on order.Sets are optimized for membership testing and eliminating duplicate entries. Checking if an element is in a set (membership test) is generally faster compared to a list.

11. What is the difference between a List and Dictionary in Python?

In Python, List and Dictionary are both data structures used to store collections of items, but they have different characteristics and use cases. Lists are ordered collections whereas Dictionaries store data in key-value pairs. Each key must be unique, and each key maps to a specific value.

LISTDICTIONARY
OrderLists are ordered collections, meaning that the elements have a defined order, and each element can be accessed by its index.As of Python 3.7, dictionaries maintain the insertion order of keys. This means that when you iterate over a dictionary, the keys will be returned in the order they were added.
DuplicatesLists can contain duplicate elements. The same value can appear multiple times in different positions within the list.Dictionaries do not allow duplicate keys. If you assign a new value to an existing key, the old value is overwritten.
Indexing and SlicingLists support indexing and slicing. You can access, modify, and slice elements using indices.Instead of accessing elements by their position, dictionaries allow you to access elements by their keys.
MutableLists are mutable, meaning that their elements can be changed after the list is created. You can add, remove, or modify elements.Dictionaries are mutable, meaning that you can change, add, or remove key-value pairs after the dictionary is created.
Use CaseLists are used when you need an ordered collection of items, such as when you want to maintain the order of items or need to access items by their position.Dictionaries are used when you need a collection of key-value pairs, such as when you want to look up values by keys or when you need a fast, unordered collection of items.
Common MethodsSome common methods for lists include append(), extend(), insert(), remove(), pop(), sort(), reverse(), and index().Some common methods for dictionaries include keys(), values(), items(), get(), update(), pop(), and clear().

12. What is the difference between a Set and Dictionary in Python?

In Python, Set and Dictionary are both data structures used to store collections of items, but they have different characteristics and use cases. Here are the key differences between them:

SETDICTIONARY
NatureSets are collections of unique elements. Each element in a set must be unique, and sets do not allow duplicate entries.Dictionaries store data in key-value pairs. Each key must be unique, and each key maps to a specific value.
OrderSets are unordered collections. The elements do not have a defined order, and there is no index assigned to any element.As of Python 3.7, dictionaries maintain the insertion order of keys. This means that when you iterate over a dictionary, the keys will be returned in the order they were added.
DuplicatesSets do not allow duplicate elements. Adding a duplicate element to a set will not change the set.Dictionaries do not allow duplicate keys. If you assign a new value to an existing key, the old value is overwritten. However, values can be duplicated.
Indexing and SlicingSets do not support indexing, slicing, or other sequence-like behavior because they are unordered.Instead of accessing elements by their position, dictionaries allow you to access elements by their keys.
MutableSets are mutable, meaning that elements can be added or removed after the set is created. However, the elements themselves must be immutable (e.g., numbers, strings, tuples).Dictionaries are mutable, meaning that you can change, add, or remove key-value pairs after the dictionary is created.
Use CaseSets are used when you need a collection of unique items, and order does not matter. They are particularly useful for membership testing and eliminating duplicate entries.Dictionaries are used when you need a collection of key-value pairs, such as when you want to look up values by keys or when you need a fast, unordered collection of items.
Common MethodsSome common methods for sets include add(), remove(), discard(), pop(), clear(), union(), intersection(), difference(), and issubset().Some common methods for dictionaries include keys(), values(), items(), get(), update(), pop(), and clear().