Python · Syntax · Beginner

Functions level 2

20 tasks

Advanced Python function practice: string and number handling, logical tests, list comprehensions, filtering, counting, finding values, and writing small reusable functions.

Thinking through a function

#
At this level the functions are still small, but the logic inside them requires combining several things you already know — loops, string methods, conditions, and return values. The challenge is not the syntax, it is deciding which tools to use. Before writing the body, ask three questions: what type is the input, what type should come out, and what operation connects them? For counting something in a string — a vowel counter, a letter counter, a word counter — the answer is almost always: loop over the string, check each character, maintain a counter, return it. ```python def count_vowels(text): vowels = "aeiouy" count = 0 for char in text.lower(): if char in vowels: count += 1 return count ``` text.lower() handles case before checking. "A" in "aeiouy" is False — converting first removes that problem. For string transformations — reverse, remove characters, trim edges — slicing and method chaining often give you a one-liner: ```python def reverse_text(text): return text[::-1] def remove_spaces(text): return text.replace(" ", "") def trim_edges(text): return text[1:-1] ``` text[::-1] is a slice with step -1 — it reads the string from the last character to the first. text[1:-1] slices off the first and last character. For numeric properties — last digit, absolute difference, divisibility — think about which arithmetic operator gives you what you need directly: ```python def last_digit(n): return abs(n) % 10 def abs_diff(a, b): return abs(a - b) def divisible_by_3_and_5(n): return n % 3 == 0 and n % 5 == 0 ``` abs() handles negative inputs so the last digit of -47 is still 7, not -7.

Patterns at this level

#
A palindrome check compares the string to its own reverse: ```python def is_palindrome(text): return text == text[::-1] ``` Case sensitivity matters. "Racecar" reversed is "racecaR" — not equal. The exercises here test simple cases, so this form is sufficient. In production you would also strip spaces and convert to lowercase first. Counting words with split: ```python def count_words(text): return len(text.split()) ``` split() with no argument splits on any whitespace and discards empty parts. "hello world".split() gives ["hello", "world"] — two items, not three. Filtering and summing from a tuple: ```python def sum_positive(numbers): total = 0 for n in numbers: if n > 0: total += n return total ``` Removing specific characters — iterate and rebuild: ```python def remove_exclamations(text): result = "" for char in text: if char != "!": result += char return result ``` This works the same way as the punctuation-stripping exercise from the while-loop topic, now wrapped in a function.

String methods, slices, and function patterns reference

#
**String methods used in functions** | Method | Returns | Example | |---|---|---| | `s.lower()` | lowercase copy | `'Hello'.lower()` → `'hello'` | | `s.upper()` | uppercase copy | `'hi'.upper()` → `'HI'` | | `s.replace(old, new)` | copy with replacements | `'a b'.replace(' ', '')` → `'ab'` | | `s.split()` | list of words | `'a b c'.split()` → `['a','b','c']` | | `s.strip()` | copy without edge spaces | `' hi '.strip()` → `'hi'` | | `s.count(sub)` | number of occurrences | `'aabaa'.count('a')` → `4` | | `s.startswith(p)` | bool | `'Py'.startswith('P')` → `True` | | `s.endswith(p)` | bool | `'on'.endswith('n')` → `True` | **Slice patterns** ```python s[::-1] # reverse the whole string s[1:-1] # remove first and last character s[:n] # first n characters s[-n:] # last n characters s[i:j] # characters from index i up to (not including) j ``` **Numeric helpers** ```python abs(-7) # 7 — always non-negative n % 10 # last digit of n (abs first if n can be negative) abs(n) % 10 # last digit, safe for negatives n % d == 0 # True when n is divisible by d ``` **Patterns at this level** ```python # Count characters matching a condition def count_vowels(text): return sum(1 for ch in text.lower() if ch in 'aeiou') # Check a property of the whole string def is_palindrome(text): return text == text[::-1] # Count words def count_words(text): return len(text.split()) # Remove unwanted characters def remove_spaces(text): return text.replace(' ', '') ```
01

Even or Odd.

#

Write a function that takes a number and returns "Even" if the number is even, and "Odd" if it is odd.

def even_or_odd(n):
    pass
Solution
def even_or_odd(n):
    if n % 2 == 0:
        return "Even"
    else:
        return "Odd"

# or you can do this: first get the remainder
def even_or_odd(n):
    rest = n % 2
    if rest == 0:
        return "Even"
    return "Odd"
02

Reverse a string using a function.

#

Write a function that takes a string and returns it in reversed form.

def reverse_text(text):
    pass
Solution
def reverse_text(text):
    return text[::-1]

# or you can do this using a loop
def reverse_text(text):
    result = ""
    for char in text:
        result = char + result
    return result
03

Arithmetic mean.

#

Write a function that takes two numbers and returns their arithmetic mean.

def average(a, b):
    pass
Solution
def average(a, b):
    return (a + b) / 2
04

Counting vowels.

#

