# 10 Python Function Practice Exercises for Beginners

Looking to enhance your Python skills through practice? Dive into this collection of Python function practice exercises crafted specifically for beginners!

Functions allow you to encapsulate code into reusable and organized blocks, making your programs more modular and maintainable. As you start your programming career, mastering Python functions is a critical step in your journey. And to help you get there, we’ve curated 10 Python function practice exercises designed specifically for beginners.

These exercises will help you understand and apply functions’ fundamental concepts, enhancing your problem-solving skills and coding proficiency. Each exercise is accompanied by a solution and a concise explanation, guiding you through the thought process behind the code. What’s more, they were taken directly from our practical courses, such as Built-in Algorithms in Python and Python Practice: Word Games. In these courses, you go through dozens of exercises and 10+ hours of content – perfect for improving your coding skills!

If you want to deepen your understanding of Python first, we recommend you check out our Python Basics track. Otherwise, let's dive into our Python function practice and start sharpening your Python skills!

## How Python Functions Work

Before jumping into the Python function exercises, let’s go over a quick reminder of how Python functions work.

To define a function, we write the following elements in a single line:

• The def
• The name of the function (which we can freely choose).
• The function parameters inside parentheses (leave the parentheses empty if there are no parameters).
• A colon ( `:` ) at the end.

Here’s what this looks like:

`	def function_name(parameter1, parameter2):`

Below this line we write the function body, where the steps necessary to the function are laid out. We use indentation (whitespace at the start of the line) to indicate which lines belong to the function body. At its end, we can optionally return a value from the function using the `return` keyword.

Here’s a basic example of a function called `sum_values` that takes two arguments (`a` and `b`) and returns their sum:

```def sum_values(a, b):
result = a + b
return result

# Calling the function for testing
print(sum_values(1, 2))

# output:
# 3
```

If you’re in need of a more thorough refresher on Python functions, read this article on how to define a function in Python.

## Python Function Practice 1: Printing a Sentence Multiple Times

Let’s start simple: Write a Python function that prompts the user to enter a number. Then, given that number, it prints the sentence "Hello, Python!" that many times.

### Solution

```def print_sentence_multiple_times():
num = int(input("Enter a number: "))
for _ in range(num):
print("Hello, Python!")

print_sentence_multiple_times()

# output: (input = 3)
# Hello, Python!
# Hello, Python!
# Hello, Python!
```

### Explanation

In the function `print_sentence_multiple_times()`, we prompt the user to input a number using the `input()` function. Then, we convert the input to an integer using `int()`. Afterward, a for loop is used to iterate that many number of times, printing the sentence "Hello, Python!" in each iteration.

Note that we use _ as the variable name in the `for` loop. This is a Python convention that indicates that the variable name is not important – indeed, we never need to use it in this `for` loop!

## Python Function Practice 2: Counting Uppercase and Lowercase Characters

Write a Python function that takes a string as input and returns a dictionary containing the number of uppercase and lowercase characters in the string. Any characters that cannot be categorized as uppercase or lowercase (e.g., symbols) should be counted as "other".

### Solution

```def count_upper_lower_chars(input_string):
char_count = {"uppercase": 0, "lowercase": 0, "other": 0}
for char in input_string:
if char.isupper():
char_count["uppercase"] += 1
elif char.islower():
char_count["lowercase"] += 1
else:
char_count["other"] += 1
return char_count

sentence = "Hello, Python! How are you?"
result = count_upper_lower_chars(sentence)

print(result)

# output:
# {'uppercase': 3, 'lowercase': 17, 'other': 7}
```

### Explanation

The function `count_upper_lower_chars()` takes a string `input_string` as input and initializes a dictionary `char_count` to store the counts of uppercase, lowercase, and symbols (“other”) characters. Then, it iterates through each character in the input string. For each character, we test if it is uppercase or lowercase, incrementing the respecting value in the `char_count` dictionary. If it’s neither, the count of other characters is incremented instead. Finally, the `char_count` dictionary is returned.

## Python Function Practice 3: Finding the Shortest and Longest Words

Write a Python function that takes a list of strings as input and returns a tuple containing the shortest and longest word from the list, in that order. If there are multiple words of the same shortest or longest length, return the first shortest/longest word found.

### Solution

```def shortest_longest_words(words_list):
shortest_word = min(words_list, key=len)
longest_word = max(words_list, key=len)
return shortest_word, longest_word

words = ["apple", "banana", "kiwi", "grapefruit", "orange"]
result = shortest_longest_words(words)

print(result)

# output:
# ('kiwi', 'grapefruit')
```

