TestGorilla LogoTestGorilla Logo

16 basic Python interview questions (and answers)


Python is one of the most widely used programming languages in the world. Hiring a skilled Python developer can deliver huge benefits for your company, such as streamlining code development and ensuring you’re always able to deliver top-quality work to your clients. 

Asking specific questions in an interview lets you hone in on the right candidate and reduces the risk of a mis-hire

Employing the wrong person can lead to a range of issues, such as poor-quality code, missed deadlines, and a poor coding style. This can negatively impact your company’s productivity and reputation, and you might lose clients if you can’t meet deadlines. 

Basic Python interview questions are a helpful addition to your hiring process and enable you to hire with confidence. You can gauge an applicant's skill level and select the most appropriate individual for your open position. 

Here are 16 example questions, along with high-level answers that you can use for inspiration.

16 basic Python interview questions and answers

We’ve put together the following list of basic Python interview questions with sample answers. Bear in mind these answers are only examples, and there is often more than one way to solve a problem using Python. 

1. What is Python and what are its applications? 


Python is a high-level, interpreted programming language that’s widely used across a range of domains. It’s known for its simplicity, versatility, and readability, which has made it one of the world’s most popular languages. 

Another reason for this is the large range of libraries and frameworks available with Python. There are countless tools available to help developers work more efficiently. Some of Python’s most common applications include: 

  • Web app development through frameworks like Flask and Django

  • Scientific computing, including simulations and modeling

  • Data analysis with the assistance of libraries like Matplotlib and NumPy

  • Game development

  • Web scraping to extract large amounts of information from websites

  • Machine learning and AI 

Overall, Python is an extremely versatile language that can be adapted to suit numerous situations. 

2. Explain what the # symbol does in Python.


In Python, the # symbol enables you to add comments to your code. These are pieces of text that aren’t executed. Instead, they usually provide an explanation of how the code works, making it easier for human readers to understand. 

You can also use comments to temporarily disable code. This is particularly useful for troubleshooting and bug fixes. Here’s an example of what a comment looks like: 

# This is a single-line comment

print("Hello, world!")  # This is also a comment

In this example, print(“Hello, world!”) is the only code that will be executed. 

3. What are lists in Python? How are they used?


In Python, lists are a commonly used data structure that lets you store a set of items. They are versatile, ordered, and modifiable. What’s more, lists can contain various data types including numbers, strings, and other objects. 

You can define a list with square brackets, [ ], separating elements with a comma. Here’s what it looks like: 

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

This example would create a list containing the numbers 1, 2, 3, 4, and 5, in that order. Python also has built-in list methods and operations that enable you to modify lists and perform other tasks, such as searching for a specific list element. 

4. Tell me what you understand about variables in Python.


A variable is a term used to refer to a value stored in memory. Variables hold data such as strings, numbers, objects, and more. By using variables, you can manipulate and reference data without having to use the actual values. This helps developers keep their code tidy and makes it easier to work with complex data. 

Variables are created by assigning a name to a value using the = operator. They can only contain numbers, letters, and underscores. They can’t start with a number, and they can’t be a Python-reserved word. 

Here’s an example of how to create and use variables: 

birth_year = 1998

current_year = 2023

age = current_year - birth_year

In this example, we’ve created three variables: birth_year, current_year, and age

5. What are modules in Python? 


A Python module is a file containing Python code. This is often in the form of functions, classes, and/or variables that can be referenced and used in other programs. 

One key benefit of modules is that they enable you to organize your code into separate files, streamlining management and making it easier to reuse code multiple times. 

To create a new module, simply create a Python file with the .py extension and start adding your code. You can import modules to take advantage of their functions, classes, and variables. This lets you use their code in your own module without having to write it yourself. 

Here’s an example of a simple module that defines an add and a subtract function: 

def add(a, b):

    return a + b

def subtract(a, b):

    return a - b

You could save this module under the name, maths_functions, for example, and import it to use the add and subtract functions in your code. 

6. What is a namespace and what types of namespaces are there?


A Python namespace is a container that holds identifiers like variable and function names, along with their corresponding values. They are designed to help you organize and manage your identifiers to avoid naming conflicts within your code. 

In Python, there are four main namespaces graphic

