October 10, 2026By SevenMentor

Interview Questions and Answers Python

You can spend a week going through Python tutorials and when time comes still freeze to an interviewer asking you to change a few lines of code. This is maybe because your program works with one input but fails with another or something else. Or you know what a function does but struggle to tell it to the interviewer about why you used it. These are the sorts of gaps that become obvious during a technical round, especially when most of your preparation has involved reading answers instead of testing code.

The 25 questions below cover the kind of ground a Python candidate should be comfortable with, from basic data types to object-oriented programming and full-stack development. Don't treat the answers as lines to memorise. Run the examples, change the values and see what happens when you take a different approach. That is where the concepts start making sense.

Working through these questions on your own is a reasonable starting point. But if you keep getting stuck at the same concepts or want to build projects alongside your preparation, take a look at the Python learning options from SevenMentor and its Full Stack Python Course. A course won't do the practice for you. What it can offer is a more structured way to work through the topics and get help when your code refuses to behave as expected.


Section 1: What Python Basic Interview Questions Should Freshers Prepare?

1. What is Python and why do developers use it?

Python shows up in quite different kinds of work. One developer might use it to build a web application, while another writes scripts to clean up files or process a large spreadsheet. It is also widely used in testing, data analysis and AI development. Part of its appeal is that the code is generally readable without sacrificing access to a broad range of libraries.

Imagine having hundreds of files to check for a particular piece of information. Opening them one by one would be tedious. A Python script can handle much of that repetitive work for you. Of course, writing a working script is only the beginning when a project gets bigger. You still need to organise the code, test unusual inputs and work through bugs when they appear.

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

Suppose you're storing the skills a student is learning. You might start with Python and SQL, then add Django a few weeks later. A list suits that situation because you can change its contents after creating it. A tuple works differently: its elements cannot be reassigned once the tuple has been created.

skills = ["Python", "SQL"]

skills.append("Django")


course_topics = ("Python", "SQL", "Django")


print(skills)

print(course_topics)

The first collection changes when append() adds Django. The tuple remains unchanged. In practice, choose a list when you expect to update the collection and consider a tuple when the values should stay fixed.


3. What are Python's main data types?

Common built-in types include:

  • int for whole numbers
  • float for decimal numbers
  • str for text
  • bool for True and False
  • list for ordered mutable collections
  • tuple for ordered immutable collections
  • dict for key-value pairs
  • set for collections of unique values

An interviewer might ask you to choose a suitable type for a situation. If you need to store a student's name alongside their course, a dictionary could work well.

student = {

    "name": "Aarav",

    "course": "Python"

}


print(student["course"])

The output is Python.


4. What is the difference between == and is?

The == operator checks whether two objects have equal values. The is operator checks whether two references point to the same object.

first = [10, 20]

second = [10, 20]


print(first == second)  # True

print(first is second) # False

Both lists contain the same values, but they are separate objects. A common practical use of is is checking whether a variable is None:

if result is None:

    print("No result found")

Remember the distinction. It is an easy question to answer incorrectly when you're rushing.


5. What are mutable and immutable objects?

Mutable objects can be changed after creation. Lists, dictionaries and sets are common examples. Immutable objects cannot have their contents changed in place; strings, integers and tuples are familiar examples.

name = "Python"

name = name + " Developer"

print(name)

This creates a new string and assigns it to name. It does not modify the original string in place.

A list behaves differently:

tools = ["Git", "Python"]

tools.append("SQL")

print(tools)

The existing list is modified. Understanding this difference helps when you pass objects into functions and investigate unexpected changes.


Section 2: Which Python Interview Questions Test Functions and Logic?


6. What is a function in Python?

A function is a reusable block of code that performs a particular task. It helps avoid repeating the same instructions throughout a program.

def calculate_total(price, quantity):

    return price * quantity


print(calculate_total(500, 3))

Output:

1500

The function accepts two arguments and returns their product. In an interview, explain what the function receives, what it does and what it returns. That is more useful than simply memorising the definition.


7. What is the difference between return and print()?

print() displays information on the screen. return sends a value back to the code that called the function.

def add_numbers(a, b):

    return a + b


answer = add_numbers(4, 6)

print(answer)

Here the returned value is stored in answer, so it can be used in another calculation. If the function only printed the result, you could not use that displayed output as its return value.


8. What are *args and **kwargs?

*args lets a function accept a variable number of positional arguments. **kwargs lets it accept a variable number of keyword arguments.

def show_skills(*args):

    for skill in args:

        print(skill)


show_skills("Python", "SQL", "Django")

You could use **kwargs when you want to accept named details:

def show_profile(**kwargs):

    print(kwargs)


show_profile(name="Riya", course="Python")

The second function receives a dictionary-like collection of keyword arguments. These features are useful, but don't add them everywhere just because Python allows them.


9. What is a lambda function?

A lambda is a small anonymous function written as a single expression. It is handy when a short function is needed temporarily.

double = lambda number: number * 2

print(double(7))

Output:

14

