• Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages

Python Projects

  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Exercise with Practice Questions and Solutions

Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you’re a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test your knowledge.

You might have seen various Python tutorials that explain the concepts in detail but that might not be enough to get hold of this language. The best way to learn is by practicing it more and more.

List of Python Programming Exercises

In the below section, we have gathered chapter-wise Python exercises with solutions . So, scroll down to the relevant topics and try to solve the Python program practice set.

Table of Content

  • Conditional Statement Exercises
  • List Exercises
  • String Exercises
  • Tuple Exercises
  • Dictionary Exercises
  • Set Exercises
  • Matrix Exercises
  • Functions Exercises
  • OOPS Exercises
  • Regex Exercises
  • LinkedList Exercises
  • Searching Exercises
  • Sorting Exercises
  • DSA Exercises
  • File Handling Exercises
  • JSON Exercises

To complement the Python exercises, you can further test your skills on the GeeksforGeeks Practice Platform , which includes numerous Python-related challenges and solutions.

Python Exercise

Let’s start with the Conditional Statement Exercise .

Python Conditional Statement Exercises

In this Section, we will explore various exercises involving Python’s conditional statements and loops, providing you with hands-on experience and practical examples to enhance your coding skills.

  • Mark Even and Odd
  • Check the status of Integer
  • Trouble with Angry Friends
  • Check for Equal Occurrences of ‘cat’ and ‘hat’ in a String
  • Conditional Boolean Evaluation
  • Print Characters at Even Indices in a String
  • Print Numbers in Decreasing Order
  • Jumping through While
  • Zero Converter
  • Check if a Number is Odd or Even
  • Program to Print the Natural Numbers
  • Check Prime Number
  • Printing Patterns in Python

Python List Exercises

In this section, we have compiled a variety of Python list exercises that range from basic to advanced levels. These exercises are designed to help you master the fundamentals of Python lists, including list creation, indexing, slicing, and common operations like appending, inserting, and removing elements.

  • Min and Max in Array
  • Union of two arrays
  • Intersection of two sorted arrays
  • Maximum of two numbers in Python
  • Minimum of two numbers in Python
  • Interchange first and last elements in a list
  • Swap two elements in a list
  • Ways to find length of list

>> More Programs on List

Python String Exercises

In this section, we provide a variety of Python string exercises designed to enhance your understanding of string manipulation and operations. Explore these exercises and upsacle your Python programming skills.

  • Exploring String Methods ( swapcase, find, strip… )
  • Exploring String Methods (upper, lower, startswith …)
  • Convert String to LowerCase
  • Reverse Words
  • String Validation and Formatting
  • Slicing in String
  • Repeat the Strings
  • Palindrome String
  • Remove all duplicates from a given string
  • Check Anagram String
  • Reverse words in a given String
  • Find length of a string
  • Print even length words in a string
  • Remove i’th character from string
  • Check whether the string is Symmetrical or Palindrome

>> More Programs on String

Python Tuple Exercises

Here, you’ll find a range of Python tuple exercises designed to help you understand and master this essential data structure. Tuples are immutable sequences used to store collections of items, and they’re a fundamental part of Python programming.

  • Find the size of a Tuple
  • Maximum and Minimum K elements in Tuple
  • Sum of tuple elements
  • Row-wise element Addition in Tuple Matrix
  • Create a list of tuples from given list having number and its cube in each tuple

>> More Programs on Tuple

Python Dictionary Exercises

In this section, you’ll find a variety of Python dictionary exercises designed to help you master the use of dictionaries, one of Python’s most powerful and versatile data structures.

  • Understanding Python Dictionaries
  • Exploring Dictionary Operations
  • Counting Element Frequencies
  • Sort Python Dictionaries by Key or Value
  • Handling missing keys in Dictionaries
  • Python dictionary with keys having multiple inputs
  • Find the sum of all items in a dictionary
  • Find the size of a Dictionary

>> More Programs on Dictionary

Python Set Exercises

This section offers a range of Python set exercises that will help you build a strong understanding of set operations in Python. You’ll practice adding and removing elements, performing operations like union, intersection, and difference, and using set comprehensions.

  • Important functions in Set
  • Operations on Sets
  • Find the size of a Set in Python
  • Iterate over a set in Python
  • Maximum and Minimum in a Set
  • Remove items from Set
  • Check if two lists have atleast one element common

