DocsStation
DSA with Python

Python Interview Questions and Answers – Top 15 Questions for Freshers

By csestudy247 Updated December 2, 2026 16 min read
16 min read

Introduction

Python is one of the most popular programming languages used in web development, automation, data science, artificial intelligence, machine learning, and software development.

For Python developer interviews, recruiters commonly ask questions about Python fundamentals, data types, memory management, operators, modules, and coding practices.

This documentation covers 15 important Python interview questions with clear explanations and practical examples. It is useful for freshers, students, and candidates preparing for Python developer interviews.

1. What is Python? What are the benefits of using Python?

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

Python is widely used in:

  • Web development
  • Artificial Intelligence and Machine Learning
  • Data Science and Data Analysis
  • Automation and scripting
  • Software development
  • API development

Benefits of Python

  1. Easy to learn: Python has simple and readable syntax.
  2. Open source: Python is freely available.
  3. Cross-platform: Python programs can run on Windows, Linux, and macOS.
  4. Large library ecosystem: Python provides many built-in modules and third-party packages.
  5. Dynamic typing: Variables do not require explicit type declarations.
  6. Automatic memory management: Python manages memory automatically.
  7. Rapid development: Its concise syntax helps developers build applications quickly.
  8. Community support: Python has a large developer community.

Example:

name = "Python"
print("Hello", name)

Output:

Hello Python

2. What is a dynamically typed language?

A dynamically typed language is a programming language in which variable types are determined during program execution rather than being explicitly declared before execution.

Python is dynamically typed. You do not need to specify the data type when creating a variable.

Example:

x = 10
print(type(x))

x = "Hello"
print(type(x))

Output:

<class 'int'>
<class 'str'>

The same variable can refer to an integer and later to a string.

Static typing vs Dynamic typing

Static typingDynamic typing
Types are checked before execution in statically typed systems.Types are checked during execution.
Variable types are generally declared or inferred under static rules.Variables do not need explicit type declarations.
Example: Java, C++Example: Python, JavaScript

Is Python strongly typed?

Yes. Python is dynamically typed and strongly typed.

For example:

print("1" + 2)

Output:

TypeError

Python does not automatically combine a string and an integer in this operation.

3. What is an interpreted language?

An interpreted language is commonly described as a language whose program execution involves an interpreter or runtime environment.

Python is often called an interpreted language.

In CPython, the most widely used Python implementation, source code is first compiled into bytecode. The Python virtual machine then executes that bytecode.

Example:

print("Hello")
print("Welcome to Python")

Output:

Hello
Welcome to Python

Examples of commonly interpreted languages

  • Python
  • JavaScript
  • Ruby
  • PHP

Interview note: Saying Python executes source code strictly line by line is an oversimplification. Its actual execution process includes compilation to bytecode and execution by the Python runtime.

4. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal.

A PEP is a document that describes proposed features, processes, or guidelines related to Python.

PEP 8 is the official Python style guide. It provides recommendations for writing readable and consistent Python code.

Important PEP 8 guidelines

1. Use four spaces for indentation.

if True:
    print("Hello")

2. Use meaningful variable names.

student_name = "Rahul"

3. Use lowercase names with underscores for functions.

def calculate_total():
    pass

4. Use uppercase names for constants.

MAX_LIMIT = 100

5. Keep lines within the recommended length.

PEP 8 recommends a maximum of 79 characters for code lines.

Why is PEP 8 important?

  • Improves code readability.
  • Maintains coding consistency.
  • Makes collaboration easier.
  • Helps developers maintain code.
  • Encourages professional coding practices.

5. What are the common built-in data types in Python?

Python provides several built-in data types to store and manipulate different kinds of values.

They can be grouped into the following categories.

1. None Type

None represents the absence of a value.

x = None
print(type(x))

Output:

<class 'NoneType'>

2. Numeric Types

Python provides three main numeric types:

  • int – Integer numbers
  • float – Floating-point numbers
  • complex – Complex numbers
a = 10
b = 10.5
c = 2 + 3j

print(type(a))
print(type(b))
print(type(c))

3. Boolean Type

Boolean values represent logical truth values: True and False.

is_active = True
print(type(is_active))

Output:

<class 'bool'>

Boolean is a subclass of integer in Python.

4. Sequence Types

Sequence types store ordered collections of values.

  • str – String
  • list – List
  • tuple – Tuple
  • range – Range object
name = "Python"
numbers = [1, 2, 3]
values = (10, 20, 30)
r = range(5)

5. Mapping Type

The dictionary (dict) stores data as key-value pairs.

student = {
    "name": "Rahul",
    "age": 22
}

print(student["name"])

Output:

Rahul

6. Set Types