### Explanation

The function `shortest_longest_words()` takes a list of strings `words_list` as input and uses the `min()` and `max()` functions to find the shortest and longest words. For this to work, we set the `key` parameter to the `len` function, which means that words will be compared by their lengths.

What if there are multiple candidates for the shortest or longest word? The `min()` and `max()` functions already return the first element, so there’s really nothing to adjust.

At the end, the function returns a tuple containing the shortest and longest words.

## Python Function Practice 4: Check Before You Append

Write a Python function that takes a list and an element as input. The function should add the element to the list only if it's not already present in the list.

### Solution

```def add_unique_element(input_list, element):
if element not in input_list:
input_list.append(element)

my_list = ["apple", "banana", "kiwi"]

print(my_list)

# output:
# ['apple', 'banana', 'kiwi', 'orange']
```

### Explanation

The function `add_unique_element()` takes a list `input_list` and the `element` as input. It first checks if the element is not already in the list using the `not in` operator. If that’s the case, it means that we should append `element` to the `input_list`. Otherwise, we don’t have to do anything; there’s no need for an `else` clause. This logic ensures that only unique elements are added to the list.

## Python Function Practice 5: Removing Duplicates and Sorting

Write a Python function that takes a list of strings as input and returns another list containing the unique elements from the input list, sorted in alphabetical order.

### Solution

```def remove_duplicates_and_sort(input_list):
unique_sorted_list = sorted(set(input_list))
return unique_sorted_list

input_list = ["apple", "banana", "kiwi", "banana", "orange", "apple"]
result = remove_duplicates_and_sort(input_list)

print(result)

# output:
# ['apple', 'banana', 'kiwi', 'orange']
```

### Explanation

The function `remove_duplicates_and_sort()` takes the list of strings `input_list` as input. It then works in a two-step process:

1. First, it creates a set from the input list using `set(input_list)`. Since Python sets have no duplicates in them, this automatically removes duplicate entries from the list.
2. Afterwards, it sorts the unique elements using the `sorted()`

Since `sorted()` always returns a list, we are already done! All that’s left is to return the list.

## Python Function Practice 6: Find the Second Occurrence

Write a Python function that takes a list and an element as input. The function should return the index of the second occurrence of the element in the list. If there are less than two occurrences, the function should return -1.

### Solution

```def second_occurrence_index(input_list, element):
occurrences = []
for index in range(len(input_list)):
if input_list[index] == element:
occurrences.append(index)

if len(occurrences) < 2:
return -1
else:
return occurrences[1]

my_list = ["apple", "banana", "kiwi", "banana", "orange", "banana"]
element = "banana"
index = second_occurrence_index(my_list, element)

print(f"Index of the second occurrence of {element}: {index}")

# output:
# Index of the second occurrence of banana: 3
```

### Explanation

The function `second_occurrence_index()` iterates through the list using a `for` loop with the range of the list's length. In this manner, we iterate over each possible index for the list. For each index, it checks if the element at that index matches the input element. When that’s the case, the index is appended to the `occurrences` list.

Once the for `loop` ends, the function checks if the length of `occurrences` is less than 2. If so, it means that there were either zero or one occurrences, so we should return -1. Otherwise, it returns the index of the second occurrence, which is stored in the `occurrences` list at index 1.

## Python Function Practice 7: Sorting Non-Negative Numbers

Write a Python function that takes a list of numbers as input and returns a sorted list containing only the non-negative numbers from the input list.

### Solution

```def sort_non_negative_numbers(input_list):
non_negative_numbers = []
for num in input_list:
if num >= 0:
non_negative_numbers.append(num)
sorted_non_negative_numbers = sorted(non_negative_numbers)
return sorted_non_negative_numbers

numbers = [5, -3, 0, 9, -2, 7, -1, 4]
result = sort_non_negative_numbers(numbers)

print(result)

# output:
# [0, 4, 5, 7, 9]
```

### Explanation

The function `sort_non_negative_numbers()` iterates through the input list using a `for` loop. For each number in the list, we check if the number is greater than or equal to zero. If it is, it means that the number should be in the output list, so we append it to the `non_negative_numbers` list.

After iterating through the entire input list, we sort the `non_negative_numbers` list using the `sorted()` function. We then return the resulting sorted list, which contains only the non-negative numbers.

## Python Function Practice 8: Calculate the Value of a Word

Write a Python function that takes a word as input and returns its calculated “value”, based on the following rules:

• Consonants are worth 1 point.
• Vowels are worth 3 points.
• The letter "x" is worth 10 points.
• Any other characters are worth 0 points.

