Published: November 5, 2025
Reading Time: 9 minutes
This comprehensive guide provides 100+ Python coding interview questions ranging from beginner to advanced levels. The article covers:
Python coding challenges test whether you can think like a developer, not just write code. Technical interviews evaluate:
Knowing how to manipulate lists, strings, and dictionaries directly helps in:
Regularly solving Python coding questions improves problem-solving, efficiency, and coding style while preparing you for real-life software tasks, not just interviews.
These questions focus on core concepts including syntax, data structures, and control flow.
Task: Write a simple Python program to print an output.
print("Hello, World!")
Output:
Hello, World!
Task: Write a Python code to check if a number is even or odd.
def is_even(num):
return num % 2 == 0
print(is_even(4)) # True
print(is_even(5)) # False
Task: Write a Python code to concatenate two strings.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Hello World
Task: Write a Python program to find the maximum of three numbers.
def max_of_three(a, b, c):
return max(a, b, c)
print(max_of_three(1, 2, 3)) # 3
Task: Write a Python program to count the number of vowels in a string.
def count_vowels(s):
return sum(1 for char in s if char.lower() in 'aeiou')
print(count_vowels("Hello World")) # 3
Task: Write a Python program to calculate the factorial of a number.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Task: Write a Python code to convert a string to an integer.
str_num = "12345"
int_num = int(str_num)
print(int_num) # 12345
Task: Write a Python program to calculate the area of a rectangle.
def area_of_rectangle(length, width):
return length * width
print(area_of_rectangle(5, 3)) # 15
Task: Write a Python code to check if a number is prime.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print(is_prime(7)) # True
print(is_prime(10)) # False
Task: Write a program to determine whether a number is a palindrome.
def is_palindrome(number):
return str(number) == str(number)[::-1]
print(is_palindrome(121)) # True
print(is_palindrome(123)) # False
Task: Write a program to determine whether a number is an Armstrong number.
def is_armstrong(number):
num_str = str(number)
num_digits = len(num_str)
return number == sum(int(digit) ** num_digits for digit in num_str)
print(is_armstrong(153)) # True
print(is_armstrong(123)) # False
Task: Write a program to find out if a number is a perfect number.
def is_perfect_number(number):
if number <= 0:
return False
divisor_sum = sum(i for i in range(1, number) if number % i == 0)
return divisor_sum == number
print(is_perfect_number(28)) # True
print(is_perfect_number(12)) # False
Task: Write a Python program to determine if a year is a leap year.
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(is_leap_year(2024)) # True
print(is_leap_year(2023)) # False
Task: Create a program that generates a Fibonacci sequence with up to n terms.
def fibonacci(n):
sequence = [0, 1]
for _ in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
print(fibonacci(7)) # [0, 1, 1, 2, 3, 5, 8]
Task: Write a Python program to calculate the sum of digits in a number.
def sum_of_digits(number):
return sum(int(digit) for digit in str(number))
print(sum_of_digits(12345)) # 15
Task: Write a Python program to convert a decimal number to binary.
def decimal_to_binary(decimal):
return bin(decimal)[2:]
print(decimal_to_binary(10)) # '1010'
Task: Check if a number is a prime factor of another number.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def is_prime_factor(number, potential_factor):
return is_prime(potential_factor) and number % potential_factor == 0
print(is_prime_factor(15, 3)) # True
print(is_prime_factor(15, 4)) # False
Task: Find all prime numbers within a given range.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def find_primes(start, end):
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes
print(find_primes(1, 10)) # [2, 3, 5, 7]
These questions evaluate logical thinking, algorithmic understanding, and code optimization abilities.
Task: Write a Python code to merge two dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 3, 'c': 4}
Task: Write a Python program to find common elements in two lists.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common = list(set(list1) & set(list2))
print(common) # [3, 4]
Task: Write a Python code to remove duplicates from a list.
list1 = [1, 2, 2, 3, 4, 4]
unique_list1 = list(set(list1))
print(unique_list1) # [1, 2, 3, 4]
Task: Write a Python code to check if a string is a palindrome.
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("radar")) # True
print(is_palindrome("hello")) # False
Task: Write a Python program to find the longest word in a sentence.
def longest_word(sentence):
words = sentence.split()
return max(words, key=len)
print(longest_word("The fox jumps over the lazy dog")) # jumps
Task: Write a Python code to find the first non-repeating character in a string.
def first_non_repeating_char(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char in s:
if char_count[char] == 1:
return char
return None
print(first_non_repeating_char("nxtwave")) # n
Task: Create a Python program to count uppercase letters in a string.
def count_uppercase(s):
return sum(1 for char in s if char.isupper())
print(count_uppercase("Nxtwave")) # 1
Task: Reverse a string using slicing.
s = "Python"
reversed_s = s[::-1]
print(reversed_s) # 'nohtyP'
Task: Convert a list of characters into a string.
chars = ['P', 'y', 't', 'h', 'o', 'n']
string = ''.join(chars)
print(string) # 'Python'
Task: Split a string into a list of words.
sentence = "Hello World"
words = sentence.split()
print(words) # ['Hello', 'World']
Task: Join a list of strings into a single string.
words = ['Hello', 'World']
sentence = ' '.join(words)
print(sentence) # 'Hello World'
Task: Count the number of occurrences of a character in a string.
s = "banana"
count_a = s.count('a')
print(count_a) # 3
Task: Count digits, letters, and spaces in a string.
s = "Hello 123"
digits = sum(c.isdigit() for c in s)
letters = sum(c.isalpha() for c in s)
spaces = sum(c.isspace() for c in s)
print(f"Digits: {digits}, Letters: {letters}, Spaces: {spaces}")
# Output: Digits: 3, Letters: 5, Spaces: 1
Task: Find the largest element in a list.
nums = [3, 7, 2, 9, 5]
max_num = max(nums)
print(max_num) # 9
Task: Find the minimum element in a list.
nums = [3, 7, 2, 9, 5]
min_num = min(nums)
print(min_num) # 2
Task: Merge two sorted lists into one sorted list.
a = [1, 3, 5]
b = [2, 4, 6]
merged = sorted(a + b)
print(merged) # [1, 2, 3, 4, 5, 6]
Task: Find the longest consecutive sequence in an unsorted list.
def longest_consecutive(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
length = 1
while num + length in num_set:
length += 1
longest = max(longest, length)
return longest
print(longest_consecutive([100, 4, 200, 1, 3, 2])) # 4
Task: Find indices of two numbers that add up to a target.
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
if target - num in seen:
return [seen[target - num], i]
seen[num] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
Task: Group anagrams from a list of strings.
from collections import defaultdict
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
anagrams = defaultdict(list)
for word in words:
key = ''.join(sorted(word))
anagrams[key].append(word)
print(list(anagrams.values())) # [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Task: Traverse a binary tree level by level.
from collections import deque
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def level_order(root):
if not root:
return []
result = []
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
Task: Implement Fibonacci with memoization.
def fib(n, memo={}):
if n in memo:
return memo[n]
if n <= 2:
return 1
memo[n] = fib(n-1, memo) + fib(n-2, memo)
return memo[n]
print(fib(10)) # 55
Task: Use nested loops to iterate through a matrix.
matrix = [[1, 2], [3, 4]]
for row in matrix:
for val in row:
print(val)
These questions examine depth of knowledge, optimization skills, and real-world problem-solving abilities.
Task: Implement a binary search algorithm.
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] < target:
low = mid + 1
elif arr[mid] > target:
high = mid - 1
else:
return mid
return -1
print(binary_search([1, 2, 3, 4, 5], 3)) # 2
Task: Create a function that flattens a nested list.
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
print(flatten([1, [2, [3, 4], 5], 6])) # [1, 2, 3, 4, 5, 6]
Task: Write a program to check if a binary tree is balanced.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_balanced(root):
if not root:
return True
def height(node):
if not node:
return 0
return 1 + max(height(node.left), height(node.right))
return abs(height(root.left) - height(root.right)) <= 1
root = Node(1)
root.left = Node(2)
root.right = Node(3)
print(is_balanced(root)) # True
Task: Find the maximum subarray sum (Kadane's Algorithm).
def max_subarray_sum(arr):
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6
Task: Find the intersection of two sets.
def intersection(set1, set2):
return set1 & set2
print(intersection({1, 2, 3}, {2, 3, 4})) # {2, 3}
Task: Implement a simple calculator.
def calculator(a, b, operation):
if operation == 'add':
return a + b
elif operation == 'subtract':
return a - b
elif operation == 'multiply':
return a * b
elif operation == 'divide':
return a / b if b != 0 else "Cannot divide by zero"
else:
return "Invalid operation"
print(calculator(5, 3, 'add')) # 8
print(calculator(5, 0, 'divide')) # Cannot divide by zero
print(calculator(5, 3, 'multiply')) # 15
Task: Check if a number is a perfect square.
def is_perfect_square(x):
return int(x ** 0.5) ** 2 == x
print(is_perfect_square(16)) # True
print(is_perfect_square(14)) # False
Task: Find the GCD of two numbers.
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6
Task: Convert a list of temperatures from Celsius to Fahrenheit.
def celsius_to_fahrenheit(temps):
return [(temp * 9/5) + 32 for temp in temps]
print(celsius_to_fahrenheit([0, 20, 37])) # [32.0, 68.0, 98.6]
Task: Implement a queue using collections.deque.
from collections import deque
class Queue:
def __init__(self):
self.queue = deque()
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.popleft() if self.queue else None
q = Queue()
q.enqueue(1)
q.enqueue(2)
print(q.dequeue()) # 1
print(q.dequeue()) # 2
print(q.dequeue()) # None
Task: Implement a singleton pattern using a metaclass.
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class MyClass(metaclass=Singleton):
pass
a = MyClass()
b = MyClass()
print(a is b) # True
Task: Demonstrate the difference between @staticmethod and @classmethod.
class Example:
@staticmethod
def static_method():
return "static method called"
@classmethod
def class_method(cls):
return f"class method called from {cls.__name__}"
print(Example.static_method()) # static method called
print(Example.class_method()) # class method called from Example
Task: Demonstrate the with statement for file handling.
with open('file.txt', 'r') as file:
data = file.read()
print(data)
Task: Demonstrate multithreading in Python.
import threading
def worker():
print("Thread is running")
t = threading.Thread(target=worker)
t.start()
t.join()
Task: Implement a coroutine using asyncio.
import asyncio
async def greet():
await asyncio.sleep(1)
print("Hello")
asyncio.run(greet())
Task: Use slots to limit instance attributes.
class MyClass:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
obj = MyClass(10, 20)
print(obj.x, obj.y) # 10 20
Task: Demonstrate data manipulation with Pandas.
import pandas as pd
data = {'name': ['Alice', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data)
df['age_plus_one'] = df['age'] + 1
print(df)
Task: Read a CSV file using Pandas.
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())
Task: Basic web scraping example with Selenium.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.example.com')
print(driver.title)
driver.quit()
Task: Handle missing values in a DataFrame.
df = df.fillna(0) # Replace missing values with 0
List: Mutable (can be changed), defined with square brackets []
Tuple: Immutable (cannot be changed), defined with parentheses ()
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
Python has automatic memory management based on reference counting and a garbage collector to free unneeded memory.
Use try-except blocks to handle exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Control flow using if, elif, and else.
x = 5
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Use the def keyword to define functions.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
PEP 8 is the official style guide for Python, promoting code readability and consistency.
Indentation (spaces or tabs) determines code blocks. Incorrect indentation causes syntax errors.
A class is a blueprint for creating objects (instances).
class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Rex")
print(my_dog.name) # Rex
| Category | Types |
|---|---|
| Numeric | int, float, complex |
| Sequence | list, tuple, range |
| Text | str |
| Set | set, frozenset |
| Mapping | dict |
| Boolean | bool |
| Binary | bytes, bytearray, memoryview |
Package management refers to installing, upgrading, and removing Python libraries using pip.
Task: Perform API interactions using the requests library.
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Request failed with status code {response.status_code}")
Task: Handle I/O-bound tasks efficiently.
import threading
def download_file(url):
# Code to download file from URL
pass
thread = threading.Thread(target=download_file, args=('https://example.com/file',))
thread.start()
thread.join()
Task: Use assertions to check conditions.
def divide(a, b):
assert b != 0, "Denominator cannot be zero"
return a / b
print(divide(10, 2)) # 5.0
Task: Implement data-driven testing.
import pytest
@pytest.mark.parametrize(
"a, b, expected",
[(1, 2, 3), (4, 5, 9)]
)
def test_add(a, b, expected):
assert a + b == expected
Task: Use environment variables securely.
import os
api_key = os.environ.get('API_KEY')
print(api_key) # Prints None if 'API_KEY' is not set
Task: Identify performance bottlenecks.
import cProfile
def slow_function():
# Some code to profile
pass
cProfile.run('slow_function()')
Task: Monitor execution time.
import time
start = time.time()
# Code to measure
end = time.time()
print(f"Execution time: {end - start} seconds")
Task: Handle HTTP status codes in API responses.
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
print("Success")
elif response.status_code == 404:
print("Not Found")
else:
print(f"Error: {response.status_code}")
Task: Perform web scraping with BeautifulSoup.
import requests
from bs4 import BeautifulSoup
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
titles = [h1.text for h1 in soup.find_all('h1')]
print(titles)
Task: Store and use API keys securely.
import os
db_password = os.environ.get('DB_PASSWORD')
if db_password is None:
raise Exception("Database password not found in environment variables.")
Task: Handle multithreading for concurrent API requests.
import requests
from concurrent.futures import ThreadPoolExecutor
urls = ['https://api.example.com/a', 'https://api.example.com/b']
def fetch(url):
return requests.get(url).json()
with ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(fetch, urls))
print(results)
Task: Apply assertions in business logic.
def process_order(order):
assert order['quantity'] > 0, "Order quantity must be positive"
# further processing
Task: Optimize web scraping performance.
import requests
from bs4 import BeautifulSoup
session = requests.Session()
response = session.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
titles = [tag.text for tag in soup.select('h1, h2')]
Task: Handle network failures with retry logic.
import requests
from time import sleep
def fetch_with_retry(url, retries=3):
for attempt in range(retries):
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.text
except requests.RequestException as e:
if attempt < retries - 1:
sleep(2)
else:
print(f"Failed after {retries} attempts: {e}")
return None
data = fetch_with_retry('https://example.com')
Consistent hands-on practice is essential. Solve coding problems across all difficulty levels to build and maintain problem-solving experience.
Focus on learning underlying algorithms and data structures rather than memorizing code snippets. This helps you adapt to unfamiliar problems.
Engage with coding platforms such as:
Competitive programming develops speed, accuracy, and thinking under pressure.
For each problem:
Use online compilers or IDEs to run solutions through various test cases, including edge cases, to ensure code robustness.
After solving a problem:
Practice solving problems:
This builds confidence and prepares you mentally for real interviews.
With regular practice, strong conceptual understanding, and realistic simulation, you'll perform at your best in Python coding interviews and demonstrate yourself as a strong candidate.
Succeeding in Python coding interviews requires more than memorizing syntax—it demands solid problem-solving skills, logical thinking, and the ability to write clean, efficient code.
This comprehensive guide has covered:
Importance of Python Coding Questions
Comprehensive Problem Coverage
Core Concepts and Real Scenarios
Actionable Preparation Strategies
Whether preparing for your first developer position, changing careers, or brushing up on coding skills, success comes through consistent practice. Focus on:
Start practicing these strategies one coding question at a time. With focus and dedicated effort, you'll succeed in your upcoming interviews and thrive in your software development career.
Tricky questions commonly involve:
Leverage coding challenge platforms:
Consistent practice on these platforms helps you:
Concentrate on:
Data Structures:
Algorithms:
Core Concepts:
Built-in Modules:
For Data Positions:
Step-by-Step Approach:
Understand the Problem
Plan Your Solution
Write the Code
Test and Optimize
Review
Preparation Strategies:
Timed Practice
Focus on Correctness First
Learn from Mistakes
Pattern Recognition
Mock Interviews
Code Review
During the Interview:
| Library | Use Case |
|---|---|
| collections | Advanced data structures (deque, Counter, defaultdict) |
| itertools | Efficient iteration tools |
| functools | Higher-order functions and decorators |
| heapq | Heap queue algorithm (priority queue) |
| bisect | Array bisection algorithm |
| math | Mathematical functions |
NxtWave Support:
This guide is provided by NxtWave, a leading platform for IT career development and technical education.