In Python, there are four main namespaces: 

  • Built-in namespace. This contains Python’s default functions and is automatically available in every program. 

  • Global namespace. This contains identifiers at the top level which can be used throughout your code. 

  • Enclosing namespace. These namespaces are used in nested functions or code blocks and allow inner functions to access variables from their outer scope. 

  • Local namespace. A local namespace is only available in the block or function where it’s defined and is deleted when execution is complete. 

Namespaces are hierarchical, which means that Python searches for identifiers in a specific order. The local namespace is searched first, followed by any enclosing namespaces, then the global namespace, and finally, the built-in namespace. 

7. Explain, with an example, how you would use Python to delete files.


The easiest way to remove files in Python is with the remove() function, which can be imported from the os module. Before you can use it, you’ll need to define the path of the file you want to delete. 

It’s also a good idea to use a try block to handle any exceptions which can arise if the file doesn’t exist, there are permission errors, or for other reasons. 

This is what this code looks like: 

import os

# Specify the path of the file you want to delete

file_path = "path/to/your/file.txt"


    # Attempt to delete the file


    print(f"{file_path} has been deleted successfully.")

except OSError as e:

    print(f"Error deleting {file_path}: {e}")

In the example, you need to simply replace path/to/your/file.txt with the actual path of the file you want to delete. 

8. What is a boolean?  


A boolean is a Python data type. Booleans can only represent two values, True or False. They are used to represent binary conditions and logical statements, enabling you to control the flow of code through conditional statements and loops. 

Let’s take a look at an example: 

age = 40

if age >= 21:

    print("You are an adult.")


    print("You are a minor.")

In this example, the if age >= 21: statement will return a boolean value. If True, the if statement will execute. If False, the else statement will execute. 

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


PEP 8, or Python Enhancement Proposal 8, is Python’s official coding style guide. It provides clear guidelines that outline the recommended conventions for code layout, naming, comments, and more. Overall, it’s designed to help you write cleaner, readable code. 

What’s more, adhering to PEP 8 standards ensures that your code can easily be understood by other programmers. This makes collaboration much smoother and enables newcomers to use your code with minimal fuss. 

10. Explain your understanding of exception handling in Python.


Using exception handling enables you to smoothly handle any errors or exceptions that occur during code execution. This ensures that your program doesn’t crash when it encounters an error. Instead, it handles the error in a pre-defined manner so that you can take the appropriate action. 

In Python, exception handling is done with the try, except, else, and finally statements. The try block should contain the code that could raise an exception. You can add multiple except blocks, which are executed if the corresponding condition is met. 

The else block is executed if there aren’t any exceptions, and the finally block is always executed. You can also use the raise statement to intentionally raise an exception if the specified conditions are met. 

11. Explain what classes and objects are in Python.


The concept of classes and objects forms the core of Python programming. 

Classes are blueprints or templates that define the structure and behavior of objects. They contain attributes and methods that define how the class will behave, and they form the basis for creating objects with shared behaviors or characteristics. 

Objects, on the other hand, are instances of classes. They are created based on the blueprint in the class and can perform the methods defined in the class. 

12. What are dictionaries in Python? What are they used for? 

Python dictionaries are built-in data structures that store key-value pairs. They store and organize data in an efficient manner and enable you to retrieve values based on their key. Dictionary keys are unique and map to their corresponding value. 

Keys must be a string, number, or tuple. Values can be any data type. Dictionaries should be enclosed with curly brackets, and key-value pairs are separated with colons. 

Here’s an example of what a dictionary looks like: 