You may see lambdas used with functions such as sorted() when you need a custom sorting rule. For complex logic, a regular function with def is usually easier to read and maintain.


10. How do you handle exceptions in Python?

Use try and except to handle errors that may occur while a program runs. You can add else for code that should run when no exception occurs and finally for cleanup that must run either way.

try:

    number = int(input("Enter a number: "))

    print(100 / number)

except ValueError:

    print("Please enter a valid integer.")

except ZeroDivisionError:

    print("The number cannot be zero.")

A good answer should mention why the exception might occur. Avoid catching every possible error with a broad except unless you have a specific reason to do so.


Section 3: What Python OOP Interview Questions Should You Know?


11. What is object-oriented programming in Python?

Object-oriented programming, or OOP, organises code around classes and objects. A class defines the structure and behaviour, while an object is an instance of that class.

class Student:

    def __init__(self, name):

        self.name = name


    def introduce(self):

        print(f"My name is {self.name}")


student = Student("Riya")

student.introduce()

Output:

My name is Riya

This example is small, but the same idea helps organise larger applications with customers, orders, courses or payment records.


12. What does __init__() do in Python?

__init__() is an initializer that runs when an object is created. It is commonly used to set the object's initial attributes.

class Course:

    def __init__(self, title, duration):

        self.title = title

        self.duration = duration


python_course = Course("Python", "12 weeks")

print(python_course.title)

Output:

Python

Technically, __new__() is responsible for creating an instance, while __init__() initializes it. For most beginner interview questions, knowing the role of __init__() is the starting point.


13. What is inheritance in Python?

Inheritance lets one class reuse and extend behaviour from another class. The class being inherited from is usually called the parent or base class.

class Course:

    def show_name(self):

        print("Python Training")


class FullStackCourse(Course):

    def show_topics(self):

        print("Python, Django and SQL")


course = FullStackCourse()

course.show_name()

course.show_topics()

The child class can use show_name() without defining it again. It can also add its own methods. In real projects, inheritance is useful when classes share a genuine relationship, not simply to avoid writing a few extra lines.



14. What is polymorphism in Python?

Polymorphism allows different objects to respond to the same operation in their own way.

class OnlineCourse:

    def access(self):

        print("Access through the learning portal")


class ClassroomCourse:

    def access(self):

        print("Access through classroom sessions")


for course in [OnlineCourse(), ClassroomCourse()]:

    course.access()

Both objects have an access() method, but each behaves differently. This can make applications easier to extend because the calling code does not need a separate instruction for every class.


15. What is the difference between instance, class and static methods?

An instance method receives self and works with a particular object's state. A class method receives cls and works with the class itself. A static method receives neither automatically and is often used for related utility logic.

class Learner:

    institute = "SevenMentor"


    def __init__(self, name):

        self.name = name


    def show_name(self):

        return self.name


    @classmethod

    def show_institute(cls):

        return cls.institute


    @staticmethod

    def course_area():

        return "Programming"

The example uses SevenMentor as a sample institute value. In an actual application, such details would normally come from configuration or stored records rather than being hard-coded.


Section 4: Which Intermediate Python Questions Often Catch Candidates Out?


16. What is a list comprehension?

A list comprehension creates a list using an expression and an iterable. It can be a neat alternative to a basic loop when the transformation is straightforward.

numbers = [1, 2, 3, 4, 5]

squares = [number ** 2 for number in numbers if number % 2 == 0]


print(squares)

Output:

[4, 16]

Only even numbers are included and each is squared. If a comprehension becomes difficult to understand at a glance, a normal loop may be the better choice.


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

A shallow copy creates a new outer object but keeps references to nested objects. A deep copy recursively copies nested objects as well.

import copy


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

shallow = copy.copy(original)

deep = copy.deepcopy(original)


original[0].append(99)


print(shallow)

print(deep)

Output:

[[1, 2, 99], [3, 4]]

[[1, 2], [3, 4]]

The shallow copy reflects the change inside the nested list because both outer lists refer to that same inner list. The deep copy has its own nested copy.


18. What is a generator in Python?

A generator produces values one at a time instead of building the entire result in memory upfront. Generator functions use yield.

def count_up_to(limit):

    number = 1

    while number <= limit:

        yield number

        number += 1


for value in count_up_to(3):

    print(value)

Output:

1

2

3

Generators are useful when processing large amounts of data because values can be handled as they are produced. Keep in mind that a generator is generally consumed as you iterate through it.


19. What is a decorator in Python?

A decorator wraps a function to add behaviour without changing the function's main code. Decorators are often used for logging, timing, access checks and other reusable operations.

def announce(func):

    def wrapper():

        print("Starting task")

        func()

    return wrapper


@announce

def greet():

    print("Hello")


greet()

Output:

Starting task

Hello

The @announce syntax applies the decorator to greet. In production code, decorators often use functools.wraps and accept *args and **kwargs so they preserve function metadata and support different function signatures.


20. What is the difference between a module and a package?

A module is usually a single Python file containing code such as functions, classes or variables. A package groups related modules into a directory structure so a larger application can be organised into manageable parts.

