Python · Syntax · Beginner

Functions: Level 3

15 tasks

Python Functions Level 3 Exercises: Functions with modes, flags, multiple conditions, string, list, and number handling to develop algorithmic thinking.

Parameters that control behavior

#
These exercises introduce a pattern you will see constantly in real code: a parameter that controls what the function does, rather than what it operates on. The most common forms are a mode string and a boolean flag. A mode string is typically one of a small set of literal values like "add", "sub", "sum", "product". The function branches on it with if/elif: ```python def calculate(a, b, operation): if operation == "add": return a + b elif operation == "sub": return a - b ``` A boolean flag switches between two behaviors. The parameter name usually makes the intent clear: ```python def format_text(text, upper): if upper: return text.upper() else: return text.lower() ``` The key insight is that the data (text, numbers) and the behavior (what to do with it) are both inputs to the function. This makes functions flexible without requiring you to write a separate function for every combination. A common mistake is treating the flag as a string: if upper == True is more fragile than if upper, and if upper == "True" is simply wrong. Boolean parameters are already True or False — use them directly.

Mode and flag patterns

#
Most exercises here combine a mode or flag with a short computation. The if/elif block is the whole function: ```python def scale_number(n, mode): if mode == "double": return n * 2 elif mode == "triple": return n * 3 def combine_numbers(numbers, mode): if mode == "sum": total = 0 for n in numbers: total += n return total elif mode == "product": result = 1 for n in numbers: result *= n return result ``` For tuple or list operations, the mode selects which computation to run — but both branches use the same iteration structure. Boolean flags with two symmetric behaviors: ```python def pick_number(a, b, get_max): if get_max: return a if a >= b else b else: return a if a <= b else b ``` a if condition else b is Python's inline conditional (ternary). It is equivalent to an if/else block but fits in a single expression. Use it when both branches are short. Combining two parameters independently: ```python def maybe_abs(n, use_abs): if use_abs: return abs(n) return n ``` When one branch just returns the input unchanged, you do not need an else — a bare return at the end handles it.

Mode, flag, ternary, and default parameters reference

#
**Mode string pattern** ```python def calculate(a, b, operation): if operation == 'add': return a + b elif operation == 'sub': return a - b elif operation == 'mul': return a * b # optional: handle unknown mode return None ``` **Boolean flag pattern** ```python def format_text(text, upper): # flag controls behavior if upper: return text.upper() return text.lower() # DO NOT do this: if upper == True: # redundant if upper == 'True': # wrong — compares to a string ``` **Ternary expression** ```python # value_if_true if condition else value_if_false result = a if a > b else b # max of two label = 'even' if n % 2 == 0 else 'odd' # equivalent to: if a > b: result = a else: result = b ``` **Default parameter values** ```python def greet(name, greeting='Hello'): return f'{greeting}, {name}!' greet('Alice') # 'Hello, Alice!' greet('Alice', 'Hi') # 'Hi, Alice!' # Rules: # - defaults go at the end of the parameter list # - caller can override them by passing a value # - use immutable defaults only (str, int, None — not lists) ``` **Combining mode and flag** ```python def process(numbers, mode, absolute=False): if mode == 'sum': result = sum(numbers) elif mode == 'max': result = max(numbers) return abs(result) if absolute else result ```
01

Double or triple mode.

#

Write a function that takes a number and a mode string: "double" or "triple". If the mode is "double" — return the number multiplied by 2, if "triple" — multiplied by 3.

def scale_number(n, mode):
    pass
Solution
def scale_number(n, mode):
    if mode == "double":
        return n * 2
    elif mode == "triple":
        return n * 3
02

Uppercase flag.

#

Write a function that takes a string and a boolean value. If the upper flag is True — return the string in uppercase, otherwise — in lowercase.

def format_text(text, upper):
    pass
Solution
def format_text(text, upper):
    if upper:
        return text.upper()
    else:
        return text.lower()
03

Add or sub operation.

#

Write a function that takes two numbers and an operation string: "add" or "sub". Return the sum or difference depending on the operation.

def calculate(a, b, operation):
    pass