Student = {

“Name” : “Matthew”,

“Age” : 22,

“Major” : “Biology”


Now, you can work with and edit your dictionary as required. For example, you can access values with their keys using the following code: 


In this case, the output would be “Matthew”. 

Dictionaries in Python have various uses. They enable fast data retrieval, let you store data in a structured manner, and can be used to represent mapping relationships, among other operations. 

13. Explain when you would use triple quotes in Python. 


In Python, triple quotes are used for creating docstrings and multiline strings. 

Docstrings are like long comments, and enable you to add multiple lines of information to your code without having to mark each one with a # to show that it’s a comment. 

Here’s an example of how docstrings are used: 

def square(n):


Square a number

Input n is the number to be squared

Returns the square of the input number


return n ** 2

In this example, everything between the triple quotes will be treated as a comment and won’t be executed. The return n ** 2 statement will square the input number, n. 

Multiline strings are similar, except that they are executed with your code. They are useful when you need to include line breaks and maintain formatting in long blocks of text. 

Here’s what a multiline string looks like: 

Multiline_string = ‘’’

Multiline strings span several lines.

They can include line breaks.

And you can maintain your formatting.


Here, everything between the triple quotes is treated as a single string.  

14. Show me how you would convert a Python string to lowercase.


The easiest way to convert a Python string to lowercase is using the lower() method. Here’s an example: 

original_string = "I’m A String"

lowercase_string = original_string.lower()

print(lowercase_string)  # Output: "i’m a string"

15. Write a function that determines if a given string is a palindrome.


To do this, we can define a simple is_palindrome function that takes a string, converts it to lowercase, removes non-alphanumeric characters, and then checks whether or not the modified string is a palindrome. 

def is_palindrome(s):

    s = s.lower()  # Convert the string to lowercase

    s = ''.join(e for e in s if e.isalnum())  # Remove non-alphanumeric characters

    return s == s[::-1]  # Check if the string is equal to its reverse

# Test cases

print(is_palindrome("racecar"))    # Output: True

print(is_palindrome("motorbike"))      # Output: False

print(is_palindrome("A man, a plan, a canal, Panama"))  # Output: True

Adding test cases enables you to verify that your function is working correctly. 

16. Write a function that removes duplicates from a list without changing its original order. 


def remove_duplicates_preserve_order(input_list):

    seen = set()

    result = []

    for item in input_list:

        if item not in seen:



    return result

# Test the function

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

output_list = remove_duplicates_preserve_order(input_list)

print(output_list)  # Output: [3, 2, 1, 4, 5]

Read next: 100 Python interview questions

How to assess Python developers to make an informed hire

Python interview questions are a powerful tool that can help you make informed hiring decisions, but they shouldn’t be used alone. They’re most effective when combined as part of a multi-measure screening and interview process. 

TestGorilla offers a range of features to help you identify top talent and make efficient hires. It offers more than 300 pre-employment screening tests, including an array of soft and hard skills tests. You can combine up to five of these with your own custom interview questions to create a well-rounded candidate screening assessment. 

What’s more, TestGorilla enables you to quickly rank test-takers based on their results, ensuring you don’t miss any skilled candidates.

Here are a few of the tests you might like to use when hiring a Python developer: 

When it comes to your custom interview questions, it’s best to select those that relate specifically to the position you’re hiring for. These can be added to your pre-employment screening assessment and/or used during face-to-face interviews. 

Recommended reading: How to assess basic Python skills and hire a developer

How TestGorilla can help you find the best Python developers 

TestGorilla offers a wide range of tools that are designed to help you identify and hire the best applicants for open positions. Using it in conjunction with basic Python interview questions enables you to confidently identify top talent. 

TestGorilla can help you assess candidates’ skills, their ability to use Python in real-world scenarios, and their cultural add. Using interview questions and objective tests can also help remove hiring bias. 

Sign up for TestGorilla’s Free plan today, which gives you the ability to try the tests and familiarize yourself with the user interface.

Alternatively, you can register for a free 30-minute live demo or watch a product tour to find out more. 


Hire the best candidates with TestGorilla

Create pre-employment assessments in minutes to screen candidates, save time, and hire the best talent.

The best advice in pre-employment testing, in your inbox.

No spam. Unsubscribe at any time.

TestGorilla Logo

Hire the best. No bias. No stress.

Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.

Free resources

Anti-cheating checklist

This checklist covers key features you should look for when choosing a skills testing platform

Onboarding checklist

This resource will help you develop an onboarding checklist for new hires.

How to find candidates with strong attention to detail

How to assess your candidates' attention to detail.

How to get HR certified

Learn how to get human resources certified through HRCI or SHRM.

Improve quality of hire

Learn how you can improve the level of talent at your company.

Case study
Case study: How CapitalT reduces hiring bias

Learn how CapitalT reduced hiring bias with online skills assessments.

Resume screening guide

Learn how to make the resume process more efficient and more effective.

Recruiting metrics
Important recruitment metrics

Improve your hiring strategy with these 7 critical recruitment metrics.

Case study
Case study: How Sukhi reduces shortlisting time

Learn how Sukhi decreased time spent reviewing resumes by 83%!

12 pre-employment testing hacks

Hire more efficiently with these hacks that 99% of recruiters aren't using.

The benefits of diversity

Make a business case for diversity and inclusion initiatives with this data.