>> More Programs on Sets

Python Matrix Exercises

Here, in this section you’ll find a collection of Python matrix exercises tailored for beginners and advanced Python programmers. These exercises focus on essential skills such as creating and manipulating matrices, performing operations like addition, subtraction, multiplication, and more.

  • Matrix Operations
  • Last cell in a Matrix
  • Rotate a Matrix
  • Assigning Subsequent Rows to Matrix first row elements
  • Adding and Subtracting Matrices in Python
  • Group similar elements into Matrix
  • Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even

>> More Programs on Matrices

Python Functions Exercises

This section offers a variety of exercises focused on Python functions to help you master this essential programming concept. You’ll learn how to define functions, work with parameters and return values, and explore advanced topics like lambda functions, decorators, and recursion.

  • How to get list of parameters name from a function in Python?
  • How to Print Multiple Arguments in Python?
  • Python program to find the power of a number using recursion
  • Sorting objects of user defined class in Python
  • Functions that accept variable length key value pair as arguments

>> More Programs on Functions

Python OOPS Exercises

Here in this practice section, you’ll find exercises focused on Object-Oriented Programming (OOP) concepts in Python . These exercises are designed to help you understand and implement key OOP principles such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction.

  • Python program to build flashcard using class in Python
  • Shuffle a deck of card with OOPS in Python
  • How to create an empty class in Python?
  • Student management system in Python

>> More Programs on Python OOPS

Python Regex Exercises

Python Regex exercises to help you master the art of pattern matching and text manipulation. Regular expressions, or Regex, are powerful tools used to search, match, and manipulate strings based on specific patterns.

  • Extracting Numbers from a String
  • Password Validation with Regex
  • Python program to find the type of IP Address using Regex
  • Python program to find Indices of Overlapping Substrings
  • Python program to extract Strings between HTML Tags
  • Check if String Contain Only Defined Characters using Regex
  • Python program to find files having a particular extension using RegEx

>> More Programs on Python Regex

Python LinkedList Exercises

In this section, we’ve compiled a series of exercises focused on implementing and manipulating linked lists using Python. These exercises cover various operations, such as inserting nodes, deleting nodes, reversing linked lists, and detecting cycles, allowing you to practice and master linked list concepts.

  • Remove loop in Linked List
  • Flattening a Linked List
  • XOR Linked List
  • Python program to Search an Element in a Circular Linked List
  • Pretty print Linked List in Python
  • Stack using Doubly Linked List
  • Queue using Doubly Linked List
  • Python program to find middle of a linked list using one traversal

>> More Programs on Linked Lists

Python Searching Exercises

This section offers a range of exercises designed to help you master searching algorithms in Python. You’ll learn how to implement techniques like linear search and binary search, as well as more advanced methods such as interpolation and exponential search.

  • Pattern searching
  • Binary Search
  • Python Program for Linear Search
  • Python Program for Binary Search (Recursive and Iterative)
  • Python Program for Anagram Substring Search (Or Search for all permutations)

>> More Programs on Python Searching

Python Sorting Exercises

This section provides a collection of exercises to help you practice and understand sorting in Python . You’ll explore various sorting algorithms, like bubble sort, merge sort, quicksort, and others, each with its unique approach to arranging data.

  • Sort a String
  • Counting Sort
  • Topological sort
  • Python Program for Bubble Sort
  • Python Program for QuickSort
  • Python Program for Insertion Sort
  • Python Program for Selection Sort
  • Python Program for Heap Sort

>> More Programs on Python Sorting

Python DSA Exercises

Strengthen your Python skills with Data Structures and Algorithms (DSA) exercises tailored to help you master the fundamental concepts of programming. These exercises cover a wide range of topics, including arrays, linked lists, stacks, queues, trees, graphs, and sorting algorithms, providing a hands-on approach to learning.

  • Python program to reverse a stack
  • Multithreaded Priority Queue in Python
  • Check whether the given string is Palindrome using Stack
  • Program to Calculate the Edge Cover of a Graph
  • Python Program for N Queen Problem

>> More Programs on Python DSA

Python File Handling Exercises

