Python Interview Questions - Basics
Master the most common Python interview questions covering foundations, data types, and core concepts.
Master the most common Python interview questions covering foundations, data types, and core concepts. This interview-focused guide covers essential python interview questions - basics concepts for technical interviews.
Python Interview Questions – Level 0: Basics
This section covers the absolute essentials of Python. These are the building blocks you must master for any Python role or technical assessment.
1. What is Python?
Python is a high-level, interpreted, general-purpose programming language. It was designed with a focus on code readability, and its syntax allows programmers to express concepts in fewer lines of code compared to languages like C++ or Java.
[!NOTE] Key Paradigms: It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
2. Who created Python?
Python was created by Guido van Rossum and was first released in 1991. He is often referred to as the "Benevolent Dictator For Life" (BDFL), although he stepped down from that role in 2018.
3. Why is Python called an interpreted language?
Python is called an interpreted language because its code is executed line-by-line by an interpreter, rather than being compiled into machine code before execution.
[!TIP] Interview Secret: While we call it "interpreted," Python actually performs a hidden compilation step. It compiles source code into bytecode (
.pycfiles) first, which is then executed by the Python Virtual Machine (PVM). This makes it faster than purely interpreted languages.
4. What are the features of Python?
- Easy to read and learn: Uses clear, English-like syntax.
- Interpreted: Direct execution of code without traditional compilation steps.
- Dynamically Typed: You don't need to declare variable types (e.g.,
int x = 5). - Standard Library: Batteries included! A massive library for everything from regex to web servers.
- Extensible: You can write modules in C/C++ for performance-critical tasks.
- Portable: Write once, run anywhere (Windows, Mac, Linux).
5. What is a variable?
A variable in Python is not a "box" that stores a value, but rather a label or reference to an object in memory.
[!IMPORTANT] When you say
x = 5,xis a name that points to an integer object5created in memory.
6. How do you assign a value to a variable?
You use the assignment operator (=). Python also supports multiple assignments in a single line:
x, y, z = 10, 20, 30
a = b = c = "Same Value"
7. What are Python keywords?
Keywords are reserved words that form the skeleton of the language. They cannot be used as identifiers (variable names, function names, etc.).
- There are currently 35+ keywords (e.g.,
async,await,yield,None).
8. How do you check Python keywords?
Use the built-in keyword module:
import keyword
print(keyword.kwlist)
9. What are comments in Python?
Comments are used to document code and prevent execution of specific lines.
- Best Practice: Use comments to explain why something is done, not what is done (the code should be readable enough to show the "what").
10. Single-line vs multi-line comments?
- Single-line: Uses
#. - Multi-line: Technically, Python doesn't have a specific multi-line comment syntax like
/* ... */in C. Instead, developers use triple quotes ('''or""") which are actually string literals that aren't assigned to any variable.
# Single line
"""
Multi-line
Docstrings are also created this way!
"""
11. What is indentation and why is it important?
Indentation in Python is not just for style; it is a syntax requirement. It is used to define the scope of code blocks (loops, functions, classes).
[!CAUTION] Pro Tip: While you can use any number of spaces, PEP 8 strictly recommends using 4 spaces per level. Mixing tabs and spaces will result in a
TabError.
12. What are literals?
Literals are direct values assigned to variables. They tell the interpreter exactly what data is being used.
- String Literals:
"Text"or'Text' - Numeric Literals:
10,10.5,3+4j - Boolean Literals:
True,False - Collection Literals:
[1, 2],(1, 2),{"a": 1}
13. What is dynamic typing?
Dynamic typing means the data type of a variable is determined at runtime, not compile-time. You don't declare types; Python infers them.
[!TIP] Edge Case: This makes Python flexible but can lead to bugs if you're not careful. This is why Type Hinting (added in Python 3.5+) is becoming so popular:
def greet(name: str) -> None:.
14. What is type() used for?
The type() function is used to inspect the class of an object.
x = [1, 2]
print(type(x)) # <class 'list'>
15. What are built-in data types?
Python has several categories of built-in types:
- Numeric:
int,float,complex - Sequence:
list,tuple,range,str - Mapping:
dict - Set Types:
set,frozenset - Boolean:
bool - Binary:
bytes,bytearray
16. What is input()?
The input() function allows user interaction via the console.
[!WARNING] Interview Trap: In Python 3,
input()always returns a string. If you need a number, you must cast it:age = int(input("Age: ")).
17. What is print()?
Outputs data to the standard output device (console).
- Cool Feature: You can change the separator and the end character.
print("A", "B", sep="|", end="!!!")
# Output: A|B!!!
18. What is Python REPL?
REPL (Read-Eval-Print Loop) is the interactive shell. It's perfect for testing short snippets without creating a file. You access it by just typing python in your terminal.
19. What is PEP 8?
PEP 8 is the "Style Guide for Python Code". Its goal is to improve the readability of code across the community.
- Naming:
snake_casefor variables,PascalCasefor classes. - Line Length: Max 79 characters.
20. How do you install Python?
Download from python.org.
[!IMPORTANT] Windows Note: Always check the box "Add Python to PATH" during installation. This allows you to run
pythonfrom any terminal window.
21. Difference between Python 2 and Python 3?
The main differences include:
- Print: Python 2:
print "hello", Python 3:print("hello"). - Division: In Python 2,
5/2is2(integer division). In Python 3,5/2is2.5(float division). - Unicode: Python 3 stores strings as Unicode by default; Python 2 uses ASCII.
- Range: Python 3's
range()is like Python 2'sxrange()(it's a generator).
22. What is whitespace?
Whitespace refers to any character representing horizontal or vertical space. In Python, indentation whitespace is syntactically significant.
23. What is None?
None is a special constant representing the absence of a value. It is an object of the NoneType class.
[!NOTE]
Noneis not the same as0,False, or an empty string. It is its own distinct entity.
24. What is pass?
The pass statement is a null operation. It is used as a placeholder when a statement is syntactically required but you don't want to execute any code.
def todo_function():
pass # I'll write this later!
25. What is id()?
The id() function returns the unique memory address of an object. In CPython, this is the address in RAM.
26. What is help()?
The help() function invokes the built-in help system. It's used to view the docstrings of modules, classes, and functions.
27. What is dir()?
The dir() function returns a list of all attributes and methods available for an object. It's a great way to "peek inside" a library or object.
28. What is the use of __name__?
__name__ is a special built-in variable.
- If you run a script directly:
__name__ == "__main__". - If you import a script:
__name__is set to the filename.
[!TIP] This is used to create scripts that can be both imported as modules and run as standalone programs.
29. What is memory management in Python?
Memory in Python is managed automatically via:
- Private Heap: All objects are stored here.
- Python Memory Manager: Handles allocation and deallocation.
- Garbage Collector: Reclaims memory from unused objects.
30. What is garbage collection?
Python uses two main techniques for garbage collection:
- Reference Counting: Deletes an object when the number of references to it reaches zero.
- Generational GC: Handles "circular references" (where two objects point to each other) that reference counting can't solve.
31. What are mutable and immutable types?
- Mutable: Can be changed after creation (
list,dict,set). - Immutable: Cannot be changed after creation (
int,float,str,tuple).
[!IMPORTANT] Interview Question: "Why are strings immutable?" Answer: For security, performance (string interning), and because they are often used as dictionary keys (which must be unchangeable).
32. What is bytecode?
Python code is first compiled into bytecode (intermediate code) before being executed by the PVM. This bytecode is stored in .pyc files found in the __pycache__ folder.
33. What is the Python shell?
The interactive interpreter where you can type code and see immediate results.
34. What is a script?
A file containing Python code (usually with a .py extension) intended to be executed from top to bottom.
35. How to check Python version?
- Terminal:
python --version - Code:
import sys; print(sys.version)
36. What is virtual environment?
A tool used to keep the dependencies required by different projects separate by creating isolated spaces for them. It avoids the "it works on my machine but not yours" problem.
37. What is pip?
pip (Pip Installs Packages) is the package installer for Python. You can use it to install libraries from the Python Package Index (PyPI).
38. What is an interpreter?
A program that executes code directly, line-by-line, translating high-level code into something the computer understands on the fly.
39. What are expressions?
An expression is any piece of code that evaluates to a value.
5 + 5 is an expression.
40. What are statements?
A statement is a logical instruction that performs an action.
x = 10 is a statement.