Python provides two built-in set types:

  • set – Mutable collection of unique elements.
  • frozenset – Immutable set.
numbers = {1, 2, 3, 3}
print(numbers)

frozen = frozenset([1, 2, 3])

7. Callable Types

Callable objects can be called using parentheses. Examples include functions, methods, and classes.

def greet():
    print("Hello")

greet()

Checking data types

Python provides type() and isinstance().

x = 10

print(type(x))
print(isinstance(x, int))

Output:

<class 'int'>
True

6. Explain the ternary operator in Python.

The ternary operator is a shorthand way of writing a simple if-else expression.

Python uses the following syntax:

value_if_true if condition else value_if_false

Example 1: Find the minimum number

a = 2
b = 3

minimum = a if a < b else b

print(minimum)

Output:

2

Example 2: Check whether a number is even or odd

num = 10

result = "Even" if num % 2 == 0 else "Odd"

print(result)

Output:

Even

Example 3: Conditional printing

a = 14
b = 12

print("Hi") if a < b else print("Bye")

Output:

Bye

Interview note: Python does not use the ?: syntax found in languages such as C and C++. It uses the conditional expression syntax shown above.

7. What does the is operator do?

The is operator is an identity operator in Python. It checks whether two variables refer to the same object in memory.

Python provides two identity operators:

  • is
  • is not

Example 1: Same object

a = [1, 2, 3]
b = a

print(a is b)

Output:

True

Both variables refer to the same list object.

Example 2: Different objects with equal values

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)
print(a is b)

Output:

True
False

The lists contain equal values, but they are different objects.

Checking object identity using id()

Python provides the id() function to return an object’s identity.

a = 10

print(id(a))

The exact identity value depends on the execution environment.

8. What are the disadvantages of Python?

Python is powerful and easy to use, but it also has some limitations.

1. Slower execution speed

Python can be slower than compiled languages such as C and C++ for CPU-intensive operations.

2. Higher memory consumption

Some Python applications can consume more memory than equivalent implementations in lower-level languages.

3. Not ideal for every mobile application

Python has mobile development frameworks, but it is less commonly used for native mobile development than languages such as Kotlin and Swift.

4. Runtime errors

Because Python is dynamically typed, some type-related errors are discovered only when the relevant code executes.

5. Global Interpreter Lock in CPython

In standard GIL-enabled CPython builds, the Global Interpreter Lock (GIL) limits how many threads can execute Python bytecode simultaneously. This can affect CPU-bound multithreaded programs.

6. Dependency management

Large projects may require careful management of packages, environments, and dependency versions.

Interview note: Python’s disadvantages depend on the application. Its extensive libraries and development speed make it a strong choice for many projects.

9. How are strings stored in Python?

A string in Python is an immutable sequence of Unicode characters.

Python strings are objects. A variable referring to a string stores a reference to that object rather than storing the entire string directly inside the variable.

Example:

s = "Python"

print(s)
print(id(s))

Important characteristics of Python strings

  1. Strings are immutable.
  2. Strings support Unicode characters.
  3. Strings are ordered sequences.
  4. Characters can be accessed using indexing.
  5. Strings support slicing.
  6. Strings can be concatenated and repeated.

String immutability example

s = "hello"

s[0] = "H"

Output:

TypeError

You cannot modify an individual character in an existing string.

Instead, create a new string:

s = "hello"
s = "H" + s[1:]

print(s)

Output:

Hello

How are strings represented internally?

In CPython, strings use an internal Unicode representation that can use different storage widths depending on the characters in the string.

This is part of CPython’s implementation and should not be confused with a universal memory layout for every Python implementation.

10. What is the Zen of Python?

The Zen of Python is a collection of guiding principles for writing Python programs.

It describes the philosophy behind Python’s design and encourages readable, simple, and maintainable code.

You can display it by importing the this module.

import this

The 19 principles of the Zen of Python

  1. Beautiful is better than ugly.
  2. Explicit is better than implicit.
  3. Simple is better than complex.
  4. Complex is better than complicated.
  5. Flat is better than nested.
  6. Sparse is better than dense.
  7. Readability counts.
  8. Special cases aren’t special enough to break the rules.
  9. Although practicality beats purity.
  10. Errors should never pass silently.
  11. Unless explicitly silenced.
  12. In the face of ambiguity, refuse the temptation to guess.
  13. There should be one– and preferably only one –obvious way to do it.
  14. Although that way may not be obvious at first unless you’re Dutch.
  15. Now is better than never.
  16. Although never is often better than right now.
  17. If the implementation is hard to explain, it’s a bad idea.
  18. If the implementation is easy to explain, it may be a good idea.
  19. Namespaces are one honking great idea — let’s do more of those!