Solution
def calculate(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "sub":
        return a - b
04

Conditional reverse.

#

Write a function that takes a string and a number. If the number is greater than 5 — return the string reversed, otherwise — return the string unchanged.

def conditional_reverse(text, limit):
    pass
Solution
def conditional_reverse(text, limit):
    if limit > 5:
        return text[::-1]
    else:
        return text
05

Absolute value by flag.

#

Write a function that takes a number and a flag. If the flag is True — return the absolute value, if False — return the number as is.

def maybe_abs(n, use_abs):
    pass
Solution
def maybe_abs(n, use_abs):
    if use_abs and n < 0:
        return -n
    return n

# Or better like this:
def maybe_abs(n, use_abs):
    if use_abs:
        return abs(n)
    return n
06

First or last mode.

#

Write a function that takes a string and a mode: "first" or "last". Return either the first character of the string or the last one.

def pick_char(text, mode):
    pass
Solution
def pick_char(text, mode):
    if text == "":
        return ""
    if mode == "first":
        return text[0]
    elif mode == "last":
        return text[-1]
07

Sum or product.

#

Write a function that takes a tuple of numbers and a mode: "sum" or "product". Return the sum or product of all elements.

def combine_numbers(numbers, mode):
    pass
Solution
def combine_numbers(numbers, mode):
    if mode == "sum":
        return sum(numbers)
    elif mode == "product":
        result = 1
        for n in numbers:
            result *= n
        return result
08

Removing spaces by flag.

#

Write a function that takes a string and a flag. If the flag is True — remove all spaces, if False — return the string unchanged.

def clean_spaces(text, remove):
    pass
Solution
def clean_spaces(text, remove):
    if not remove:
        return text
    return text.replace(" ", "")
09

Even or odd mode.

#

Write a function that takes a number and a mode: "even" or "odd". Return True if the number matches the mode.

def check_parity(n, mode):
    pass
Solution
def check_parity(n, mode):
    if mode == "even":
        return n % 2 == 0
    elif mode == "odd":
        return n % 2 != 0
10

First or last 3 characters.

#

Write a function that takes a string and a mode: "short" or "long". If the mode is "short" — return the first 3 characters, if "long" — the last 3 characters.

def slice_text(text, mode):
    pass
Solution
def slice_text(text, mode):
    if len(text) < 3:
        return text
    if mode == "short":
        return text[:3]
    elif mode == "long":
        return text[-3:]
11

Larger or smaller by flag.

#

Write a function that takes two numbers and a flag. If the flag is True — return the larger number, if False — the smaller one.

def pick_number(a, b, get_max):
    pass
Solution
def pick_number(a, b, get_max):
    if get_max:
        return a if a > b else b
    else:
        return a if a < b else b
12

Count or length.

#

Write a function that takes a string and a mode: "count" or "length". If the mode is "count" — return the number of letters "a", if "length" — the length of the string.

def analyze_text(text, mode):
    pass
Solution
def analyze_text(text, mode):
    if mode == "length":
        return len(text)
    elif mode == "count":
        cnt = 0
        for ch in text.lower():
            if ch == "a":
                cnt += 1
        return cnt
13

Square or cube.

#

Write a function that takes a number and a flag. If the flag is True — return the square of the number, if False — the cube of the number.

def power_by_flag(n, square):
    pass
Solution
def power_by_flag(n, square):
    if square:
        return n * n
    else:
        return n * n * n
14

Trim start or end.

#

Write a function that takes a string and a mode: "start" or "end". If "start" — return the string without the first 2 characters, if "end" — without the last 2.

def trim_text(text, mode):
    pass
Solution
def trim_text(text, mode):
    if len(text) <= 2:
        return ""
    if mode == "start":
        return text[2:]
    elif mode == "end":
        return text[:-2]
15

Sign or abs.

#

Write a function that takes a number and a mode: "sign" or "abs". If the mode is "sign" — return the string "positive", "negative", or "zero", if "abs" — return the absolute value of the number.

def number_info(n, mode):
    pass
Solution
def number_info(n, mode):
    if mode == "abs":
        return -n if n < 0 else n
    elif mode == "sign":
        if n > 0:
            return "positive"
        elif n < 0:
            return "negative"
        else:
            return "zero"