30-Aug-2024
Are you looking to improve your Python skills through practice? Explore this collection of Python function practice exercises specifically crafted for beginners!
Functions allow you to encapsulate code into reusable and organized blocks, making your programs more modular and maintainable. As you embark on your programming journey, mastering Python functions becomes crucial. We’ve curated 10 Python function practice exercises tailored for beginners to assist you in this endeavor.
These exercises will enhance your understanding of fundamental function concepts, sharpen your problem-solving abilities, and boost your coding proficiency. Each exercise comes with a solution and a concise explanation, guiding you through the thought process behind the code. Moreover, these exercises are directly sourced from our practical courses, such as ‘Built-in Algorithms in Python’ and ‘Python Practice: Word Games.’ In these courses, you’ll tackle numerous exercises and benefit from over 10 hours of content – an ideal way to enhance your coding skills.
Before diving into the Python function exercises, let’s quickly review how Python functions function.
To define a function, we assemble the following components in a single line:
Here’s what this structure looks like:
Code:
def my_function(parameter1, parameter2): # Function body goes here # … |
Below this line, we write the function body, laying out the necessary steps for the function. We use indentation (whitespace at the start of the line) to indicate which lines belong to the function body. At the 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:
Code: def sum_values(a, b): result = a + b return result
# Calling the function for testing print(sum_values(1, 2))
# output: # 3 |
If you need a more comprehensive refresher on Python functions, consider reading an article on how to define functions in Python.
Now, let’s dive into a simple Python function practice:
Write a Python function that prompts the user to enter a number. Given that number, the function should print the sentence “Hello, Python!” that many times.
Here’s the solution:
Code:
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 this function print_sentence_multiple_times(), we prompt the user to input a number using the input() function. Next, we convert the input to an integer using int(). Afterward, a for loop is used to iterate that many 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 the variable name is not important – indeed, we never need to use it in a for loop!
Write a Python function that takes a string as input and returns a dictionary with the count of uppercase and lowercase characters in string. Any characters that do not fall into the categories of uppercase or lowercase (such as symbols) should be counted as “other”.
Here is the solution for:
Code:
def count_upper_lower_chars(input_string): char_count = {“uppercase”: 0, “lowercase”: 0, “other”: 0} for char in input_string: if char.super(): 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 other (non-alphabetical) characters. It then iterates through each character in the input string. For each character, it checks if it is uppercase or lowercase, incrementing the corresponding value in the char_count dictionary. If the character is neither uppercase nor lowercase, the count for “other” characters is incremented. Finally, the char_count dictionary is returned.
Write a Python function that takes a list of strings as input and returns a tuple containing the shortest and longest words from the list, in that order. If there are multiple words of the same shortest or longest length, return the first shortest or longest word encountered.
Here is the Solution:
Code:
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. To achieve this, the key parameter is set to the len function, ensuring that the words are compared by their length.
What if there are multiple words with the same shortest or longest length? The min() and max() function automatically return the first occurrence, so no additional adjustments are needed.
The function then returns a tuple containing the shortest and longest words.
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 is not already present in the list.
Here is the Solution:
Code:
def add_unique_element(input_list, element): if element not in input_list: input_list.append(element)
my_list = [“apple”, “banana”, “kiwi”] add_unique_element(my_list, “banana”) add_unique_element(my_list, “orange”)
print(my_list)
# output: # [‘apple’, ‘banana’, ‘kiwi’, ‘orange’] |
Explanation
The function add_unique_element() takes a list, input_list, and an element as input. It first checks if the element is not already in the list using the not in operator. If the element is not present, it is appended to input_list. Otherwise, no action is needed, so there is no need for an else clause. This approach ensures that unique elements are added to the list.
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.
Here is the Solution:
Code:
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 a list of strings, input_list, as input. It then follows a two-step process:
First, it converts the input list to a set using set(input_list). Since Python sets do not allow duplicate values, this step automatically removes any duplicate entries from the list.
Next, it sorts the unique elements using the sorted() function. Since sorted() always returns a list, this step completes the process. The final step is to return the sorted list.
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 the element appears less than twice, the function should return -1.
Here is the Solution:
Code:
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, ranging from 0 to the length of the list. This way, we examine each index of the list. For each index, the function checks if the element at that index matches the input element. If it does, the index is appended to the occurrences list.
After the for loop completes, the function checks whether the length of occurrences is less than 2. If it is, this indicates that there were either zero or one occurrences, so the function returns -1. If there are two or more occurrences, it returns the index of the second occurrence, which is stored in the occurrences list at index 1.
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.
Here is the Solution:
Code: 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, it checks if the number is greater than or equal to zero. If it is, the number is added to the non_negative_numbers list.
Once the entire input list has been processed, the non_negative_numbers list is sorted using the sorted() function. The function then returns the sorted list, which contains only the non-negative numbers.
Write a Python function that takes a word as input and returns its calculated “value” based on the following rules:
Here is the Solution:
Code:
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 a variable, value, to store the calculated value of the word, starting from 0. It then iterates through each character in the word using a for loop.
For each character, the function checks if it is a vowel (using the string ‘aeiou’), the letter ‘x’, or a consonant (using the str.isalpha() method). Depending on the type of character, it adds the corresponding points to value. Finally, the function returns the calculated value of the word.
Write a Python function that takes a string as input and returns a new string where every character is shifted by one place in the alphabet. For example, “A” becomes “B”, “B” becomes “C”, and so on.
Here is the Solution:
Code: 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! |
This one is a bit more complex! Let’s break it down step by step.
The function shift_characters() starts by taking input_string as input. Inside the function, we store a string called the alphabet containing all lowercase letters. We also create an empty string, shifted_string, to store the shifted characters.
Next, we iterate through each character in the input string. For each character, we check if it is a letter using char.isalpha(). If the character is not a letter, the code moves to the else clause and simply adds char to shifted_string, so symbols and spaces remain unchanged.
If the character is a letter, we need to determine which character to add to shifted_string—specifically, the next letter in the alphabet. To achieve this, we first get the index of the character to be shifted in the alphabet, shifted_char_idx. This is done using alphabet.index() to find the index of the current character (with char.lower() to handle case insensitivity). We then add 1 to this index to get the index of the next character. To ensure the index wraps around correctly and avoids a potential IndexError, we use the modulo operator (%). All this is accomplished in a single line.
After determining the shifted_char by indexing into the alphabet string, we check if the original character was uppercase or lowercase, adjust the shifted character accordingly, and add it to shifted_string.
Modify the previous Python function to allow for an arbitrary shift, effectively creating a Caesar cipher. The function should take a string and an integer (representing the shift) as input and return a new string where every character is shifted by the specified amount in the alphabet.
Here is the Solution:
Code: 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 one is quite straightforward! Compared to the previous exercise, the only difference in the caesar_cipher() function is that it now takes an integer jump along with the input_string.
Most of the logic from the previous function remains unchanged. The only alteration is in the line where shifted_char_idx is defined; we replace the fixed shift of 1 with the jump variable. This single modification significantly changes the behavior of our function, effectively turning it into a proper Caesar cipher!
Practicing Python functions through hands-on exercises is an excellent way to strengthen your understanding and improve your coding skills. The exercises provided here—covering everything from basic string manipulations to implementing a Caesar cipher—offer a wide range of challenges designed to help beginners grasp fundamental concepts.
To take your Python skills to the next level, consider enrolling in Python Programming Courses from Learning 360 Courses. They offer comprehensive training to help you master Python and advance your programming abilities.
We hope you found them useful!
2-Dec-2024
19-Nov-2024
11-Nov-2024