Write a function that takes a string and returns the number of vowels in it. Vowels: a, e, i, o, u, y (case does not matter).

def count_vowels(text):
    pass
Solution
def count_vowels(text):
    vowels = "aeiouy"
    count = 0
    for ch in text.lower():
        if ch in vowels:
            count += 1
    return count
05

Divisibility by 3 and 5.

#

Write a function that takes a number and returns True if it is divisible by both 3 and 5, otherwise False .

def divisible_by_3_and_5(n):
    pass
Solution
def divisible_by_3_and_5(n):
    return n % 3 == 0 and n % 5 == 0
06

String without spaces.

#

Write a function that takes a string and returns it without spaces.

def remove_spaces(text):
    pass
Solution
def remove_spaces(text):
    result = ""
    for ch in text:
        if ch != " ":
            result += ch
    return result

# or like this:
def remove_spaces(text):
    return text.replace(" ", "")
07

Sum of positive elements.

#

Write a function that takes a tuple of numbers and returns the sum of positive elements.

def sum_positive(numbers):
    pass
Solution
def sum_positive(numbers):
    total = 0
    for n in numbers:
        if n > 0:
            total += n
    return total
08

Palindrome check.

#

Write a function that takes a string and returns True if it is a palindrome.

def is_palindrome(text):
    pass
Solution
def is_palindrome(text):
    return text == text[::-1]

# or you can do this: prepare the reversed string separately
def is_palindrome(text):
    reversed_text = text[::-1]
    return text == reversed_text
09

Positive, Negative, or Zero.

#

Write a function that takes a number and returns a string: "Positive", "Negative", or "Zero".

def describe_number(n):
    pass
Solution
def describe_number(n):
    if n > 0:
        return "Positive"
    elif n < 0:
        return "Negative"
    else:
        return "Zero"
10

Number of words in a string.

#

Write a function that takes a string and returns the number of words in it. Words are separated by spaces.

def count_words(text):
    pass
Solution
def count_words(text):
    if text == "":
        return 0
    return len(text.split())
11

Multiple of ten.

#

Write a function that takes a number and returns True if it is a multiple of 10, otherwise False .

def is_multiple_of_ten(n):
    pass
Solution
def is_multiple_of_ten(n):
    return n % 10 == 0
12

First and last character using a function.

#

Write a function that takes a string and returns its first and last character as a single string.

def first_and_last(text):
    pass
Solution
def first_and_last(text):
    if text == "":
        return ""
    return text[0] + text[-1]
13

Yes, if greater than 100.

#

Write a function that takes a number and returns the string "Yes" if the number is greater than 100, otherwise "No" .

def more_than_hundred(n):
    pass
Solution
def more_than_hundred(n):
    if n > 100:
        return "Yes"
    return "No"

# Or like this using a ternary operator:
def more_than_hundred(n):
    return "Yes" if n > 100 else "No"
14

Counting the letter a.

#

Write a function that takes a string and returns the number of letters "a" in it (case does not matter).

def count_a(text):
    pass
Solution
def count_a(text):
    count = 0
    for ch in text.lower():
        if ch == "a":
            count += 1
    return count
    
# or
def count_a(text):
    return text.lower().count("a")
15

Absolute difference.

#

Write a function that takes two numbers and returns their absolute difference.

def abs_diff(a, b):
    pass
Solution
def abs_diff(a, b):
    diff = a - b
    if diff < 0:
        diff = -diff
    return diff

# or you can do this using abs
def difference(a, b):
    return abs(a - b)
16

Even length of a string.

#

Write a function that takes a string and returns True if its length is even, otherwise False .

def is_even_length(text):
    pass
Solution
def is_even_length(text):
    return len(text) % 2 == 0
17

Last digit of a number.

#

Write a function that takes an int number and returns the last digit of this number as an int.

def last_digit(n):
    pass
Solution
def last_digit(n):
    if n < 0:
        n = -n
    return n % 10

# or you can do this using a string
def last_digit(n):
    return int(str(abs(n))[-1])
18

Without the first and last letter.

#

Write a function that takes a string and returns it without the first and last letter.

def trim_edges(text):
    pass
Solution
def trim_edges(text):
    if len(text) <= 2:
        return ""
    return text[1:-1]
19

Small, Medium, or Large.

#

Write a function that takes a number and returns a string: - "Small" — if the number is less than 10 - "Medium" — if the number is from 10 to 100 - "Large" — if the number is greater than 100

def size_label(n):
    pass
Solution
def size_label(n):
    if n < 10:
        return "Small"
    elif n <= 100:
        return "Medium"
    else:
        return "Large"
20

Removing exclamation marks.

#

Write a function that takes a string and returns it without all exclamation marks "!" .

def remove_exclamations(text):
    pass
Solution
def remove_exclamations(text):
    result = ""
    for ch in text:
        if ch != "!":
            result += ch
    return result

# or you can do this using replace
def remove_exclamation(text):
    return text.replace("!", "")