Why is the Zen of Python important?

  • Encourages readable code.
  • Promotes simplicity.
  • Helps maintain consistency.
  • Supports better software design.
  • Reflects Python’s programming philosophy.

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

Both operators compare objects, but they perform different operations.

is operator== operator
Checks object identity.Checks value equality.
Determines whether two references point to the same object.Determines whether two objects have equal values.
Identity operator.Equality operator.

Example

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)
print(a is b)

Output:

True
False

Example using list assignment

s = [1, 2, 3]

p = s
q = s[:]

print("id of p:", id(p))
print("id of s:", id(s))
print("id of q:", id(q))

print("s == q:", s == q)
print("s is q:", s is q)

print("s == p:", s == p)
print("s is p:", s is p)

Explanation:

  • p = s makes both variables refer to the same list.
  • q = s[:] creates a separate list containing the same elements.
  • Therefore, s == q is True, but s is q is False.
  • Both s == p and s is p are True.

Important interview point

Use == when comparing values and is when checking object identity. For example, use is None when checking whether a variable is None.

value = None

if value is None:
    print("No value")

12. What does the underscore (_) variable represent in Python?

The underscore (_) has several uses in Python. One common use is to indicate a value that is intentionally ignored.

It is often called a throwaway variable.

1. Ignore a value during unpacking

x, _, y = (1, 2, 3)

print("x:", x)
print("y:", y)

Output:

x: 1
y: 3

The second value is assigned to _ because it is not needed.

2. Ignore the loop variable

Suppose you want to print "Hello" five times but do not need the loop index.

for _ in range(5):
    print("Hello")

Output:

Hello
Hello
Hello
Hello
Hello

Other uses of underscore

  • _ is used in interactive Python environments to refer to the previous result in some interpreters.
  • A leading underscore in a variable name, such as _name, conventionally indicates an internal or non-public name.
  • Double leading underscores in class attributes can trigger name mangling.

Interview note: _ is not a special keyword in ordinary variable assignments. It is a normal identifier with conventional uses.

13. What is the difference between modules, packages, and libraries?

Python uses modules, packages, and libraries to organize and reuse code.

1. Module

A module is a Python file containing code such as functions, classes, and variables that can be imported into another Python file.

Example:

Create a file named calculator.py.

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

Import the module:

import calculator

print(calculator.add(10, 20))

Output:

30

2. Package

A package is a way of organizing related modules into a directory structure.

Example:

my_package/
    __init__.py
    calculator.py
    geometry.py

Import a module:

from my_package import calculator

The __init__.py file is commonly used to mark and initialize regular packages. Modern Python also supports namespace packages without this file.

3. Library

A library is a broader collection of reusable code that provides functionality for specific tasks.

Examples:

  • NumPy – Numerical computing.
  • Pandas – Data manipulation and analysis.
  • Matplotlib – Data visualization.
  • Requests – HTTP requests.

Difference between module, package, and library

ModulePackageLibrary
A Python file containing reusable code.A way to organize related modules.A broader collection of reusable code.
Usually a single .py file.Usually a directory structure.May contain many modules and packages.
Example: mathExample: emailExample: NumPy

Interview note: The terms module, package, and library are sometimes used loosely in everyday Python discussions.

14. Why is 0.3 - 0.2 not equal to 0.1 in Python?

This happens because computers represent most floating-point numbers using binary floating-point arithmetic.

Some decimal fractions cannot be represented exactly in binary. Therefore, small rounding differences can appear during calculations.

Example

print(0.3 - 0.2)
print(0.3 - 0.2 == 0.1)

Output:

0.09999999999999998
False

The result is very close to 0.1, but it is not exactly equal.

Why does this happen?

Computers commonly use the IEEE 754 floating-point standard.

Floating-point values are represented in binary rather than decimal. Some decimal values have repeating binary representations, resulting in small precision errors.

How to compare floating-point numbers?

Use math.isclose() when approximate equality is appropriate.

import math

a = 0.3 - 0.2
b = 0.1

print(math.isclose(a, b))

Output:

True

How to perform exact decimal calculations?

Use Python’s decimal module when decimal arithmetic is required, such as in financial calculations.

from decimal import Decimal

a = Decimal("0.3")
b = Decimal("0.2")

print(a - b)
print(a - b == Decimal("0.1"))

Output:

0.1
True

Important: Use strings when constructing Decimal values to avoid introducing an earlier floating-point approximation.

15. What are Python docstrings?

A docstring is a string literal used to document a module, function, class, or method.

Docstrings explain what a particular part of the program does and how it should be used.

They are generally written as the first statement inside the documented object.

Example 1: Function docstring

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

print(add(10, 20))

Output:

30

Example 2: Access a docstring using __doc__