In this section, you’ll find a variety of exercises focused on Python file handling to help you master reading from and writing to files. These exercises will guide you through the essentials, such as opening, reading, writing, closing files and more.

  • Read content from one file and write it into another file
  • Write a dictionary to a file in Python
  • How to check file size in Python?
  • Find the most repeated word in a text file
  • How to read specific lines from a File in Python?

>> More Programs on Python File Handling

Python JSON Exercises

In this section, we provide a variety of exercises to help you master JSON (JavaScript Object Notation) in Python . JSON is a popular data format used for exchanging information between web clients and servers.

  • Convert class object to JSON in Python
  • Convert JSON data Into a Custom Python Object
  • Flattening JSON objects in Python
  • Convert CSV to JSON using Python

>> More Programs on Python JSON

  • Number guessing game in Python
  • 2048 Game in Python
  • Get Live Weather Desktop Notifications Using Python
  • 8-bit game using pygame
  • Tic Tac Toe GUI In Python using PyGame

>> More Projects in Python

What we Offer? The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core python concepts as well as applications of Python in various domains. So if you are at any stage like beginner, intermediate, or advanced this Python practice set will help you to boost your programming skills in Python.

In closing, we just want to say that the practice or solving Python problems always helps to clear your core concepts and programming logic. Hence, we have designed this Python exercises after deep research so that one can easily enhance their skills and logic abilities.

Similar Reads

  • Python Programs

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Practice for Beginners: 15 Hands-On Problems

Author's photo

  • online practice

Want to put your Python skills to the test? Challenge yourself with these 15 Python practice exercises taken directly from our Python courses!

There’s no denying that solving Python exercises is one of the best ways to practice and improve your Python skills . Hands-on engagement with the language is essential for effective learning. This is exactly what this article will help you with: we've curated a diverse set of Python practice exercises tailored specifically for beginners seeking to test their programming skills.

These Python practice exercises cover a spectrum of fundamental concepts, all of which are covered in our Python Data Structures in Practice and Built-in Algorithms in Python courses. Together, both courses add up to 39 hours of content. They contain over 180 exercises for you to hone your Python skills. In fact, the exercises in this article were taken directly from these courses!

In these Python practice exercises, we will use a variety of data structures, including lists, dictionaries, and sets. We’ll also practice basic programming features like functions, loops, and conditionals. Every exercise is followed by a solution and explanation. The proposed solution is not necessarily the only possible answer, so try to find your own alternative solutions. Let’s get right into it!

Python Practice Problem 1: Average Expenses for Each Semester

John has a list of his monthly expenses from last year:

He wants to know his average expenses for each semester. Using a for loop, calculate John’s average expenses for the first semester (January to June) and the second semester (July to December).

Explanation

We initialize two variables, first_semester_total and second_semester_total , to store the total expenses for each semester. Then, we iterate through the monthly_spending list using enumerate() , which provides both the index and the corresponding value in each iteration. If you have never heard of enumerate() before – or if you are unsure about how for loops in Python work – take a look at our article How to Write a for Loop in Python .

Within the loop, we check if the index is less than 6 (January to June); if so, we add the expense to first_semester_total . If the index is greater than 6, we add the expense to second_semester_total .

After iterating through all the months, we calculate the average expenses for each semester by dividing the total expenses by 6 (the number of months in each semester). Finally, we print out the average expenses for each semester.

Python Practice Problem 2: Who Spent More?

John has a friend, Sam, who also kept a list of his expenses from last year:

They want to find out how many months John spent more money than Sam. Use a for loop to compare their expenses for each month. Keep track of the number of months where John spent more money.

We initialize the variable months_john_spent_more with the value zero. Then we use a for loop with range(len()) to iterate over the indices of the john_monthly_spending list.

Within the loop, we compare John's expenses with Sam's expenses for the corresponding month using the index i . If John's expenses are greater than Sam's for a particular month, we increment the months_john_spent_more variable. Finally, we print out the total number of months where John spent more money than Sam.

Python Practice Problem 3: All of Our Friends

Paul and Tina each have a list of their respective friends:

Combine both lists into a single list that contains all of their friends. Don’t include duplicate entries in the resulting list.