For example, a web application might have separate modules for user accounts, payments and notifications. Grouping these sensibly makes the project easier to maintain as it grows.

If you're preparing for Python full-stack interviews, this is where theory should connect with a real project. A Django application has multiple files working together, and you should be able to explain why code belongs in a particular module instead of placing everything in one large file.

SevenMentor's Full Stack Python Course is one option to explore if you want structured practice with Python and web development rather than stopping at isolated syntax examples.


Section 5: What Python Interview Questions Matter for Real Projects?


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

In traditional CPython builds, the Global Interpreter Lock restricts how multiple threads execute Python bytecode at the same time within one interpreter. This can limit the benefit of threads for CPU-heavy Python work, though threads can still help with I/O-bound tasks.

Python's threading behaviour depends on the implementation and version, and modern CPython also has optional free-threaded builds. A careful interview answer avoids claiming that every Python program can only ever use one CPU core.


22. How do you read a file safely in Python?

Use a with statement when opening a file. It handles closing the file when the block finishes, including when an error occurs.

with open("notes.txt", "r", encoding="utf-8") as file:

    content = file.read()


print(content)

For a large file, reading everything at once may consume too much memory. You can process it line by line instead:

with open("notes.txt", encoding="utf-8") as file:

    for line in file:

        print(line.rstrip())

Be prepared to explain what happens if the file does not exist. Depending on the application, you might handle FileNotFoundError or show the user a useful message.


23. How would you connect Python to a database?

Python applications commonly use database drivers or libraries to communicate with databases. The exact method depends on the database and the framework.

For example, a database query should use parameters rather than inserting raw user input into a SQL string. With a driver that supports %s placeholders, the code might look like this:

cursor.execute(

    "SELECT name FROM students WHERE student_id = %s",

    (student_id,)

)

The placeholder format varies by database driver. Parameterized queries help protect against SQL injection and avoid treating user input as executable SQL. Never assume the placeholder syntax is identical across every Python database library.


24. How can you make Python code faster?

Start by finding out what is actually slow. Guessing can waste time, and rewriting a working function without measuring it may not help.

A sensible approach is to:

  • Profile the code to identify the bottleneck.
  • Avoid repeating expensive calculations unnecessarily.
  • Choose appropriate data structures.
  • Use database queries efficiently instead of fetching data repeatedly.
  • Process large inputs in chunks or with generators where suitable.
  • Add caching only when repeated work makes it worthwhile.

Suppose a report takes 40 seconds to run because it queries a database inside a loop. Reworking the query may help far more than replacing a few Python statements with shorter syntax. Interviewers often want to hear how you would investigate the issue, not just a list of optimisation tricks.


25. How do you explain a Python project in an interview?

Pick a project you can explain without relying on a memorised speech. Describe the problem, your approach, the main technical decisions and one issue you had to solve. If you worked on a Django application, for instance, you could explain how a request reaches a view, how data is retrieved and how the response is returned.

You can also use a small Python program to demonstrate variables, calculations and formatted output. The following example uses hypothetical salary figures to show how Python handles a simple comparison. These amounts are illustrative only. They are not SevenMentor salary data or a promise that training will lead to a particular package.

institute = "SevenMentor"

role = "Python Developer"


salary_a = 300000

salary_a_with_training = 420000


difference = salary_a_with_training - salary_a


print(f"{institute} offers Python learning and training options.")

print(f"Role: {role}")

print(f"Illustrative salary A: Rs. {salary_a:,} per year")

print(

    "Illustrative salary A with additional training: "

    f"Rs. {salary_a_with_training:,} per year"

)

print(f"Illustrative difference: Rs. {difference:,} per year")

Example output:

SevenMentor offers Python learning and training options.

Role: Python Developer

Illustrative salary A: Rs. 300,000 per year

Illustrative salary A with additional training: Rs. 420,000 per year

Illustrative difference: Rs. 120,000 per year

The point of this example is the code, not the salary figures. Completing a course does not automatically raise someone's salary. Actual offers depend on experience, technical ability, interview performance, location and the employer.

If you're considering formal training, look at the syllabus and practical work offered by SevenMentor and decide whether it fits the skills you need to build. Be ready to show your own programs and explain the decisions behind them.


How Should You Practise Before a Python Interview?

Don't try to memorise all 25 answers word for word. Read a question, close the page and explain the answer in your own words. Then run the example and change something: pass a different argument, give the program unexpected input or remove a line to see what breaks.

For the coding questions, practise writing the solution without copying it. For OOP and intermediate topics, prepare a small example of your own. If an interviewer asks a follow-up question, your understanding matters more than remembering the exact wording of a definition.

You can use these questions as a revision checklist and explore SevenMentor's Python interview preparation resources for further practice. If you are aiming for a full-stack role, make time for SQL, HTTP basics, Django and project-based questions as well.

A Python interview is rarely about knowing every feature in the language. It is about showing that you can work through a problem, explain your reasoning and write code another developer can understand.

SevenMentor

Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.

#Technology#Education#Career Guidance