Python provides the __doc__ attribute to access an object’s documentation string.

def greet():
    """Display a greeting message."""
    print("Hello")

print(greet.__doc__)

Output:

Display a greeting message.

Example 3: Built-in function docstrings

Built-in functions also provide documentation.

print(input.__doc__)

This displays the documentation string for Python’s built-in input() function.

Similarly:

print(type.__doc__)

This displays documentation for the built-in type() function.

Example 4: Class docstring

class Student:
    """Represent a student."""

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

print(Student.__doc__)

Output:

Represent a student.

Types of docstrings

  1. Module docstring – Describes a Python module.
  2. Class docstring – Describes a class.
  3. Function docstring – Describes a function.
  4. Method docstring – Describes a class method.

Why are docstrings important?

  • Explain the purpose of code.
  • Improve code readability.
  • Help developers understand functions and classes.
  • Support automatic documentation tools.
  • Make projects easier to maintain.

Additional Important Python Interview Concepts

The uploaded notebook also contains a few related examples and notes worth reviewing.

A. Operator precedence in Python

Operator precedence determines the order in which Python evaluates expressions.

Example:

result = 10 + 5 * 2

print(result)

Output:

20

Multiplication is performed before addition.

Parentheses can be used to control evaluation order:

result = (10 + 5) * 2

print(result)

Output:

30

B. Python object identity and the id() function

The id() function returns an object’s identity during its lifetime.

a = 10
b = a

print(id(a))
print(id(b))
print(a is b)

The two identity values are equal because both variables refer to the same object.

Important: Do not depend on object identity for integer values. Python implementations may reuse certain immutable objects, but that is an implementation detail.

C. String immutability and object identity

s = "have"

print(id(s))

s = s.capitalize()

print(id(s))

The capitalize() method returns a new string. The variable s is then assigned a reference to that new string. The identity values will generally differ.

D. Multiple assignment

Python allows multiple assignments in one statement.

a, b = 10, 20

print(a)
print(b)

Output:

10
20

You can also unpack the results of expressions:

a, b = print("hello"), print("world")

Both print() calls execute and return None, so both a and b receive None.

E. Changing a loop variable inside a loop

for i in range(1, 5):
    i = 3
    print(i, end=" ")

Output:

3 3 3 3

The loop obtains each next value from the iterator, then the assignment changes the local variable i for that iteration.

Python Interview Practice MCQs

Test your understanding with these multiple-choice questions.

1. Which type of language is Python?

A. Statically typed only
B. Dynamically typed
C. Assembly language
D. Machine language

Correct Answer: B. Dynamically typed

2. What does PEP stand for?

A. Python Execution Process
B. Programming Enhancement Process
C. Python Enhancement Proposal
D. Python Environment Program

Correct Answer: C. Python Enhancement Proposal

3. Which operator checks whether two variables refer to the same object?

A. ==
B. !=
C. is
D. in

Correct Answer: C. is

4. What is the output of the following code?

a = [1, 2]
b = a

print(a is b)

A. True
B. False
C. None
D. Error

Correct Answer: A. True

5. Which function is used to check the type of an object?

A. id()
B. type()
C. len()
D. input()

Correct Answer: B. type()

6. Which of the following is a mutable data type?

A. Tuple
B. String
C. List
D. Integer

Correct Answer: C. List

7. What is the output of 10 + 5 * 2?

A. 30
B. 20
C. 25
D. 15

Correct Answer: B. 20

8. Which module provides Decimal?

A. math
B. random
C. decimal
D. statistics

Correct Answer: C. decimal

9. What does _ commonly represent in Python?

A. A class
B. An ignored or unused value
C. A loop keyword
D. A package

Correct Answer: B. An ignored or unused value

10. Which attribute is used to access an object’s docstring?

A. __name__
B. __class__
C. __doc__
D. __type__

Correct Answer: C. __doc__

11. Which statement about Python strings is correct?

A. Strings are mutable
B. Strings are immutable
C. Strings cannot contain Unicode
D. Strings cannot be sliced

Correct Answer: B. Strings are immutable

12. What is the main purpose of PEP 8?

A. Database management
B. Python installation
C. Python coding style guidelines
D. Memory allocation

Correct Answer: C. Python coding style guidelines

13. What is a Python module?

A. A Python file containing reusable code
B. A database
C. An operating system
D. A compiler

Correct Answer: A. A Python file containing reusable code

14. Which operator compares values for equality?

A. is
B. ==
C. and
D. not

Correct Answer: B. ==

15. Which statement about Python’s Decimal class is correct?

A. It is part of the decimal module
B. It is part of the random module
C. It is a loop statement
D. It is an identity operator

Correct Answer: A. It is part of the decimal module

Scroll to Top