IT Training
Blog
Search

15 Python Programming Examples with Solutions for Beginners

Colourful program code on a computer screen

The fastest way to get good at Python is to solve small problems yourself, then compare your code with a clean solution, and these 15 Python programming examples with solutions take you from basics to the kind of tasks asked in fresher coding rounds. Each example has a short problem statement, working code you can run in Python 3, and a note on the idea it teaches.

Key takeaways

  • Try each problem for at least ten minutes before reading the solution, because struggling is where learning happens.
  • The examples cover strings, lists, dictionaries, loops, functions, files and exceptions, which are the core of most fresher tests.
  • Python built-ins such as sum, sorted, enumerate and collections.Counter often replace several lines of manual code.
  • Always test your code with edge cases such as an empty list, zero, negative numbers and repeated values.
  • After these, move on to small projects that combine several examples into one program.

Run the code in any Python 3 environment: IDLE, VS Code, a Jupyter notebook or an online editor. If you have not set Python up yet, start with our guide to learning Python for beginners.

Basic Python programming examples with solutions

1. Check whether a number is even or odd

n = int(input('Enter a number: '))
if n % 2 == 0:
    print(n, 'is even')
else:
    print(n, 'is odd')

Idea: the modulus operator % gives the remainder. Any number with remainder 0 after division by 2 is even. This works for negative numbers too.

2. Find the largest of three numbers

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
print(max(12, 45, 7))       # built-in gives the same result

Idea: write the logic once by hand to show you understand conditions, then mention that max does the job in real code.

3. Sum of digits of a number

def digit_sum(n):
    n = abs(n)
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

print(digit_sum(4729))   # 22

Idea: % 10 takes the last digit and // 10 removes it. This pattern appears in Armstrong number and palindrome number problems.

4. Factorial using a loop and recursion

def factorial_loop(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def factorial_rec(n):
    return 1 if n <= 1 else n * factorial_rec(n - 1)

print(factorial_loop(5), factorial_rec(5))   # 120 120

Idea: both are correct. Interviewers often ask which is better: the loop avoids Python's recursion limit for large n.

5. Fibonacci series up to n terms

def fibonacci(n):
    a, b = 0, 1
    series = []
    for _ in range(n):
        series.append(a)
        a, b = b, a + b
    return series

print(fibonacci(10))   # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Idea: tuple unpacking lets you update two variables in one line without a temporary variable.

6. Check for a prime number

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)])

Idea: you only need to test divisors up to the square root of n, which makes the check much faster for large numbers.

String examples

7. Reverse a string and check for a palindrome

def is_palindrome(text):
    cleaned = ''.join(ch.lower() for ch in text if ch.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome('Madam'))                 # True
print(is_palindrome('Never odd or even'))     # True

Idea: slicing with [::-1] reverses a sequence. Cleaning spaces and case first handles real sentences.

8. Count vowels in a sentence

def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in 'aeiou')

print(count_vowels('Radium Four teaches Python'))   # 9

Idea: a generator expression inside sum counts matches without building a list.

9. Count the frequency of each word

from collections import Counter

text = 'the cat and the dog and the bird'
counts = Counter(text.split())
print(counts.most_common(2))   # [('the', 3), ('and', 2)]

Idea: Counter is a dictionary built for counting. Be ready to also write this with a plain dictionary and get.

10. Check whether two words are anagrams

def are_anagrams(a, b):
    return sorted(a.replace(' ', '').lower()) == sorted(b.replace(' ', '').lower())

print(are_anagrams('Listen', 'Silent'))   # True

List and dictionary examples

11. Remove duplicates while keeping order

def unique(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

print(unique([3, 1, 3, 2, 1]))   # [3, 1, 2]

Idea: list(set(items)) also removes duplicates but does not guarantee the original order. A set gives fast membership checks.

12. Find the second largest number in a list

def second_largest(nums):
    values = sorted(set(nums), reverse=True)
    return values[1] if len(values) > 1 else None

print(second_largest([10, 40, 40, 25]))   # 25

Idea: handle duplicates and the case where every value is the same. Interviewers check edge cases.

13. Merge two dictionaries and add values for common keys

sales_jan = {'pen': 10, 'book': 4}
sales_feb = {'pen': 6, 'bag': 3}

total = dict(sales_jan)
for item, qty in sales_feb.items():
    total[item] = total.get(item, 0) + qty

print(total)   # {'pen': 16, 'book': 4, 'bag': 3}

Files and error handling

14. Read a file and count lines, words and characters

def file_stats(path):
    lines = words = chars = 0
    with open(path, encoding='utf-8') as f:
        for line in f:
            lines += 1
            words += len(line.split())
            chars += len(line)
    return lines, words, chars

print(file_stats('notes.txt'))

Idea: the with statement closes the file automatically, even if an error happens. Reading line by line works for large files.

15. Safe division with exception handling

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print('Cannot divide by zero')
        return None
    except TypeError:
        print('Both values must be numbers')
        return None

print(safe_divide(10, 2))   # 5.0
print(safe_divide(10, 0))   # None

Idea: catch specific exceptions instead of a bare except, so real bugs are not hidden.

How to practise with these examples

  1. Read the problem, close the solution and write your own version.
  2. Test it with normal input and at least two edge cases.
  3. Compare with the solution and note one thing you would change.
  4. Rewrite it a second way, for example with a loop instead of a built-in.
  5. Explain your solution aloud in two or three sentences, as you would in an interview.

When these feel easy, combine them into small programs from our Python projects for beginners, and prepare for theory rounds with our Python interview questions.

Frequently asked questions

How many Python programs should a beginner practise?

There is no magic number. Solving 50 to 100 small problems across strings, lists, dictionaries, loops and functions, and understanding each one, prepares most freshers well for basic coding rounds.

Should I use built-in functions in coding interviews?

Usually yes, but ask the interviewer first. Some want to see the manual logic, such as finding the maximum without max, to check your understanding.

Where can I run Python code without installing anything?

You can use an online Python editor or a notebook service in your browser. For regular practice, installing Python and VS Code on your computer is better.

What should I learn after these examples?

Learn object-oriented programming with classes, then modules and packages, then a library that matches your goal, such as pandas for data or Flask and Django for web development.

Find more Python tutorials in our Python section.

Other articles

Radium4 — IT training blog

Practical, plain-English guides for DevOps, cloud, data, Python, testing and security learners.