Quick answer: The best Python basics practice problems cover strings, loops, conditions, lists, dictionaries and functions: reversing a string, counting vowels, summing digits, FizzBuzz, palindromes, primes, Fibonacci, word counts, removing duplicates, second largest, anagrams, a missing number and two-sum. Try each one yourself for 15 to 20 minutes before reading the solution.
These Python basics practice problems are the ones I give students in their first few weeks of Python. They are small enough to finish in one sitting, but each one teaches a pattern you will use again in real code and in interviews.
The 15 problems are graded in three levels. Level 1 builds comfort with strings, loops and conditions. Level 2 adds functions, math logic and dictionaries. Level 3 is the kind of problem fresher coding rounds actually use. Every solution below runs as written on Python 3.
How to use these Python basics exercises
Reading solutions teaches you very little. Writing code does. Follow this routine for each problem:
- Read the problem and write the expected output for one example by hand.
- Try it yourself for 15 to 20 minutes, in a file you save, not in your head.
- Compare with the solution and read the explanation.
- Next day, close the solution and write it again from memory.
Pro tip: Keep all your solutions in one GitHub repository, one file per problem. It builds a commit history from your first week, and recruiters do check.
Level 1: Warm-up problems
1. Reverse a string
Write a function that returns a string reversed. "python" should give "nohtyp".
def reverse_string(text):
return text[::-1]
print(reverse_string("python")) # nohtyp
The slice [::-1] walks the string with a step of minus one. Interviewers sometimes ask for a loop version too, so practise building the result character by character with result = ch + result.
2. Count the vowels
Count how many vowels (a, e, i, o, u) are in a string, ignoring case.
def count_vowels(text):
vowels = "aeiou"
return sum(1 for ch in text.lower() if ch in vowels)
print(count_vowels("Education")) # 5
Notice the .lower() call: without it, the capital "E" would be missed. The generator inside sum() adds 1 for every character that passes the check.
3. Sum of digits
Return the sum of the digits of an integer. 4721 should give 14.
def digit_sum(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10 # last digit
n //= 10 # drop the last digit
return total
print(digit_sum(4721)) # 14
% 10 gives the last digit and // 10 removes it. This pair appears in many number problems: reversing a number, Armstrong numbers and palindromic numbers all use it.
4. Largest of three numbers
Find the largest of three numbers without using max().
def largest(a, b, c):
if a >= b and a >= c:
return a
if b >= c:
return b
return c
print(largest(12, 45, 7)) # 45
Using >= handles ties cleanly: if two values are equal and largest, the function still returns that value. Once this works, check that max(a, b, c) gives the same answer.
5. FizzBuzz
Print numbers from 1 to 15. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz".
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
The order of the checks is the whole problem. If you test % 3 first, 15 prints "Fizz" and never reaches "FizzBuzz". Always put the most specific condition first.
Common mistake: Writing
range(1, 15)and wondering why 15 never prints.rangestops before the end value, so you needrange(1, 16).
Level 2: Python basics problems and solutions with functions and logic
6. Palindrome check
Check whether a phrase reads the same forwards and backwards, ignoring case, spaces and punctuation.
def is_palindrome(text):
cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome("Never odd or even")) # True
print(is_palindrome("Python")) # False
The real work is cleaning the input. isalnum() keeps only letters and digits, so spaces and commas drop out before the comparison.
7. Factorial
Return the factorial of a non-negative integer. 5 should give 120, and 0 should give 1.
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial(5)) # 120
print(factorial(0)) # 1
Notice that factorial(0) returns 1 without a special case, because the loop simply does not run. Raising ValueError for bad input is better than silently returning a wrong answer.
8. Fibonacci series
Return the first n Fibonacci numbers as a list.
def fibonacci(n):
series = []
a, b = 0, 1
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
print(fibonacci(8)) # [0, 1, 1, 2, 3, 5, 8, 13]
The line a, b = b, a + b updates both values at once using the old values. Splitting it into two lines (a = b then b = a + b) is a classic bug, because a has already changed.
9. Prime check
Write a function that says whether a number is prime, then list the primes below 30.
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
print([x for x in range(1, 30) if is_prime(x)])
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
You only need to test divisors up to the square root of n: if n has a factor bigger than that, it also has one smaller. That one idea turns a slow solution into a fast one, and interviewers like to hear you explain it.
10. Word frequency
Count how many times each word appears in a sentence.
def word_count(sentence):
counts = {}
for word in sentence.lower().split():
counts[word] = counts.get(word, 0) + 1
return counts
print(word_count("the cat and the hat"))
# {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
counts.get(word, 0) returns 0 for a word you have not seen yet, so there is no need for an if check. Once you understand this, try collections.Counter, which does the same job in one line.
Level 3: Python basics coding practice at interview level
11. Remove duplicates, keep the order
Remove duplicates from a list while keeping the first occurrence of each item in its original position.
def remove_duplicates(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(remove_duplicates([3, 1, 3, 2, 1, 5])) # [3, 1, 2, 5]
The set makes each "have I seen this?" check fast, and the list keeps the order. list(set(items)) removes duplicates too, but it does not keep the order, which is exactly what the question tests. A neat one-liner alternative is list(dict.fromkeys(items)).
12. Second largest number
Find the second largest distinct number in a list, in one pass. Return None if there is no second largest.
def second_largest(nums):
first = second = None
for n in nums:
if first is None or n > first:
first, second = n, first
elif n != first and (second is None or n > second):
second = n
return second
print(second_largest([10, 40, 30, 40, 20])) # 30
print(second_largest([7, 7])) # None
The n != first check stops a repeated maximum (the second 40) from being counted as the second largest. sorted(set(nums))[-2] also works for valid input, but it sorts the whole list and crashes when there is only one distinct value.
Interview note: For problems like this, say your edge cases out loud before coding: empty list, one element, all values equal, negative numbers. Interviewers score that habit as much as the final code.
13. Anagram check
Check whether two words are anagrams (same letters, different order), ignoring case and spaces.
def is_anagram(a, b):
clean_a = sorted(a.replace(" ", "").lower())
clean_b = sorted(b.replace(" ", "").lower())
return clean_a == clean_b
print(is_anagram("Listen", "Silent")) # True
print(is_anagram("Apple", "Paper")) # False
Sorting both strings puts the letters in the same order if they are anagrams. "Apple" and "Paper" share most letters, but one has an extra "l" and the other an "r", so the sorted lists differ.
14. Find the missing number
A list contains the numbers 1 to n with exactly one missing. Find it.
def missing_number(nums):
n = len(nums) + 1
expected = n * (n + 1) // 2
return expected - sum(nums)
print(missing_number([1, 2, 4, 5, 6])) # 3
The list has five items, so n is 6 and the full sum should be 21. The actual sum is 18, so 3 is missing. No sorting and no nested loops: one formula does it.
15. Two sum
Given a list and a target, return the indexes of the two numbers that add up to the target.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
need = target - n
if need in seen:
return [seen[need], i]
seen[n] = i
return None
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
print(two_sum([3, 2, 4], 6)) # [1, 2]
The dictionary stores each number's index as you go, so for every new number you only ask "have I already seen the number I need?" That makes it one pass instead of checking every pair. Notice the second example: 3 is not paired with itself, because a number is added to seen only after the check.
What these problems teach
Each problem is small, but together they cover the core patterns of beginner Python:
| Pattern | Problems |
|---|---|
| Slicing and string methods | 1, 2, 6, 13 |
% and // for number logic |
3, 5, 9, 14 |
| Conditions and their order | 4, 5, 12 |
| Loops that build a result | 7, 8, 10 |
| Sets and dictionaries for fast lookups | 10, 11, 15 |
If one row feels weak, write three more problems of that type before moving on.
What to practise next
Once these feel easy, move to slightly larger problems: matrix operations, list comprehensions, small classes, and reading and writing files. Then start building something, such as a console app that manages student records with a dictionary and saves them to a JSON file.
These basics are Stage 1 of our Python full stack developer roadmap, which takes you from here to Django, React and a deployed project. For a broader look at Python career tracks, see the Python developer roadmap.
In CodeBegun's Python Full Stack with AI course, problems like these are part of the Core Python module, and placement preparation runs alongside the course. Placement support includes mock interviews, referrals and 5+ interview opportunities, subject to the placement policy and eligibility. Final selection depends on your skills and the employer.
Frequently asked questions
How many Python practice problems should a beginner solve?
Aim for 50 to 100 basic problems before moving on to frameworks like Django. Solving one or two a day for a couple of months builds the habit and the pattern recognition that interviews test.
Should I use built-in functions like max and sorted in practice?
Solve each problem once without them so you understand the logic, then rewrite it with built-ins. Interviewers sometimes ask you to avoid built-ins, and sometimes expect you to know them, so you need both.
What should I do if I cannot solve a problem?
Spend 15 to 20 minutes trying, write down where you are stuck, then read the solution. Close it and write the code again from memory the next day. That second attempt is where most of the learning happens.
Are these problems asked in fresher interviews?
Yes. Reversing strings, palindromes, primes, Fibonacci, duplicates, anagrams and two-sum are among the most common warm-up questions in fresher coding rounds and online tests. Our guide to Python developer jobs for freshers covers what else to prepare.
Which Python version should I use for these exercises?
Any current Python 3 release works. Python 3.12 or newer is a good choice. None of these solutions rely on features from a specific recent version.
Want a trainer to review your solutions? Book a free demo class and see how we teach Python, or download the Python Full Stack syllabus (PDF).
