Top 30 Python Coding Questions and Answers
π Top 30 Python Coding Questions and Answers for Placements (With Clear Explanations & Examples)
In todayβs competitive job market, Python has become one of the most in-demand programming languages. Whether youβre preparing for a campus placement, technical interview, or coding test, having a strong grip on Python is essential. This post provides you with Top 30 frequently asked Python coding questions and answers that are ideal for students, beginners, and job seekers. Each question comes with a clear explanation, input-output examples, and practical logic to help you crack any placement test confidently.
Letβs dive into these must-practice questions! π
π’ 1. Write a program to check if a number is even or odd.
Explanation: An even number is divisible by 2, odd is not.
1 2 3 4 5 6 |
def check_even_odd(num): return "Even" if num % 2 == 0 else "Odd" # Example print(check_even_odd(7)) # Output: Odd print(check_even_odd(12)) # Output: Even |
π 2. Write a program to print the Fibonacci series up to n terms.
Explanation: Fibonacci series: 0, 1, 1, 2, 3, 5, 8…
1 2 3 4 5 6 7 8 9 |
def fibonacci(n): a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + b # Example fibonacci(6) # Output: 0 1 1 2 3 5 |
π 3. Check if a number is prime or not.
Explanation: Prime numbers are divisible only by 1 and themselves.
1 2 3 4 5 6 7 8 9 10 11 |
def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True # Example print(is_prime(7)) # Output: True print(is_prime(10)) # Output: False |
π 4. Reverse a string without using built-in functions.
Explanation: Loop through the string backwards.
1 2 3 4 5 6 7 8 |
def reverse_string(s): rev = "" for char in s: rev = char + rev return rev # Example print(reverse_string("hello")) # Output: olleh |
π― 5. Find the factorial of a number using recursion.
Explanation: Factorial of n = n * (n-1)…
π 6. Count the vowels in a string
Explanation:
Vowels in English are a
, e
, i
, o
, and u
. This problem asks us to count how many vowels are present in a given string. We’ll check each character to see if it’s a vowel.
1 2 3 4 5 6 7 8 9 10 |
def count_vowels(s): vowels = 'aeiouAEIOU' count = 0 for char in s: if char in vowels: count += 1 return count # Example print(count_vowels("Hello World")) # Output: 3 |
Why it works:
We loop through each character in the string and increment the counter only if it matches any vowel (uppercase or lowercase).
π 7. Check if a string is a palindrome
Explanation:
A palindrome is a string that reads the same backward as forward. Examples: madam
, racecar
, level
.
To check this, we simply compare the original string with its reverse.
1 2 3 4 5 6 |
def is_palindrome(s): return s == s[::-1] # Example print(is_palindrome("madam")) # Output: True print(is_palindrome("python")) # Output: False |
Why it works:s[::-1]
reverses the string using Python slicing. If the original and reversed strings are equal, itβs a palindrome.
β 8. Find the sum of digits of a number
Explanation:
To find the sum of all digits in a number, we convert it to a string, loop through each character (digit), convert it back to an integer, and add it.
1 2 3 4 5 6 7 8 |
def sum_of_digits(n): total = 0 for digit in str(n): total += int(digit) return total # Example print(sum_of_digits(1234)) # Output: 10 (1+2+3+4) |
Why it works:
The str(n)
breaks the number into individual digits, and we accumulate the sum using a loop.
π― 9. Find the largest of three numbers
Explanation:
To find the largest number among three, we use Pythonβs built-in max()
function or logic with conditional statements.
1 2 3 4 5 |
def largest_of_three(a, b, c): return max(a, b, c) # Example print(largest_of_three(10, 25, 17)) # Output: 25 |
Alternative (Without using max):
1 2 3 4 5 6 7 |
def largest_of_three(a, b, c): if a >= b and a >= c: return a elif b >= a and b >= c: return b else: return c |
Why it works:
We simply compare the values to determine the highest. Both max()
and if-else
logic are acceptable in interviews.
π 10. Print all prime numbers in a range
Explanation:
A prime number is a number greater than 1 that has no divisors other than 1 and itself. We use a helper function to check if a number is prime and print all such numbers in a given range.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5)+1): if n % i == 0: return False return True def primes_in_range(start, end): for num in range(start, end + 1): if is_prime(num): print(num, end=" ") # Example primes_in_range(10, 20) # Output: 11 13 17 19 |
Why it works:
We check divisibility up to the square root of the number for efficiency. This reduces unnecessary checks and improves performance.
βοΈ 11. Check if a number is an Armstrong number
Explanation:
An Armstrong number is one whose sum of its digits raised to the power of the number of digits is equal to the number itself.
For example, 153
is an Armstrong number because:
Why it works:
We convert the number to a string to iterate over its digits, raise each to the power of the number of digits, and compare the result with the original number.
π’ 12. Calculate the GCD of two numbers
Explanation:
GCD (Greatest Common Divisor) is the largest number that divides both numbers without leaving a remainder.
1 2 3 4 5 6 7 |
def gcd(a, b): while b: a, b = b, a % b return a # Example print(gcd(60, 48)) # Output: 12 |
Why it works:
This is known as Euclidβs Algorithm. We repeatedly replace a
with b
and b
with a % b
until it b
becomes 0. The final a
is the GCD.
π 13. Calculate the LCM of two numbers
Explanation:
LCM (Least Common Multiple) of two numbers is the smallest number that is a multiple of both.
We use the formula:
1 2 3 4 5 6 7 8 9 10 |
def gcd(a, b): while b: a, b = b, a % b return a def lcm(a, b): return (a * b) // gcd(a, b) # Example print(lcm(12, 18)) # Output: 36 |
Why it works:
We first calculate the GCD and then use it to compute the LCM using the standard formula.
π 14. Print a pattern β right-angled triangle of stars
Explanation:
A common pattern question in coding interviews. For a given number of rows n
, print a right-angled triangle of stars (*
).
1 2 3 4 5 6 |
def print_triangle(n): for i in range(1, n + 1): print('*' * i) # Example print_triangle(5) |
Output:
*
**
***
****
*****
Why it works:
In each iteration, we print i
stars, increasing the count with each row.
Also Read,
Top 30 C Language Coding Questions and Answers |
π€ 15. Count the frequency of characters in a string
Explanation:
We loop through each character in the string and maintain a dictionary to count occurrences.
1 2 3 4 5 6 7 8 |
def char_frequency(s): freq = {} for char in s: freq[char] = freq.get(char, 0) + 1 return freq # Example print(char_frequency("hello")) |
Output:
Why it works:
We use the .get()
method to safely update the dictionary even if the character is not present initially.
π 16. Remove duplicates from a list
Explanation:
Lists can contain repeated elements. To get only unique values, we can convert the list to a set
, then back to a list
.
1 2 3 4 5 |
def remove_duplicates(lst): return list(set(lst)) # Example print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) |
Output:
Why it works:
Sets automatically eliminate duplicates. Converting back to a list gives us the required format.
π 17. Reverse a list without using reverse() function
Explanation:
We can reverse a list manually using slicing. This is a common logic question asked to test your knowledge of Python list manipulation.
1 2 3 4 5 |
def reverse_list(lst): return lst[::-1] # Example print(reverse_list([10, 20, 30, 40])) |
Output:
Why it works:
The slicing method [::-1]
returns the list in reversed order. Itβs a clean, Pythonic solution.
π 18. Find the factorial of a number using recursion
Explanation:
The factorial of a number n
(denoted n!
) is the product of all positive integers less than or equal to n
.
For example:5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 = 120
1 2 3 4 5 6 7 |
def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) # Example print(factorial(5)) # Output: 120 |
Why it works:
The function calls itself with a smaller number until it hits the base case n == 1
, making it a classic example of recursion.
π 19. Check if two strings are anagrams
Explanation:
Two strings are anagrams if they contain the same characters in any order.
Example: listen
and silent
are anagrams.
1 2 3 4 5 |
def are_anagrams(str1, str2): return sorted(str1) == sorted(str2) # Example print(are_anagrams("listen", "silent")) # Output: True |
Why it works:
By sorting both strings, we bring the characters into the same order. If they match, they are anagrams.
π 20. Merge two dictionaries
Explanation:
Python allows us to combine two dictionaries using the update()
method or the **
unpacking operator.
1 2 3 4 5 6 7 |
def merge_dicts(dict1, dict2): return {**dict1, **dict2} # Example d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} print(merge_dicts(d1, d2)) |
Output:
Why it works:
The **
operator unpacks key-value pairs from both dictionaries into a new one, creating a merged dictionary.
π 21. Find the second largest number in a list
Explanation:
To find the second largest number, we sort the list in descending order and pick the second element. This is a very common coding test question.
1 2 3 4 5 6 7 |
def second_largest(lst): unique_nums = list(set(lst)) # Remove duplicates unique_nums.sort(reverse=True) return unique_nums[1] if len(unique_nums) >= 2 else None # Example print(second_largest([10, 20, 4, 45, 99, 99])) # Output: 45 |
Why it works:
We use a set
to remove duplicates, sort the list in descending order, and access the second element.
π 22. Rotate a list to the right by k steps
Explanation:
Rotation means shifting elements. Rotating to the right moves the last element to the front.
1 2 3 4 5 6 |
def rotate_list(lst, k): k = k % len(lst) # Handle if k > len(lst) return lst[-k:] + lst[:-k] # Example print(rotate_list([1, 2, 3, 4, 5], 2)) # Output: [4, 5, 1, 2, 3] |
Why it works:
We use slicing to split and rearrange the list into rotated form. The modulo helps avoid errors for large k
.
π― 23. Check if a number is a perfect number
Explanation:
A perfect number is a positive integer that is equal to the sum of its proper divisors.
Example: 28
β Divisors = 1, 2, 4, 7, 14
β Sum = 28 β
1 2 3 4 5 6 7 |
def is_perfect(n): divisors = [i for i in range(1, n) if n % i == 0] return sum(divisors) == n # Example print(is_perfect(28)) # Output: True print(is_perfect(12)) # Output: False |
Why it works:
We find all divisors less than n
and check if their sum equals n
.
π€ 24. Remove all special characters from a string
Explanation:
We can use a loop or a regex to remove non-alphanumeric characters from a string.
1 2 3 4 5 6 7 |
import re def remove_special_chars(s): return re.sub(r'[^A-Za-z0-9 ]+', '', s) # Example print(remove_special_chars("Hello@# World!!")) # Output: "Hello World" |
Why it works:
The regex [^A-Za-z0-9 ]
targets all characters except letters, numbers, and space. The re.sub()
function replaces them with an empty string.
π 25. Print the Fibonacci series up to n terms
Explanation:
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones.
Starting with: 0, 1, 1, 2, 3, 5, 8...
1 2 3 4 5 6 7 8 |
def fibonacci(n): a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + b # Example fibonacci(7) |
Output:
Why it works:
We use two variables a
and b
to generate the series iteratively. Itβs efficient and beginner-friendly.
π¦ 26. Flatten a nested list
Explanation:
A nested list is a list inside another list. To flatten it, we extract all elements and put them into a single list.
1 2 3 4 5 6 7 8 9 |
def flatten_list(nested): flat = [] for sublist in nested: for item in sublist: flat.append(item) return flat # Example print(flatten_list([[1, 2], [3, 4], [5]])) # Output: [1, 2, 3, 4, 5] |
Why it works:
We use two for
loops to access elements of inner lists and collect them in a single flat list.
π§ 27. Find the most frequent element in a list
Explanation:
We count the frequency of each element and return the one with the highest count.
1 2 3 4 5 6 7 8 |
def most_frequent(lst): freq = {} for item in lst: freq[item] = freq.get(item, 0) + 1 return max(freq, key=freq.get) # Example print(most_frequent([1, 3, 2, 1, 4, 1])) # Output: 1 |
Why it works:
We use a dictionary to count and then find the key with the highest value using max()
and key=freq.get
.
π₯ 28. Find all pairs in a list that sum to a target
Explanation:
This is a classic coding interview question. We loop through the list and use a set to track complements.
1 2 3 4 5 6 7 8 9 10 11 12 |
def find_pairs(lst, target): seen = set() pairs = [] for num in lst: diff = target - num if diff in seen: pairs.append((diff, num)) seen.add(num) return pairs # Example print(find_pairs([1, 2, 3, 4, 5], 6)) # Output: [(2, 4), (1, 5)] |
Why it works:
We store elements in a set and check if the required number to reach the target is already seen.
π§Ύ 29. Convert a string to title case
Explanation:
Title case means every word starts with an uppercase letter.
1 2 3 4 5 |
def to_title_case(s): return s.title() # Example print(to_title_case("hello world from python")) # Output: "Hello World From Python" |
Why it works:
Python’s built-in .title()
method automatically capitalizes the first letter of each word.
π 30. Count vowels in a string
Explanation:
We loop through each character and check if it’s a vowel (both lowercase and uppercase).
1 2 3 4 5 6 |
def count_vowels(s): vowels = "aeiouAEIOU" return sum(1 for char in s if char in vowels) # Example print(count_vowels("Python Programming")) # Output: 4 |
Why it works:
We use a generator expression to count all vowels efficiently without creating an intermediate list.
π Thatβs it! You’ve now got 30 beginner-friendly, placement-focused Python coding questions with solutions and logical clarity!
π Conclusion
This blog will teach you from basic-level coding questions and answers to advanced-level which will be helpful in placement exam coding rounds. Whether you are a student, beginner, or career switcher, understanding these foundational concepts will boost your confidence in solving real-time coding problems.
β Pro Tips:
-
Practice regularly on platforms like HackerRank, LeetCode, or GeeksforGeeks.
-
Understand the logic before memorising code.
-
Always dry-run your code with examples.
π‘ βPractice doesn’t make perfect. Perfect practice makes perfect.β
π€ Stay Updated with NextGen Careers Hub
π± Follow us onΒ Instagram
πΊ Subscribe to us on YouTube
Please share our website with others:Β NextGenCareersHub.in