### Solution

```def calculate_word_value(word):
value = 0
for char in word:
if char.lower() in 'aeiou':
value += 3
elif char.lower() == 'x':
value += 10
elif char.isalpha():
value += 1
return value

word = "Python"
result = calculate_word_value(word)

print(result)

# output:
# 8
```

### Explanation

The function `calculate_word_value()` takes a word as input and initializes the variable `value`. This variable stores the calculated value of the word, starting from 0. Then, we iterate through each character in the word using a `for` loop.

For each character, we check if it is a vowel (using the string '`aeiou`'), the letter '`x`', or a consonant (using the `str.isalpha()` method). Based on the type of character, it adds the corresponding points to the value. At the end, we return the calculated value of the word.

## Python Function Practice 9: Shifting Characters in the Alphabet

Write a Python function that takes a string as input and returns a new string where every character is shifted by one character in the alphabet. For example, "`A`" becomes "`B`", "`B`" becomes "`C`", and so on.

### Solution

```def shift_characters(input_string):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
shifted_string = ""
for char in input_string:
if char.isalpha():
shifted_char_idx = (alphabet.index(char.lower()) + 1) % 26
shifted_char = alphabet[shifted_char_idx]
if char.isupper():
shifted_string += shifted_char.upper()
else:
shifted_string += shifted_char
else:
shifted_string += char
return shifted_string

sentence = "Hello, Python!"
result = shift_characters(sentence)
print(result)

# output:
# Ifmmp, Qzuipo!
```

### Explanation

This one is rather more complex! Let’s take it step by step.

The function `shift_characters()` starts by taking the input_string as input. In the function, we store the alphabet string that contains all lowercase letters. An empty string called `shifted_string` is created to store the shifted characters.

We then iterate through each character in the input string. For each character, it checks if it's a letter using `char.isalpha()`. If the character is not a letter, the code jumps to the `else` clause and simply adds char to the `shifted_string`, meaning that symbols and spaces are left unchanged.

If the character is a letter, we need to figure out what to add to `shifted_string` – i.e. the next letter in the alphabet. To do this, we first get the index of the shifted character in the alphabet, `shifted_char_idx`. This is done using `alphabet.index()` to get the index of the current character (with `char.lower()` to ignore case). We add the value of 1 to the index to get the index of the next character. Note that we use the modulo operator ( `%` ) so that the resulting index wraps around, avoiding a potential `IndexError`. All this is accomplished in a single line.

Once this is done, we get the `shifted_char` by indexing the `alphabet` string. At this point, all that’s left is to find out if the original character was uppercase or lowercase, adjusting the shifted character accordingly and adding it to the `shifted_string`.

## Python Function Practice 10: Caesar Cipher

Modify the previous Python function to allow for an arbitrary jump, thus effectively creating a Caesar cipher. The function should take a string and an integer (representing the jump) as input. It should return a new string where every character is shifted by the specified jump in the alphabet.

### Solution

```def caesar_cipher(input_string, jump):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
shifted_string = ""
for char in input_string:
if char.isalpha():
shifted_char_idx = (alphabet.index(char.lower()) + jump) % 26
shifted_char = alphabet[shifted_char_idx]
if char.isupper():
shifted_string += shifted_char.upper()
else:
shifted_string += shifted_char
else:
shifted_string += char
return shifted_string

input_str = "Hello, Python!"
jump = 3
result = caesar_cipher(input_str, jump)

print(result)

# output:
# Khoor, Sbwkrq!
```

### Explanation

If you pay close attention, this last one is a freebie! Compared to the previous exercise, the only difference to this `caesar_cipher()` function is that it takes an integer jump along the `input_string`.

Most of the logic from the previous function remains the same. The only difference is in the line where `shifted_char_idx` is defined; we replace the fixed `jump` of 1 by the jump variable. This single modification is enough to change the behavior of our function drastically, effectively creating a proper Caesar cipher!

## Want More Beginner-Friendly Python Function Practice?

Practicing Python functions through hands-on exercises is a fantastic way to solidify your understanding and enhance your coding skills. The exercises provided here – ranging from basic string manipulations to implementing a Caesar cipher – offer a broad spectrum of challenges designed to help beginners grasp fundamental concepts. We hope you enjoyed them!

Remember, the key to mastering programming is consistent practice and exploration of different solutions. If you’re on the lookout for more exercises, we recommend you check out our article on Python practice for beginners and our curated list of Python string exercises.  And for more structured learning and additional practice problems, be sure to explore the Python Basics track. Happy coding!