There are a few different ways to solve this problem. One option is to use the + operator to concatenate Paul and Tina's friend lists ( paul_friends and tina_friends ). Afterwards, we convert the combined list to a set using set() , and then convert it back to a list using list() . Since sets cannot have duplicate entries, this process guarantees that the resulting list does not hold any duplicates. Finally, we print the resulting combined list of friends.

If you need a refresher on Python sets, check out our in-depth guide to working with sets in Python or find out the difference between Python sets, lists, and tuples .

Python Practice Problem 4: Find the Common Friends

Now, let’s try a different operation. We will start from the same lists of Paul’s and Tina’s friends:

In this exercise, we’ll use a for loop to get a list of their common friends.

For this problem, we use a for loop to iterate through each friend in Paul's list ( paul_friends ). Inside the loop, we check if the current friend is also present in Tina's list ( tina_friends ). If it is, it is added to the common_friends list. This approach guarantees that we test each one of Paul’s friends against each one of Tina’s friends. Finally, we print the resulting list of friends that are common to both Paul and Tina.

Python Practice Problem 5: Find the Basketball Players

You work at a sports club. The following sets contain the names of players registered to play different sports:

How can you obtain a set that includes the players that are only registered to play basketball (i.e. not registered for football or volleyball)?

This type of scenario is exactly where set operations shine. Don’t worry if you never heard about them: we have an article on Python set operations with examples to help get you up to speed.

First, we use the | (union) operator to combine the sets of football and volleyball players into a single set. In the same line, we use the - (difference) operator to subtract this combined set from the set of basketball players. The result is a set containing only the players registered for basketball and not for football or volleyball.

If you prefer, you can also reach the same answer using set methods instead of the operators:

It’s essentially the same operation, so use whichever you think is more readable.

Python Practice Problem 6: Count the Votes

Let’s try counting the number of occurrences in a list. The list below represent the results of a poll where students were asked for their favorite programming language:

Use a dictionary to tally up the votes in the poll.

In this exercise, we utilize a dictionary ( vote_tally ) to count the occurrences of each programming language in the poll results. We iterate through the poll_results list using a for loop; for each language, we check if it already is in the dictionary. If it is, we increment the count; otherwise, we add the language to the dictionary with a starting count of 1. This approach effectively tallies up the votes for each programming language.

If you want to learn more about other ways to work with dictionaries in Python, check out our article on 13 dictionary examples for beginners .

Python Practice Problem 7: Sum the Scores

Three friends are playing a game, where each player has three rounds to score. At the end, the player whose total score (i.e. the sum of each round) is the highest wins. Consider the scores below (formatted as a list of tuples):

Create a dictionary where each player is represented by the dictionary key and the corresponding total score is the dictionary value.

This solution is similar to the previous one. We use a dictionary ( total_scores ) to store the total scores for each player in the game. We iterate through the list of scores using a for loop, extracting the player's name and score from each tuple. For each player, we check if they already exist as a key in the dictionary. If they do, we add the current score to the existing total; otherwise, we create a new key in the dictionary with the initial score. At the end of the for loop, the total score of each player will be stored in the total_scores dictionary, which we at last print.

Python Practice Problem 8: Calculate the Statistics

Given any list of numbers in Python, such as …

 … write a function that returns a tuple containing the list’s maximum value, sum of values, and mean value.

We create a function called calculate_statistics to calculate the required statistics from a list of numbers. This function utilizes a combination of max() , sum() , and len() to obtain these statistics. The results are then returned as a tuple containing the maximum value, the sum of values, and the mean value.

The function is called with the provided list and the results are printed individually.

Python Practice Problem 9: Longest and Shortest Words

Given the list of words below ..

… find the longest and the shortest word in the list.

To find the longest and shortest word in the list, we initialize the variables longest_word and shortest_word as the first word in the list. Then we use a for loop to iterate through the word list. Within the loop, we compare the length of each word with the length of the current longest and shortest words. If a word is longer than the current longest word, it becomes the new longest word; on the other hand, if it's shorter than the current shortest word, it becomes the new shortest word. After iterating through the entire list, the variables longest_word and shortest_word will hold the corresponding words.

