Practice: Common Python Programming Problems

« Read the chapter

Q1. Sum of digits

BeginnerCoding

Write code that prints the sum of the digits of 12345.

Goal: Loop over digits.

Q2. Reverse a string

BeginnerCoding

Print the reverse of 'python'.

Goal: Use slicing.

Q3. Count vowels

BeginnerCoding

Print how many vowels are in 'programming language'.

Goal: Count characters.

Q4. Largest of a list without max

IntermediateCoding

Find the largest value in [4, 19, 7, 3] using a loop and print it.

Goal: Track a running best.

Q5. Character frequency

IntermediateCoding

Print a dictionary with the count of each letter in 'banana', in order of first appearance.

Goal: Count with a dictionary.

Q6. Armstrong number

AdvancedCoding

Print True if 153 equals the sum of each digit raised to the number of digits.

Goal: Combine digits and powers.

Q7. FizzBuzz order

BeginnerOutput

What does this print?

Code
for n in [3, 5, 15, 7]:
    if n % 3 == 0:
        print('Fizz')
    elif n % 5 == 0:
        print('Buzz')
    elif n % 15 == 0:
        print('FizzBuzz')
    else:
        print(n)

Goal: Condition order.

Q8. Reverse words

BeginnerOutput

What does this print?

Code
print(' '.join('one two three'.split()[::-1]))

Goal: Reverse a list.

Q9. Palindrome check

IntermediateOutput

What does this print?

Code
def pal(s):
    return s == s[::-1]

print(pal('level'), pal('Level'))

Goal: Case matters.

Q10. Set removes order

IntermediateOutput

What does this print?

Code
items = [5, 5, 6, 5, 7]
print(sorted(set(items)), len(set(items)))

Goal: Use sets.

Q11. Counter output

IntermediateOutput

What does this print?

Code
from collections import Counter
print(Counter('aabbbc').most_common(1))

Goal: Use Counter.

Q12. Fibonacci terms

AdvancedOutput

What does this print?

Code
a, b = 0, 1
for _ in range(6):
    a, b = b, a + b
print(a, b)

Goal: Trace a loop.

Q13. Palindrome never true

IntermediateDebugging

This function should say True for 'noon' but fails for 'Noon'. Fix it.

Code
def pal(s):
    return s == s[::-1]

print(pal('Noon'))

Goal: Normalise input.

Q14. Off by one

BeginnerDebugging

The loop below should print 1 to 5 but stops at 4. Fix it.

Code
for i in range(1, 5):
    print(i)

Goal: Fix off-by-one.

Q15. Second largest bug

AdvancedDebugging

This returns 9 for [5, 9, 9, 7] but the second largest distinct value is 7. Fix it.

Code
nums = [5, 9, 9, 7]
print(sorted(nums)[-2])

Goal: Handle duplicates.

Q16. Choose a data structure

IntermediateConceptual

You need to remove duplicates from a list but keep the first-seen order. Which approach works and why?

Goal: Pick data structures.

Q17. Why test up to square root

IntermediateConceptual

Why does a prime check only need divisors up to the square root of n?

Goal: Explain an optimisation.

Q18. Recursion or loop

AdvancedApplication

Give one reason to prefer a loop for Fibonacci in an interview.

Goal: Compare approaches.