16th Oct 2023 12 minutes read 10 Python Practice Exercises for Beginners with Solutions Luke Hande python basics get started with python online practice A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills. Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types. Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level. If you’re new to Python and looking for a structured way to improve your programming, consider taking the Python Basics Practice course. It includes 17 interactive exercises designed to improve all aspects of your programming and get you into good programming habits early. To improve your coding skills consider using a programming homework help service to pay for research paper and get detailed examples of code that works. Take the course Python Practice: Word Games, and you gain experience working with string functions and text files through its 27 interactive exercises. Its release announcement gives you more information and a feel for how it works. Each course has enough material to keep you busy for about 10 hours. To give you a little taste of what these courses teach you, we have selected 10 Python practice exercises straight from these courses. We’ll give you the exercises and solutions with detailed explanations about how they work. To get the most out of this article, have a go at solving the problems before reading the solutions. Some of these practice exercises have a few possible solutions, so also try to come up with an alternative solution after you’ve gone through each exercise. Let’s get started! Exercise 1: User Input and Conditional Statements Write a program that asks the user for a number then prints the following sentence that number of times: ‘I am back to check on my skills!’ If the number is greater than 10, print this sentence instead: ‘Python conditions and loops are a piece of cake.’ Assume you can only pass positive integers. Solution number = int(input("Please enter a number: ")) if number > 10: print("Python conditions and loops are a piece of cake.") else: for i in range(number): print("I am back to check on my skills!") Here, we start by using the built-in function input(), which accepts user input from the keyboard. The first argument is the prompt displayed on the screen; the input is converted into an integer with int() and saved as the variable number. If the variable number is greater than 10, the first message is printed once on the screen. If not, the second message is printed in a loop number times. Exercise 2: Lowercase and Uppercase Characters Below is a string, text. It contains a long string of characters. Your task is to iterate over the characters of the string, count uppercase letters and lowercase letters, and print the result: LOWERCASE: <count> UPPERCASE: <count> Use the string.islower() and string.isupper() methods to check if a string contains lowercase and uppercase characters. text = "ABgvddVICJSdkeprsmgn UTPDvndhtuwPOTNRSjfisuRNSUesajdsa" Solution lowercase_count = 0 uppercase_count = 0 for letter in text: if letter.islower(): lowercase_count += 1 elif letter.isupper(): uppercase_count += 1 print("LOWERCASE:", lowercase_count) print("UPPERCASE:", uppercase_count) We start this one by initializing the two counters for uppercase and lowercase characters. Then, we loop through every letter in text and check if it is lowercase. If so, we increment the lowercase counter by one. If not, we check if it is uppercase and if so, we increment the uppercase counter by one. Finally, we print the results in the required format. Exercise 3: Building Triangles Create a function named is_triangle_possible() that accepts three positive numbers. It should return True if it is possible to create a triangle from line segments of given lengths and False otherwise. With 3 numbers, it is sometimes, but not always, possible to create a triangle: You cannot create a triangle from a = 13, b = 2, and c = 3, but you can from a = 13, b = 9, and c = 10. Solution def is_triangle_possible(a, b, c): return (a+b>c and c+b>a and a+c>b) The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be helpful to start drawing triangles before you start coding anything. Notice that the sum of any two sides must be larger than the third side to form a triangle. That means we need a + b > c, c + b > a, and a + c > b. All three conditions must be met to form a triangle; hence we need the and condition in the solution. Once you have this insight, the solution is easy! Exercise 4: Call a Function From Another Function Create two functions: print_five_times() and speak(). The function print_five_times() should accept one parameter (called sentence) and print it five times. The function speak(sentence, repeat) should have two parameters: sentence (a string of letters), and repeat (a Boolean with a default value set to False). If the repeat parameter is set to False, the function should just print a sentence once. If the repeat parameter is set to True, the function should call the print_five_times() function. Solution def print_five_times(sentence): for i in range(5): print(sentence) def speak(sentence, repeat=False): if repeat: print_five_times(sentence) else: print(sentence) This is a good example of calling a function in another function. It is something you’ll do often in your programming career. It is also a nice demonstration of how to use a Boolean flag to control the flow of your program. If the repeat parameter is True, the print_five_times() function is called, which prints the sentence parameter 5 times in a loop. Otherwise, the sentence parameter is just printed once. Note that in Python, writing if repeat is equivalent to if repeat == True. Exercise 5: Looping and Conditional Statements Write a function called find_greater_than() that takes two parameters: a list of numbers and an integer threshold. The function should create a new list containing all numbers in the input list greater than the given threshold. The order of numbers in the result list should be the same as in the input list. For example: >>> find_greater_than([-3, 2, 8, 15, 31, 5, 4, 8], 5) [8, 15, 31, 8] Solution def find_greater_than(int_list, threshold): new_list = [] for integer in int_list: if integer > threshold: new_list.append(integer) return new_list Here, we start by defining an empty list to store our results. Then, we loop through all elements in the input list and test if the element is greater than the threshold. If so, we append the element to the new list. Notice that we do not explicitly need an else and pass to do nothing when integer is not greater than threshold. You may include this if you like. Exercise 6: Nested Loops and Conditional Statements Write a function called find_censored_words() that accepts a list of strings and a list of special characters as its arguments, and prints all censored words from it one by one in separate lines. A word is considered censored if it has at least one character from the special_chars list. Use the word_list variable to test your function. We've prepared the two lists for you: special_chars = ['!', '@', '#', '$', '%', '^', '&', '*'] word_list = ['se#$et', 'Ver*%&$lo', 'di$#^$nt', 'c*%e', 'is', '#%$#@!@#$%^$#'] Solution special_chars = ['!', '@', '#', '$', '%', '^', '&', '*'] word_list = ['se#$et', 'Ver*%&$lo', 'di$#^$nt', 'c*%e', 'is', '#%$#@!@#$%^$#'] def find_censored_words(word_list, special_chars): for word in word_list: for character in word: if character in special_chars: print(word) break This is another nice example of looping through a list and testing a condition. We start by looping through every word in word_list. Then, we loop through every character in the current word and check if the current character is in the special_chars list. This time, however, we have a break statement. This exits the inner loop as soon as we detect one special character since it does not matter if we have one or several special characters in the word. Exercise 7: Lists and Tuples Create a function find_short_long_word(words_list). The function should return a tuple of the shortest word in the list and the longest word in the list (in that order). If there are multiple words that qualify as the shortest word, return the first shortest word in the list. And if there are multiple words that qualify as the longest word, return the last longest word in the list. For example, for the following list: words = ['go', 'run', 'play', 'see', 'my', 'stay'] the function should return ('go', 'stay') Assume the input list is non-empty. Solution words = ['go', 'run', 'play', 'see', 'my', 'stay'] def find_short_long_word(words_list): shortest_word = words_list[0] longest_word = words_list[0] for word in words_list: if len(word) < len(shortest_word): shortest_word = word elif len(word) >= len(longest_word): longest_word = word return (shortest_word, longest_word) The key to this problem is to start with a “guess” for the shortest and longest words. We do this by creating variables shortest_word and longest_word and setting both to be the first word in the input list. We loop through the words in the input list and check if the current word is shorter than our initial “guess.” If so, we update the shortest_word variable. If not, we check to see if it is longer than or equal to our initial “guess” for the longest word, and if so, we update the longest_word variable. Having the >= condition ensures the longest word is the last longest word. Finally, we return the shortest and longest words in a tuple. Exercise 8: Dictionaries As you see, we've prepared the test_results variable for you. Your task is to iterate over the values of the dictionary and print all names of people who received less than 45 points. test_results = {'Jenny': 50, 'Mathew': 45, 'Joe': 30, 'Peter': 40, 'Agness': 50, 'Samantha': 45, 'John': 20} Solution for key, value in test_results.items(): if value < 45: print(key) Here, we have an example of how to iterate through a dictionary. Dictionaries are useful data structures that allow you to create a key (the names of the students) and attach a value to it (their test results). Dictionaries have the dictionary.items() method, which returns an object with each key:value pair in a tuple. The solution shows how to loop through this object and assign a key and a value to two variables. Then, we test whether the value variable is greater than 45. If so, we print the key variable. Exercise 9: More Dictionaries Write a function called consonant_vowels_count(frequencies_dictionary, vowels) that takes a dictionary and a list of vowels as arguments. The keys of the dictionary are letters and the values are their frequencies. The function should print the total number of consonants and the total number of vowels in the following format: VOWELS: <vowels> CONSONANTS: <consonants> For example, for input: frequencies_dictionary = {'a': 2, 's': 1, 'i': 3, 'u': 3, 'm': 4, 'l': 2, 'z': 1, 'n': 3, 'k': 1, 'e': 4, 'y': 2, 'd': 2, 'o': 1} the output should be: VOWELS: 13 CONSONANTS: 16 Solution vowels = ['a', 'e', 'i', 'u', 'o'] frequencies_dictionary = {'a': 2, 's': 1, 'i': 3, 'u': 3, 'm': 4, 'l': 2, 'z': 1, 'n': 3, 'k': 1, 'e': 4, 'y': 2, 'd': 2, 'o': 1} def consonant_vowels_count(frequencies_dictionary, vowels): vowels_count = 0 consonants_count = 0 for key, values in frequencies_dictionary.items(): if key in vowels: vowels_count += frequencies_dictionary[key] else: consonants_count += frequencies_dictionary[key] print("VOWELS:", vowels_count) print("CONSONANTS:", consonants_count) Working with dictionaries is an important skill. So, here’s another exercise that requires you to iterate through dictionary items. We start by defining a list of vowels. Next, we need to define two counters, one for vowels and one for consonants, both set to zero. Then, we iterate through the input dictionary items and test whether the key is in the vowels list. If so, we increase the vowels counter by one, if not, we increase the consonants counter by one. Finally, we print out the results in the required format. Exercise 10: String Encryption Implement the Caesar cipher. This is a simple encryption technique that substitutes every letter in a word with another letter from some fixed number of positions down the alphabet. For example, consider the string 'word'. If we shift every letter down one position in the alphabet, we have 'xpse'. Shifting by 2 positions gives the string 'yqtf'. Start by defining a string with every letter in the alphabet: alphabet = "abcdefghijklmnopqrstuvwxyz". Name your function cipher(word, shift), which accepts a string to encrypt, and an integer number of positions in the alphabet by which to shift every letter. Solution alphabet = "abcdefghijklmnopqrstuvwxyz" def cipher(word, shift): shifted_alphabet = alphabet[shift:] + alphabet[:shift] new_word = "" for letter in word: letter_index = alphabet.index(letter) new_letter = shifted_alphabet[letter_index] new_word += new_letter return new_word This exercise is taken from the Word Games course. We have our string containing all lowercase letters, from which we create a shifted alphabet using a clever little string-slicing technique. Next, we create an empty string to store our encrypted word. Then, we loop through every letter in the word and find its index, or position, in the alphabet. Using this index, we get the corresponding shifted letter from the shifted alphabet string. This letter is added to the end of the new_word string. This is just one approach to solving this problem, and it only works for lowercase words. Try inputting a word with an uppercase letter; you’ll get a ValueError. When you take the Word Games course, you slowly work up to a better solution step-by-step. This better solution takes advantage of two built-in functions chr() and ord() to make it simpler and more robust. The course contains three similar games, with each game comprising several practice exercises to build up your knowledge. Do You Want More Python Practice Exercises? We have given you a taste of the Python practice exercises available in two of our courses, Python Basics Practice and Python Practice: Word Games. These courses are designed to develop skills important to a successful Python programmer, and the exercises above were taken directly from the courses. Sign up for our platform (it’s free!) to find more exercises like these. We’ve discussed Different Ways to Practice Python in the past, and doing interactive exercises is just one way. Our other tips include reading books, watching videos, and taking on projects. For tips on good books for Python, check out “The 5 Best Python Books for Beginners.” It’s important to get the basics down first and make sure your practice exercises are fun, as we discuss in “What’s the Best Way to Practice Python?” If you keep up with your practice exercises, you’ll become a Python master in no time! Tags: python basics get started with python online practice