Python Practice Exercises – Part 5: Functions, Logic, and Algorithm Challenges

Python Practice Exercises – Part 5

In this part, you’ll find a series of Python practice exercises.
Each one focuses on a key programming skill — functions, loops, conditions, and basic algorithms.
Try to solve them first, then check the explanations below.

Exercises

Exercise 1 – Cost Calculation

Write a function that calculates the total cost.
It should take price, quantity, and currency as arguments and return the result.
By default, quantity = 100 and currency = ‘€’.

Example calls:

print(calculate_cost(2))                 # 200 €
print(calculate_cost(2, 2))              # 4 €
print(calculate_cost(2, 2, '$'))         # 4 $
print(calculate_cost(2, currency='$'))   # 200 $

Exercise 2 – Average of Three Numbers

Write a function that takes three numbers, calculates their average, and returns it.

Exercise 3 – Reversible Primes

Write a program that prints all prime numbers up to 1000 that remain prime when their digits are reversed.

Exercise 4 – Sum of Divisors

Write a function that checks whether the sum of all proper divisors of a number (excluding the number itself) is smaller than the number.

Examples:

  • For 81 → 1 + 3 + 9 + 27 = 40 < 81 → True
  • For 80 → 1 + 2 + 4 + 5 + 8 + 10 + 16 + 20 + 40 = 106 > 80 → False

Exercise 5 – Bubble Sort

Write a function that receives a list of numbers and returns it sorted,
using the bubble sort algorithm (compare each element with the next one and swap if needed; repeat until sorted).

Exercise 6 – Smallest of Three Values

Create three random numbers and print which one is the smallest.

Exercise 7 – Min–Max Function

Write your own min_max() function that returns both the smallest and the largest number
from a list – as a tuple – without using min(), max(), or sorted().

Exercise 8 – Password Quality

Write a function that evaluates password strength using this scoring system:

  • ≤ 7 characters → 0 points
  • ≥ 8 characters → +1 point
  • contains both uppercase and lowercase letters → +1 point
  • has more than 6 unique characters → +1 point
  • contains at least one digit → +1 point
  • contains at least one special character → +1 point

Examples:

'abc'          → 0 points  
'abcdefghij'   → 2 points  
'ab1122$$!!'   → 3 points  
'Abcd1234$!'   → 5 points  

Solutions and Explanations

Solution 1 – Cost Calculation

def calculate_cost(price, quantity=100, currency='€'):
    total = price * quantity
    return f"{total} {currency}"

print(calculate_cost(2))                 # 200 €
print(calculate_cost(2, 2))              # 4 €
print(calculate_cost(2, 2, '$'))         # 4 $
print(calculate_cost(2, currency='$'))   # 200 $

Explanation:

  • Default arguments let you skip parameters when you don’t need to change them.
  • If only price is provided, Python uses quantity=100 and currency='€'.
  • The function returns a formatted string like "200 €" or "4 $".

Solution 2 – Average of Three Numbers

def average(a, b, c):
    return (a + b + c) / 3

print(average(3, 6, 9))  # 6.0

Explanation:
Add all three numbers, divide by 3, and return the result.
Parentheses ensure addition happens before division.

Solution 3 – Reversible Primes

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

for num in range(2, 1001):
    if is_prime(num):
        reversed_num = int(str(num)[::-1])
        if is_prime(reversed_num):
            print(num)

Explanation:

  1. The helper function is_prime() checks primality efficiently.
  2. Each number up to 1000 is tested.
  3. Convert the number to a string, reverse it with slicing [::-1], convert back to int, and check again.
  4. If both are prime → print it.
    Examples: 13 ↔ 31, 17 ↔ 71.

Solution 4 – Sum of Divisors

def is_sum_smaller(n):
    divisors = [i for i in range(1, n) if n % i == 0]
    return sum(divisors) < n

print(is_sum_smaller(81))  # True
print(is_sum_smaller(80))  # False

Explanation:

  • The list comprehension collects all divisors less than n.
  • Their sum is compared to n.
  • For 81 → sum = 40 < 81 → True.

Solution 5 – Bubble Sort

def bubble_sort(lst):
    n = len(lst)
    while True:
        swapped = False
        for i in range(n - 1):
            if lst[i] > lst[i + 1]:
                lst[i], lst[i + 1] = lst[i + 1], lst[i]
                swapped = True
        if not swapped:
            break
    return lst

print(bubble_sort([5, 3, 8, 1, 2]))  # [1, 2, 3, 5, 8]

Explanation:

  • Compare each number with its neighbor.
  • Swap if they are out of order.
  • Keep looping until no swaps occur.
    This is one of the simplest sorting algorithms — great for understanding loops and conditionals.

Solution 6 – Smallest of Three Values

import random

a = random.randint(1, 100)
b = random.randint(1, 100)
c = random.randint(1, 100)

print(a, b, c)

smallest = a
if b < smallest:
    smallest = b
if c < smallest:
    smallest = c

print("Smallest value:", smallest)

Explanation:

  • Random numbers are generated using randint().
  • We assume the first one is smallest and compare sequentially.
  • The final smallest value is printed.
    (If you wanted to, you could simply use min(a, b, c), but this way helps practice logic.)

Solution 7 – Min–Max Function

def min_max(lst):
    smallest = largest = lst[0]
    for num in lst[1:]:
        if num < smallest:
            smallest = num
        elif num > largest:
            largest = num
    return (smallest, largest)

print(min_max([4, 1, 9, 3, 7]))  # (1, 9)

Explanation:
We loop through all numbers once.
If we find a smaller or larger value, we update our variables.
Finally, both are returned together as a tuple.

Solution 8 – Password Quality

import string

def password_score(pw):
    if len(pw) <= 7:
        return 0

    score = 1  # length ≥ 8
    if any(c.islower() for c in pw) and any(c.isupper() for c in pw):
        score += 1
    if len(set(pw)) > 6:
        score += 1
    if any(c.isdigit() for c in pw):
        score += 1
    if any(c in string.punctuation for c in pw):
        score += 1
    return score

print(password_score('abc'))         # 0
print(password_score('abcdefghij'))  # 2
print(password_score('ab1122$$!!'))  # 3
print(password_score('Abcd1234$!'))  # 5

Explanation:

  • Check one rule at a time using simple conditions.
  • string.punctuation provides a ready list of special characters.
  • Each rule adds 1 point to the score.

Leave a Reply

Your email address will not be published. Required fields are marked *