• 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?

10 Python Function Practice Exercises for Beginners

Author's photo

  • python basics
  • online practice

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 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:

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:

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.

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".

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.

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.

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.

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

  • 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.
  • 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.

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.

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.

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.

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.

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!

You may also like

python function assignment questions

How Do You Write a SELECT Statement in SQL?

python function assignment questions

What Is a Foreign Key in SQL?

python function assignment questions

Enumerate and Explain All the Basic Elements of an SQL Query

IMAGES

  1. Solved PYTHON In this assignment, you will write a function

    python function assignment questions

  2. Solved Python Assignment 02 1. Write a function named

    python function assignment questions

  3. Assignment questions on functions

    python function assignment questions

  4. 4. Multiple Assignment Function in Python

    python function assignment questions

  5. Assignment Operator in Python

    python function assignment questions

  6. PPT

    python function assignment questions

VIDEO

  1. Python Features

  2. python function #python #coading #programming

  3. python function , defined function , product manipulation and usage

  4. Python function to add #coding #datascience #datamanagement #datascienceacademy #python #hiring

  5. Python Functions

  6. "Python Assignment Operators Explained with Examples