Python Programming Placement Questions
Python Programming Questions for Placement 2026 (with Solutions)
Last Updated: March 2026
Introduction
Python has emerged as one of the most popular programming languages for placements, especially in data science, machine learning, automation, and web development roles. Companies like Google, Amazon, Microsoft, TCS, Infosys, and startups extensively use Python for its simplicity, readability, and vast library ecosystem. Python's clean syntax makes it ideal for rapid development and coding interviews.
Why Python is Important for Placements
- Easy to Learn: Clean, readable syntax ideal for beginners
- Versatile: Used in web dev, data science, ML, automation, scripting
- Rich Libraries: NumPy, Pandas, Django, Flask, TensorFlow
- Interview Friendly: Less boilerplate code, focus on logic
- Industry Demand: Fastest-growing language in tech industry
Frequently Asked Coding Questions with Solutions
Question 1: List Operations
Problem: Write a program to find the second largest number in a list.
Solution:
def second_largest(numbers):
if len(numbers) < 2:
return None
first = second = float('-inf')
for num in numbers:
if num > first:
second = first
first = num
elif first > num > second:
second = num
return second if second != float('-inf') else None
# Test
nums = [10, 20, 4, 45, 99, 99]
print(f"Second largest: {second_largest(nums)}") # Output: 45
Question 2: String Manipulation
Problem: Check if a string is a palindrome (ignoring spaces and case).
Solution:
def is_palindrome(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
# Test
text = "A man a plan a canal Panama"
print(f"Is palindrome: {is_palindrome(text)}") # Output: True
Question 3: Dictionary Operations
Problem: Count word frequency in a sentence.
Solution:
def word_frequency(text):
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
# Test
text = "the quick brown fox jumps over the lazy dog"
print(word_frequency(text))
# Output: {'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, ...}
Question 4: Fibonacci Series
Problem: Generate Fibonacci series up to n terms.
Solution:
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
# Test
print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Question 5: Prime Number Check
Problem: Check if a number is prime.
Solution:
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Test
print(f"17 is prime: {is_prime(17)}") # Output: True
print(f"20 is prime: {is_prime(20)}") # Output: False
Question 6: File Handling
Problem: Read a file and count lines, words, and characters.
Solution:
def file_stats(filename):
try:
with open(filename, 'r') as f:
content = f.read()
lines = content.split('\n')
words = content.split()
return {
'lines': len(lines),
'words': len(words),
'characters': len(content)
}
except FileNotFoundError:
return "File not found"
# Usage
# stats = file_stats('example.txt')
# print(stats)
Question 7: Lambda and Map
Problem: Use lambda and map to square all numbers in a list.
Solution:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
# Using list comprehension (more Pythonic)
squared2 = [x**2 for x in numbers]
print(squared2) # Output: [1, 4, 9, 16, 25]
Question 8: Class and Object
Problem: Create a Student class with attributes and methods.
Solution:
class Student:
def __init__(self, name, roll_no, marks):
self.name = name
self.roll_no = roll_no
self.marks = marks
def get_grade(self):
if self.marks >= 90:
return 'A'
elif self.marks >= 80:
return 'B'
elif self.marks >= 70:
return 'C'
elif self.marks >= 60:
return 'D'
else:
return 'F'
def __str__(self):
return f"{self.roll_no}: {self.name} - {self.get_grade()}"
# Test
s1 = Student("Alice", 101, 85)
print(s1) # Output: 101: Alice - B
Question 9: Exception Handling
Problem: Demonstrate exception handling with try-except.
Solution:
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Invalid input type"
except Exception as e:
return f"Error: {e}"
# Test
print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Output: Cannot divide by zero
print(divide(10, 'a')) # Output: Invalid input type
Question 10: List Comprehension
Problem: Use list comprehension for various operations.
Solution:
# Even numbers from 1 to 20
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Squares of numbers
doubled = [x**2 for x in range(1, 6)]
print(doubled) # [1, 4, 9, 16, 25]
# Flatten a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [item for row in matrix for item in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Question 11: Recursion
Problem: Calculate factorial using recursion.
Solution:
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
# Test
print(f"Factorial of 5: {factorial(5)}") # Output: 120
Question 12: Sorting
Problem: Sort a list of dictionaries by a key.
Solution:
students = [
{'name': 'Alice', 'marks': 85},
{'name': 'Bob', 'marks': 92},
{'name': 'Charlie', 'marks': 78}
]
# Sort by marks
sorted_students = sorted(students, key=lambda x: x['marks'], reverse=True)
print(sorted_students)
# [{'name': 'Bob', 'marks': 92}, {'name': 'Alice', 'marks': 85}, ...]
Question 13: Set Operations
Problem: Demonstrate set operations.
Solution:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(f"Union: {set1 | set2}") # {1, 2, 3, 4, 5, 6, 7, 8}
print(f"Intersection: {set1 & set2}") # {4, 5}
print(f"Difference: {set1 - set2}") # {1, 2, 3}
print(f"Symmetric diff: {set1 ^ set2}") # {1, 2, 3, 6, 7, 8}
Question 14: Decorators
Problem: Create a timing decorator.
Solution:
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
slow_function() # Output: slow_function took 1.00xx seconds
Question 15: Generator
Problem: Create a generator for Fibonacci numbers.
Solution:
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
# Usage
for num in fibonacci_generator(10):
print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34
Question 16: Regular Expressions
Problem: Validate email using regex.
Solution:
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# Test
print(validate_email("[email protected]")) # True
print(validate_email("invalid.email")) # False
Question 17: Inheritance
Problem: Demonstrate class inheritance.
Solution:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy says Woof!
print(cat.speak()) # Whiskers says Meow!
Question 18: JSON Handling
Problem: Parse and create JSON data.
Solution:
import json
# Dictionary to JSON
data = {'name': 'Alice', 'age': 25}
json_str = json.dumps(data, indent=2)
print(json_str)
# JSON to dictionary
parsed = json.loads(json_str)
print(parsed['name']) # Alice
Question 19: CSV Handling
Problem: Read and write CSV files.
Solution:
import csv
# Writing CSV
data = [['Name', 'Age'], ['Alice', '25'], ['Bob', '30']]
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
# Reading CSV
with open('output.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
Question 20: Binary Search
Problem: Implement binary search.
Solution:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Test
arr = [1, 3, 5, 7, 9, 11, 13]
print(binary_search(arr, 7)) # 3
print(binary_search(arr, 10)) # -1
Output Prediction Questions (10 Questions)
Question 1: What is the output?
x = [1, 2, 3]
y = x
y.append(4)
print(x)
Question 2: What is the output?
print(3 * [1, 2])
Question 3: What is the output?
a = [1, 2, 3]
print(a[::-1])
Question 4: What is the output?
def func(x, y=[]):
y.append(x)
return y
print(func(1))
print(func(2))
Question 5: What is the output?
print(type(lambda: None))
Question 6: What is the output?
x = 5
print(x > 3 and x < 10)
Question 7: What is the output?
print("Hello"[1:4])
Question 8: What is the output?
d = {'a': 1, 'b': 2}
print(d.get('c', 3))
Question 9: What is the output?
print(list(range(3, 10, 2)))
Question 10: What is the output?
s = {1, 2, 3}
s.add(3)
print(len(s))
MCQs on Python Fundamentals (10 Questions)
Question 1: What is the output of print(2 ** 3)?
a) 6 b) 8 c) 9 d) Error
Question 2: Which is NOT a valid Python data type?
a) list b) tuple c) array d) dictionary
Question 3: What does len() function do?
a) Returns last element b) Returns length of object c) Returns first element d) Converts to list
Question 4: What is the correct syntax for an empty dictionary?
a) [] b) () c) {} d) <>
Question 5: Which method adds an element to a set?
a) append() b) add() c) insert() d) extend()
Question 6: What is a lambda function?
a) A named function b) An anonymous function c) A recursive function d) A generator function
Question 7: What does __init__ represent?
a) Destructor b) Constructor c) Initializer variable d) Module import
Question 8: Which keyword is used to define a generator?
a) return b) yield c) generate d) async
Question 9: What is the output of print(10 // 3)?
a) 3.33 b) 3 c) 1 d) Error
Question 10: Which statement is used to handle exceptions?
a) if-else b) try-except c) for-while d) with-as
Tips for Python Coding Rounds
1. Master List Comprehensions
# Instead of
result = []
for x in range(10):
if x % 2 == 0:
result.append(x**2)
# Use
result = [x**2 for x in range(10) if x % 2 == 0]
2. Use Built-in Functions
# Common useful functions
sum([1, 2, 3]) # 6
max([1, 5, 3]) # 5
min([1, 5, 3]) # 1
sorted([3, 1, 2]) # [1, 2, 3]
len("hello") # 5
enumerate(['a', 'b']) # [(0, 'a'), (1, 'b')]
zip([1, 2], ['a', 'b']) # [(1, 'a'), (2, 'b')]
3. Dictionary Best Practices
# Use get() with default
value = d.get('key', default_value)
# Use setdefault
# Use collections.defaultdict for automatic defaults
from collections import defaultdict
d = defaultdict(list)
d['key'].append(1) # No KeyError
4. String Operations
# Common string methods
text = "Hello World"
text.upper() # "HELLO WORLD"
text.lower() # "hello world"
text.split() # ["Hello", "World"]
text.replace('l', 'x') # "Hexxo Worxd"
text.strip() # Remove whitespace
5. File Handling
# Always use with statement
with open('file.txt', 'r') as f:
content = f.read()
# File automatically closed
6. Avoid Common Mistakes
# Mutable default arguments - DON'T
def bad_func(items=[]):
items.append(1)
return items
# DO this instead
def good_func(items=None):
if items is None:
items = []
items.append(1)
return items
Frequently Asked Questions (FAQ)
Q1: Is Python good for placements?
Yes! Python is widely accepted in placements, especially for data science, ML, automation, and web development roles. Many companies allow candidates to code in Python for interviews.
Q2: What are the most important Python topics for placements?
Focus on: Data structures (lists, dicts, sets), String manipulation, List/dict comprehensions, OOP concepts, File handling, Exception handling, and Common built-in functions.
Q3: Should I learn Python 2 or Python 3?
Python 3 only. Python 2 is deprecated and not used in modern development.
Q4: How do I handle coding interviews in Python?
Practice writing clean, readable code. Use list comprehensions where appropriate. Know when to use different data structures. Practice solving problems on platforms like LeetCode, HackerRank.
Q5: What libraries should I know for placements?
For general placements: Standard library is sufficient. For data roles: NumPy, Pandas. For web roles: Basic Django/Flask knowledge helps.
Master Python through consistent practice focusing on clean code, efficient data structure usage, and problem-solving. Practice writing Pythonic code using list comprehensions, generators, and appropriate built-in functions. Good luck with your placement preparation!
Explore this topic cluster
More resources in Uncategorized
Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.