There’s a catch, though: what happens if two or more words are the shortest? In that case, since the logic used is to overwrite the shortest_word only if the current word is shorter – but not of equal length – then shortest_word is set to whichever shortest word appears first. The same logic applies to longest_word , too. If you want to set these variables to the shortest/longest word that appears last in the list, you only need to change the comparisons to <= (less or equal than) and >= (greater or equal than), respectively.

If you want to learn more about Python strings and what you can do with them, be sure to check out this overview on Python string methods .

Python Practice Problem 10: Filter a List by Frequency

Given a list of numbers …

… create a new list containing only the numbers that occur at least three times in the list.

Here, we use a for loop to iterate through the number_list . In the loop, we use the count() method to check if the current number occurs at least three times in the number_list . If the condition is met, the number is appended to the filtered_list .

After the loop, the filtered_list contains only numbers that appear three or more times in the original list.

Python Practice Problem 11: The Second-Best Score

You’re given a list of students’ scores in no particular order:

Find the second-highest score in the list.

This one is a breeze if we know about the sort() method for Python lists – we use it here to sort the list of exam results in ascending order. This way, the highest scores come last. Then we only need to access the second to last element in the list (using the index -2 ) to get the second-highest score.

Python Practice Problem 12: Check If a List Is Symmetrical

Given the lists of numbers below …

… create a function that returns whether a list is symmetrical. In this case, a symmetrical list is a list that remains the same after it is reversed – i.e. it’s the same backwards and forwards.

Reversing a list can be achieved by using the reverse() method. In this solution, this is done inside the is_symmetrical function.

To avoid modifying the original list, a copy is created using the copy() method before using reverse() . The reversed list is then compared with the original list to determine if it’s symmetrical.

The remaining code is responsible for passing each list to the is_symmetrical function and printing out the result.

Python Practice Problem 13: Sort By Number of Vowels

Given this list of strings …

… sort the list by the number of vowels in each word. Words with fewer vowels should come first.

Whenever we need to sort values in a custom order, the easiest approach is to create a helper function. In this approach, we pass the helper function to Python’s sorted() function using the key parameter. The sorting logic is defined in the helper function.

In the solution above, the custom function count_vowels uses a for loop to iterate through each character in the word, checking if it is a vowel in a case-insensitive manner. The loop increments the count variable for each vowel found and then returns it. We then simply pass the list of fruits to sorted() , along with the key=count_vowels argument.

Python Practice Problem 14: Sorting a Mixed List

Imagine you have a list with mixed data types: strings, integers, and floats:

Typically, you wouldn’t be able to sort this list, since Python cannot compare strings to numbers. However, writing a custom sorting function can help you sort this list.

Create a function that sorts the mixed list above using the following logic:

  • If the element is a string, the length of the string is used for sorting.
  • If the element is a number, the number itself is used.

As proposed in the exercise, a custom sorting function named custom_sort is defined to handle the sorting logic. The function checks whether each element is a string or a number using the isinstance() function. If the element is a string, it returns the length of the string for sorting; if it's a number (integer or float), it returns the number itself.

The sorted() function is then used to sort the mixed_list using the logic defined in the custom sorting function.

If you’re having a hard time wrapping your head around custom sort functions, check out this article that details how to write a custom sort function in Python .

Python Practice Problem 15: Filter and Reorder

Given another list of strings, such as the one below ..

.. create a function that does two things: filters out any words with three or fewer characters and sorts the resulting list alphabetically.

Here, we define filter_and_sort , a function that does both proposed tasks.

First, it uses a for loop to filter out words with three or fewer characters, creating a filtered_list . Then, it sorts the filtered list alphabetically using the sorted() function, producing the final sorted_list .

The function returns this sorted list, which we print out.

Want Even More Python Practice Problems?

We hope these exercises have given you a bit of a coding workout. If you’re after more Python practice content, head straight for our courses on Python Data Structures in Practice and Built-in Algorithms in Python , where you can work on exciting practice exercises similar to the ones in this article.

Additionally, you can check out our articles on Python loop practice exercises , Python list exercises , and Python dictionary exercises . Much like this article, they are all targeted towards beginners, so you should feel right at home!

You may also like

problem solving using python programming

How Do You Write a SELECT Statement in SQL?

problem solving using python programming

What Is a Foreign Key in SQL?

problem solving using python programming

Enumerate and Explain All the Basic Elements of an SQL Query