• Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs

Python Projects

  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

Python Exercise with Practice Questions and Solutions

  • Python List Exercise
  • Python String Exercise
  • Python Tuple Exercise
  • Python Dictionary Exercise
  • Python Set Exercise

Python Matrix Exercises

  • Python program to a Sort Matrix by index-value equality count
  • Python Program to Reverse Every Kth row in a Matrix
  • Python Program to Convert String Matrix Representation to Matrix
  • Python - Count the frequency of matrix row length
  • Python - Convert Integer Matrix to String Matrix
  • Python Program to Convert Tuple Matrix to Tuple List
  • Python - Group Elements in Matrix
  • Python - Assigning Subsequent Rows to Matrix first row elements
  • Adding and Subtracting Matrices in Python
  • Python - Convert Matrix to dictionary
  • Python - Convert Matrix to Custom Tuple Matrix
  • Python - Matrix Row subset
  • Python - Group similar elements into Matrix
  • Python - Row-wise element Addition in Tuple Matrix
  • Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even

Python Functions Exercises

  • Python splitfields() Method
  • 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
  • Assign Function to a Variable in Python
  • Returning a function from a function - Python
  • What are the allowed characters in Python function names?
  • Defining a Python function at runtime
  • Explicitly define datatype in a Python function
  • Functions that accept variable length key value pair as arguments
  • How to find the number of arguments in a Python function?
  • How to check if a Python variable exists?
  • Python - Get Function Signature
  • Python program to convert any base to decimal by using int() method

Python Lambda Exercises

  • Python - Lambda Function to Check if value is in a List
  • Difference between Normal def defined function and Lambda
  • Python: Iterating With Python Lambda
  • How to use if, else & elif in Python Lambda Functions
  • Python - Lambda function to find the smaller value between two elements
  • Lambda with if but without else in Python
  • Python Lambda with underscore as an argument
  • Difference between List comprehension and Lambda in Python
  • Nested Lambda Function in Python
  • Python lambda
  • Python | Sorting string using order defined by another string
  • Python | Find fibonacci series upto n using lambda
  • Overuse of lambda expressions in Python
  • Python program to count Even and Odd numbers in a List
  • Intersection of two arrays in Python ( Lambda expression and filter function )

Python Pattern printing Exercises

  • Simple Diamond Pattern in Python
  • Python - Print Heart Pattern
  • Python program to display half diamond pattern of numbers with star border
  • Python program to print Pascal's Triangle
  • Python program to print the Inverted heart pattern
  • Python Program to print hollow half diamond hash pattern
  • Program to Print K using Alphabets
  • Program to print half Diamond star pattern
  • Program to print window pattern
  • Python Program to print a number diamond of any given size N in Rangoli Style
  • Python program to right rotate n-numbers by 1
  • Python Program to print digit pattern
  • Print with your own font using Python !!
  • Python | Print an Inverted Star Pattern
  • Program to print the diamond shape

Python DateTime Exercises

  • Python - Iterating through a range of dates
  • How to add time onto a DateTime object in Python
  • How to add timestamp to excel file in Python
  • Convert string to datetime in Python with timezone
  • Isoformat to datetime - Python
  • Python datetime to integer timestamp
  • How to convert a Python datetime.datetime to excel serial date number
  • How to create filename containing date or time in Python
  • Convert "unknown format" strings to datetime objects in Python
  • Extract time from datetime in Python
  • Convert Python datetime to epoch
  • Python program to convert unix timestamp string to readable date
  • Python - Group dates in K ranges
  • Python - Divide date range to N equal duration
  • Python - Last business day of every month in year

Python OOPS Exercises

  • Get index in the list of objects by attribute in Python
  • Python program to build flashcard using class in Python
  • How to count number of instances of a class in Python?
  • Shuffle a deck of card with OOPS in Python
  • What is a clean and Pythonic way to have multiple constructors in Python?
  • How to Change a Dictionary Into a Class?
  • How to create an empty class in Python?
  • Student management system in Python
  • How to create a list of object in Python class

Python Regex Exercises

  • Validate an IP address using Python without using RegEx
  • Python program to find the type of IP Address using Regex
  • Converting a 10 digit phone number to US format using Regex in Python
  • Python program to find Indices of Overlapping Substrings
  • Python program to extract Strings between HTML Tags
  • Python - Check if String Contain Only Defined Characters using Regex
  • How to extract date from Excel file using Pandas?
  • Python program to find files having a particular extension using RegEx
  • How to check if a string starts with a substring using regex in Python?
  • How to Remove repetitive characters from words of the given Pandas DataFrame using Regex?
  • Extract punctuation from the specified column of Dataframe using Regex
  • Extract IP address from file using Python
  • Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
  • Categorize Password as Strong or Weak using Regex in Python
  • Python - Substituting patterns in text using regex

Python LinkedList Exercises

  • Python program to Search an Element in a Circular Linked List
  • Implementation of XOR Linked List in Python
  • Pretty print Linked List in Python
  • Python Library for Linked List
  • Python | Stack using Doubly Linked List
  • Python | Queue using Doubly Linked List
  • Program to reverse a linked list using Stack
  • Python program to find middle of a linked list using one traversal
  • Python Program to Reverse a linked list

Python Searching Exercises

  • Binary Search (bisect) in Python
  • Python Program for Linear Search
  • Python Program for Anagram Substring Search (Or Search for all permutations)
  • Python Program for Binary Search (Recursive and Iterative)
  • Python Program for Rabin-Karp Algorithm for Pattern Searching
  • Python Program for KMP Algorithm for Pattern Searching

Python Sorting Exercises

  • Python Code for time Complexity plot of Heap Sort
  • Python Program for Stooge Sort
  • Python Program for Recursive Insertion Sort
  • Python Program for Cycle Sort
  • Bisect Algorithm Functions in Python
  • Python Program for BogoSort or Permutation Sort
  • Python Program for Odd-Even Sort / Brick Sort
  • Python Program for Gnome Sort
  • Python Program for Cocktail Sort
  • Python Program for Bitonic Sort
  • Python Program for Pigeonhole Sort
  • Python Program for Comb Sort
  • Python Program for Iterative Merge Sort
  • Python Program for Binary Insertion Sort
  • Python Program for ShellSort

Python DSA Exercises

  • Saving a Networkx graph in GEXF format and visualize using Gephi
  • Dumping queue into list or array in Python
  • Python program to reverse a stack
  • Python - Stack and StackSwitcher in GTK+ 3
  • Multithreaded Priority Queue in Python
  • Python Program to Reverse the Content of a File using Stack
  • Priority Queue using Queue and Heapdict module in Python
  • Box Blur Algorithm - With Python implementation
  • Python program to reverse the content of a file and store it in another file
  • Check whether the given string is Palindrome using Stack
  • Take input from user and store in .txt file in Python
  • Change case of all characters in a .txt file using Python
  • Finding Duplicate Files with Python

Python File Handling Exercises

  • Python Program to Count Words in Text File
  • Python Program to Delete Specific Line from File
  • Python Program to Replace Specific Line in File
  • Python Program to Print Lines Containing Given String in File
  • Python - Loop through files of certain extensions
  • Compare two Files line by line in Python
  • How to keep old content when Writing to Files in Python?
  • How to get size of folder using Python?
  • How to read multiple text files from folder in Python?
  • Read a CSV into list of lists in Python
  • Python - Write dictionary of list to CSV
  • Convert nested JSON to CSV in Python
  • How to add timestamp to CSV file in Python

Python CSV Exercises

  • How to create multiple CSV files from existing CSV file using Pandas ?
  • How to read all CSV files in a folder in Pandas?
  • How to Sort CSV by multiple columns in Python ?
  • Working with large CSV files in Python
  • How to convert CSV File to PDF File using Python?
  • Visualize data from CSV file in Python
  • Python - Read CSV Columns Into List
  • Sorting a CSV object by dates in Python
  • Python program to extract a single value from JSON response
  • Convert class object to JSON in Python
  • Convert multiple JSON files to CSV Python
  • Convert JSON data Into a Custom Python Object
  • Convert CSV to JSON using Python

Python JSON Exercises

  • Flattening JSON objects in Python
  • Saving Text, JSON, and CSV to a File in Python
  • Convert Text file to JSON in Python
  • Convert JSON to CSV in Python
  • Convert JSON to dictionary in Python
  • Python Program to Get the File Name From the File Path
  • How to get file creation and modification date or time in Python?
  • Menu driven Python program to execute Linux commands
  • Menu Driven Python program for opening the required software Application
  • Open computer drives like C, D or E using Python

Python OS Module Exercises

  • Rename a folder of images using Tkinter
  • Kill a Process by name using Python
  • Finding the largest file in a directory using Python
  • Python - Get list of running processes
  • Python - Get file id of windows file
  • Python - Get number of characters, words, spaces and lines in a file
  • Change current working directory with Python
  • How to move Files and Directories in Python
  • How to get a new API response in a Tkinter textbox?
  • Build GUI Application for Guess Indian State using Tkinter Python
  • How to stop copy, paste, and backspace in text widget in tkinter?
  • How to temporarily remove a Tkinter widget without using just .place?
  • How to open a website in a Tkinter window?

Python Tkinter Exercises

  • Create Address Book in Python - Using Tkinter
  • Changing the colour of Tkinter Menu Bar
  • How to check which Button was clicked in Tkinter ?
  • How to add a border color to a button in Tkinter?
  • How to Change Tkinter LableFrame Border Color?
  • Looping through buttons in Tkinter
  • Visualizing Quick Sort using Tkinter in Python
  • How to Add padding to a tkinter widget only on one side ?
  • Python NumPy - Practice Exercises, Questions, and Solutions
  • Pandas Exercises and Programs
  • How to get the Daily News using Python
  • How to Build Web scraping bot in Python
  • Scrape LinkedIn Using Selenium And Beautiful Soup in Python
  • Scraping Reddit with Python and BeautifulSoup
  • Scraping Indeed Job Data Using Python

Python Web Scraping Exercises

  • How to Scrape all PDF files in a Website?
  • How to Scrape Multiple Pages of a Website Using Python?
  • Quote Guessing Game using Web Scraping in Python
  • How to extract youtube data in Python?
  • How to Download All Images from a Web Page in Python?
  • Test the given page is found or not on the server Using Python
  • How to Extract Wikipedia Data in Python?
  • How to extract paragraph from a website and save it as a text file?
  • Automate Youtube with Python
  • Controlling the Web Browser with Python
  • How to Build a Simple Auto-Login Bot with Python
  • Download Google Image Using Python and Selenium
  • How To Automate Google Chrome Using Foxtrot and Python

Python Selenium Exercises

  • How to scroll down followers popup in Instagram ?
  • How to switch to new window in Selenium for Python?
  • Python Selenium - Find element by text
  • How to scrape multiple pages using Selenium in Python?
  • Python Selenium - Find Button by text
  • Web Scraping Tables with Selenium and Python
  • Selenium - Search for text on page
  • Python Projects - Beginner to Advanced

Python Exercise: Practice makes you perfect in everything. This proverb always proves itself correct. Just like this, if you are a Python learner, then regular practice of Python exercises makes you more confident and sharpens your skills. So, to test your skills, go through these Python exercises with solutions.

Python is a widely used general-purpose high-level language that can be used for many purposes like creating GUI, web Scraping, web development, etc. 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 practising it more and more.

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.

problem solving python questions

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.

Python List Exercises

  • Python program to interchange first and last elements in a list
  • Python program to swap two elements in a list
  • Python | Ways to find length of list
  • Maximum of two numbers in Python
  • Minimum of two numbers in Python

>> More Programs on List

Python String Exercises

  • Python program to check whether the string is Symmetrical or Palindrome
  • Reverse words in a given String in Python
  • Ways to remove i’th character from string in Python
  • Find length of a string in python (4 ways)
  • Python program to print even length words in a string

>> More Programs on String

Python Tuple Exercises

  • Python program to Find the size of a Tuple
  • Python – Maximum and Minimum K elements in Tuple
  • Python – Sum of tuple elements
  • Python – 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

  • Python | Sort Python Dictionaries by Key or Value
  • Handling missing keys in Python dictionaries
  • Python dictionary with keys having multiple inputs
  • Python program to find the sum of all items in a dictionary
  • Python program to find the size of a Dictionary

>> More Programs on Dictionary

Python Set Exercises

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

>> More Programs on Sets

  • Python – Assigning Subsequent Rows to Matrix first row elements
  • Python – Group similar elements into Matrix

>> More Programs on Matrices

>> More Programs on Functions

  • Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function

>> More Programs on Lambda

  • Programs for printing pyramid patterns in Python

>> More Programs on Python Pattern Printing

  • Python program to get Current Time
  • Get Yesterday’s date using Python
  • Python program to print current year, month and day
  • Python – Convert day number to date in particular year
  • Get Current Time in different Timezone using Python

>> More Programs on DateTime

>> More Programs on Python OOPS

  • Python – Check if String Contain Only Defined Characters using Regex

>> More Programs on Python Regex

>> More Programs on Linked Lists

>> More Programs on Python Searching

  • 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

  • Program to Calculate the Edge Cover of a Graph
  • Python Program for N Queen Problem

>> More Programs on Python DSA

  • 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

  • Update column value of CSV in Python
  • How to add a header to a CSV file in Python?
  • Get column names from CSV using Python
  • Writing data from a Python List to CSV row-wise

>> More Programs on Python CSV

>> More Programs on Python JSON

  • Python Script to change name of a file to its timestamp

>> More Programs on OS Module

  • Python | Create a GUI Marksheet using Tkinter
  • Python | ToDo GUI Application using Tkinter
  • Python | GUI Calendar using Tkinter
  • File Explorer in Python using Tkinter
  • Visiting Card Scanner GUI Application using Python

>> More Programs on Python Tkinter

NumPy Exercises

  • How to create an empty and a full NumPy array?
  • Create a Numpy array filled with all zeros
  • Create a Numpy array filled with all ones
  • Replace NumPy array elements that doesn’t satisfy the given condition
  • Get the maximum value from given matrix

>> More Programs on NumPy

Pandas Exercises

  • Make a Pandas DataFrame with two-dimensional list | Python
  • How to iterate over rows in Pandas Dataframe
  • Create a pandas column using for loop
  • Create a Pandas Series from array
  • Pandas | Basic of Time Series Manipulation

>> More Programs on Python Pandas

>> More Programs on Web Scraping

  • Download File in Selenium Using Python
  • Bulk Posting on Facebook Pages using Selenium
  • Google Maps Selenium automation using Python
  • Count total number of Links In Webpage Using Selenium In Python
  • Extract Data From JustDial using Selenium

>> More Programs on Python Selenium

  • 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

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.

Please Login to comment...

Similar reads.

  • CBSE Exam Format Changed for Class 11-12: Focus On Concept Application Questions
  • 10 Best Waze Alternatives in 2024 (Free)
  • 10 Best Squarespace Alternatives in 2024 (Free)
  • Top 10 Owler Alternatives & Competitors in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Say "Hello, World!" With Python Easy Max Score: 5 Success Rate: 96.26%

Python if-else easy python (basic) max score: 10 success rate: 89.73%, arithmetic operators easy python (basic) max score: 10 success rate: 97.42%, python: division easy python (basic) max score: 10 success rate: 98.68%, loops easy python (basic) max score: 10 success rate: 98.11%, write a function medium python (basic) max score: 10 success rate: 90.31%, print function easy python (basic) max score: 20 success rate: 97.26%, list comprehensions easy python (basic) max score: 10 success rate: 97.69%, find the runner-up score easy python (basic) max score: 10 success rate: 94.15%, nested lists easy python (basic) max score: 10 success rate: 91.65%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

10 Python Practice Exercises for Beginners With Detailed Solutions

Author's photo

  • 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. Read about the course in the March 2023 episode of our series Python Course of the Month .

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.

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:

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.

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.

Python Practice Exercises for Beginners

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.

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:

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:

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:

the function should return

Assume the input list is non-empty.

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.

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:

For example, for input:

the output should be:

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:

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.

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!

You may also like

problem solving python questions

How Do You Write a SELECT Statement in SQL?

problem solving python questions

What Is a Foreign Key in SQL?

problem solving python questions

Enumerate and Explain All the Basic Elements of an SQL Query

Pythonista Planet Logo

35 Python Programming Exercises and Solutions

To understand a programming language deeply, you need to practice what you’ve learned. If you’ve completed learning the syntax of Python programming language, it is the right time to do some practice programs.

In this article, I’ll list down some problems that I’ve done and the answer code for each exercise. Analyze each problem and try to solve it by yourself. If you have any doubts, you can check the code that I’ve provided below. I’ve also attached the corresponding outputs.

1. Python program to check whether the given number is even or not.

2. python program to convert the temperature in degree centigrade to fahrenheit, 3. python program to find the area of a triangle whose sides are given, 4. python program to find out the average of a set of integers, 5. python program to find the product of a set of real numbers, 6. python program to find the circumference and area of a circle with a given radius, 7. python program to check whether the given integer is a multiple of 5, 8. python program to check whether the given integer is a multiple of both 5 and 7, 9. python program to find the average of 10 numbers using while loop, 10. python program to display the given integer in a reverse manner, 11. python program to find the geometric mean of n numbers, 12. python program to find the sum of the digits of an integer using a while loop, 13. python program to display all the multiples of 3 within the range 10 to 50, 14. python program to display all integers within the range 100-200 whose sum of digits is an even number, 15. python program to check whether the given integer is a prime number or not, 16. python program to generate the prime numbers from 1 to n, 17. python program to find the roots of a quadratic equation, 18. python program to print the numbers from a given number n till 0 using recursion, 19. python program to find the factorial of a number using recursion, 20. python program to display the sum of n numbers using a list, 21. python program to implement linear search, 22. python program to implement binary search, 23. python program to find the odd numbers in an array, 24. python program to find the largest number in a list without using built-in functions, 25. python program to insert a number to any position in a list, 26. python program to delete an element from a list by index, 27. python program to check whether a string is palindrome or not, 28. python program to implement matrix addition, 29. python program to implement matrix multiplication, 30. python program to check leap year, 31. python program to find the nth term in a fibonacci series using recursion, 32. python program to print fibonacci series using iteration, 33. python program to print all the items in a dictionary, 34. python program to implement a calculator to do basic operations, 35. python program to draw a circle of squares using turtle.

problem solving python questions

For practicing more such exercises, I suggest you go to  hackerrank.com  and sign up. You’ll be able to practice Python there very effectively.

Once you become comfortable solving coding challenges, it’s time to move on and build something cool with your skills. If you know Python but haven’t built an app before, I suggest you check out my  Create Desktop Apps Using Python & Tkinter  course. This interactive course will walk you through from scratch to building clickable apps and games using Python.

I hope these exercises were helpful to you. If you have any doubts, feel free to let me know in the comments.

Happy coding.

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

11 thoughts on “ 35 Python Programming Exercises and Solutions ”

I don’t mean to nitpick and I don’t want this published but you might want to check code for #16. 4 is not a prime number.

Thanks man for pointing out the mistake. I’ve updated the code.

# 8. Python program to check whether the given integer is a multiple of both 5 and 7:

You can only check if integer is a multiple of 35. It always works the same – just multiply all the numbers you need to check for multiplicity.

For reverse the given integer n=int(input(“enter the no:”)) n=str(n) n=int(n[::-1]) print(n)

very good, tnks

Please who can help me with this question asap

A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs $0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the entire bill (including the 911 charge) is subject to 5 percent sales tax.

We are so to run the code in phyton

this is best app

Hello Ashwin, Thanks for sharing a Python practice

May be in a better way for reverse.

#”’ Reverse of a string

v_str = str ( input(‘ Enter a valid string or number :- ‘) ) v_rev_str=” for v_d in v_str: v_rev_str = v_d + v_rev_str

print( ‘reverse of th input string / number :- ‘, v_str ,’is :- ‘, v_rev_str.capitalize() )

#Reverse of a string ”’

Problem 15. When searching for prime numbers, the maximum search range only needs to be sqrt(n). You needlessly continue the search up to //n. Additionally, you check all even numbers. As long as you declare 2 to be prime, the rest of the search can start at 3 and check every other number. Another big efficiency improvement.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name and email in this browser for the next time I comment.

Recent Posts

Introduction to Modular Programming with Flask

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules. In this tutorial, let's understand what modular...

Introduction to ORM with Flask-SQLAlchemy

While Flask provides the essentials to get a web application up and running, it doesn't force anything upon the developer. This means that many features aren't included in the core framework....

problem solving python questions

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python exercises.

You can test your Python skills with W3Schools' Exercises.

We have gathered a variety of Python exercises (with answers) for each Python Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start Python Exercises

Start Python Exercises ❯

If you don't know Python, we suggest that you read our Python Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Python Wife Logo

  • Computer Vision
  • Problem Solving in Python
  • Intro to DS and Algo
  • Analysis of Algorithm
  • Dictionaries
  • Linked Lists
  • Doubly Linked Lists
  • Circular Singly Linked List
  • Circular Doubly Linked List
  • Tree/Binary Tree
  • Binary Search Tree
  • Binary Heap
  • Sorting Algorithms
  • Searching Algorithms
  • Single-Source Shortest Path
  • Topological Sort
  • Dijkstra’s
  • Bellman-Ford’s
  • All Pair Shortest Path
  • Minimum Spanning Tree
  • Kruskal & Prim’s

Problem-solving is the process of identifying a problem, creating an algorithm to solve the given problem, and finally implementing the algorithm to develop a computer program .

An algorithm is a process or set of rules to be followed while performing calculations or other problem-solving operations. It is simply a set of steps to accomplish a certain task.

In this article, we will discuss 5 major steps for efficient problem-solving. These steps are:

  • Understanding the Problem
  • Exploring Examples
  • Breaking the Problem Down
  • Solving or Simplification
  • Looking back and Refactoring

While understanding the problem, we first need to closely examine the language of the question and then proceed further. The following questions can be helpful while understanding the given problem at hand.

  • Can the problem be restated in our own words?
  • What are the inputs that are needed for the problem?
  • What are the outputs that come from the problem?
  • Can the outputs be determined from the inputs? In other words, do we have enough information to solve the given problem?
  • What should the important pieces of data be labeled?

Example : Write a function that takes two numbers and returns their sum.

  • Implement addition
  • Integer, Float, etc.

Once we have understood the given problem, we can look up various examples related to it. The examples should cover all situations that can be encountered while the implementation.

  • Start with simple examples.
  • Progress to more complex examples.
  • Explore examples with empty inputs.
  • Explore examples with invalid inputs.

Example : Write a function that takes a string as input and returns the count of each character

After exploring examples related to the problem, we need to break down the given problem. Before implementation, we write out the steps that need to be taken to solve the question.

Once we have laid out the steps to solve the problem, we try to find the solution to the question. If the solution cannot be found, try to simplify the problem instead.

The steps to simplify a problem are as follows:

  • Find the core difficulty
  • Temporarily ignore the difficulty
  • Write a simplified solution
  • Then incorporate that difficulty

Since we have completed the implementation of the problem, we now look back at the code and refactor it if required. It is an important step to refactor the code so as to improve efficiency.

The following questions can be helpful while looking back at the code and refactoring:

  • Can we check the result?
  • Can we derive the result differently?
  • Can we understand it at a glance?
  • Can we use the result or mehtod for some other problem?
  • Can you improve the performance of the solution?
  • How do other people solve the problem?

Trending Posts You Might Like

  • File Upload / Download with Streamlit
  • Dijkstra’s Algorithm in Python
  • Seaborn with STREAMLIT
  • Greedy Algorithms in Python

Author : Bhavya

Mastering Algorithms for Problem Solving in Python

Python Practice Questions for Coding Interviews

Aman Kharwal

  • July 15, 2022
  • Machine Learning

While learning a new programming language, it is valuable to solve practice questions. When you solve questions, it develops problem-solving skills. If you are learning Python and have completed the fundamentals of Python, your next step should be to solve some Python practice questions as a beginner. So, in this article, I will take you through some Python practice questions for coding interviews every beginner should try.

All the Python practice questions mentioned below are for someone who has completed the fundamentals of Python. Solving these questions is your next step in mastering the Python programming language. Some of these questions are also popular in the coding interviews of FAANG , so it will be helpful for you in your journey to become a Python developer.

  • Transpose Matrix
  • Buddy Strings
  • Uncommon words from two sentences
  • Binary Search
  • Set Mismatch
  • Reorder Routes
  • Detect Capital
  • Check Perfect Number
  • Relative Ranks
  • Repeated Substring Pattern
  • Counting Bits
  • Valid Perfect Square
  • First Unique Character
  • Assign Cookies
  • Hamming Distance
  • Max Consecutive Ones
  • Construct Rectangle
  • License Key Formatting
  • Number of Segments in a string
  • Third maximum number
  • FizzBuzz Problem
  • Reverse a String
  • Power of three
  • Move zeroes
  • Ugly Number
  • Power of two
  • Find Duplicate Values
  • Validate Palindromes
  • Pascal’s Triangle
  • Check Duplicate Values
  • Majority Element
  • Excel Sheet Column Title
  • Single Number
  • Best Time to Buy and Sell Stocks
  • Climbing Stairs
  • Find Missing Number
  • Two Sum Problem
  • Solving Plus One Problem
  • Remove Duplicates from a Sorted Array
  • Square Root using Python
  • Merge Two Sorted Lists
  • Finding the Longest Common Prefix
  • Group Elements of Same Indices
  • Group Anagrams
  • Calculate Execution Time
  • Find the most frequent word in a file
  • Find the number of capital letters in a file
  • Index of Maximum Value
  • Index of Minimum Value
  • Calculate Distance Between Two Locations

The above list of Python practice questions will keep updating with more questions.

So these are some Python practice questions you should try after learning the fundamentals of Python. Some of the questions in this list are popular in coding interviews. I will keep updating the list with more questions regularly. I hope you liked this article on Python practice questions for coding interviews every beginner should try. Feel free to ask valuable questions in the comments section below.

Aman Kharwal

Aman Kharwal

Data Strategist at Statso. My aim is to decode data science for the real world in the most simple words.

Recommended For You

How Much Python is Required to Learn Data Science

How Much Python is Required to Learn Data Science?

  • January 3, 2024

How to Choose Python Tableau or Power BI for Data Analysis

How to Choose Python Tableau or Power BI for Data Analysis

  • August 22, 2023

Detect and Remove Outliers using Python

Detect and Remove Outliers using Python

  • July 26, 2023

Python and R Libraries for Data Science

Python and R Libraries for Data Science

  • July 13, 2023

One comment

Thanks a lot ❤️🙏

Leave a Reply Cancel reply

Discover more from thecleverprogrammer.

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

Problem Solving with Python

If you like this book, please consider purchasing a hard copy version on amazon.com .

  • You will find the book chapters on the left hand menu
  • You will find navigation within a section of a chapter (one webpage) on the righthand menu
  • Sources for this text are stored on GitHub at github.com/professorkazarinoff/Problem-Solving-with-Python-37-Edition

If you find the text useful, please consider supporting the work by purchasing a hard copy of the text .

This work is licensed under a GNU General Public License v3.0

COMMENTS

  1. Python Exercises, Practice, Challenges

    Each exercise has 10-20 Questions. The solution is provided for every question. Practice each Exercise in Online Code Editor. These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

  2. Python Exercise with Practice Questions and Solutions

    Hence, we have designed this Python exercises after deep research so that one can easily enhance their skills and logic abilities. Python exercises, practice questions, and solutions. A detailed guide with 50 plus Python practice exercises for Python developer. Here you can find chapter-wise Python exercises with solutions for beginners as well ...

  3. Python Practice Problems: Get Ready for Your Next Interview

    Python Practice Problem 2: Caesar Cipher. The next question is a two-parter. You'll code up a function to compute a Caesar cipher on text input. ... Your final Python practice problem is to solve a sudoku puzzle! Finding a fast and memory-efficient solution to this problem can be quite a challenge. The solution you'll examine has been ...

  4. Python Practice for Beginners: 15 Hands-On Problems with Solutions

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

  5. Solve Python

    Easy Python (Basic) Max Score: 10 Success Rate: 89.73%. Solve Challenge. Arithmetic Operators. Easy Python (Basic) Max Score: 10 Success Rate: 97.42%. Solve Challenge. ... Problem Solving (Basic) Python (Basic) Problem Solving (Advanced) Python (Intermediate) Difficulty. Easy. Medium. Hard. Subdomains. Introduction. Basic Data Types. Strings ...

  6. 10 Python Practice Exercises for Beginners With Detailed Solutions

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

  7. Python Basic Exercise for Beginners with Solutions

    What questions are included in this Python fundamental exercise? The exercise contains 15 programs to solve. The hint and solution is provided for each question. I have added tips and required learning resources for each question, which will help you solve the exercise. When you complete each question, you get more familiar with the basics of ...

  8. Practice Python Programming Practice Problem Course Online

    It is the best source for hands-on practice. (5.0) Student. Get hands-on experience with Practice Python programming practice problem course on CodeChef. Solve a wide range of Practice Python coding challenges and boost your confidence in programming.

  9. 2,500+ Python Practice Challenges // Edabit

    Return the Sum of Two Numbers. Create a function that takes two numbers as arguments and returns their sum. Examples addition (3, 2) 5 addition (-3, -6) -9 addition (7, 3) 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab.

  10. 35 Python Programming Exercises and Solutions

    In this article, I'll list down some problems that I've done and the answer code for each exercise. Analyze each problem and try to solve it by yourself. If you have any doubts, you can check the code that I've provided below. I've also attached the corresponding outputs. 1. Python program to check whether the given number is even or not.

  11. Python Exercises, Practice, Solution

    Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. Python supports multiple programming paradigms, including object-oriented ...

  12. Python Exercises

    We have gathered a variety of Python exercises (with answers) for each Python Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  13. 100 Python Practice Questions

    1. Write a program to print "Hello, World!" on the screen. 2. Write a program to add two numbers and display the sum. 3. Write a program to find the largest of three numbers. 4. Write a ...

  14. Python for loop and if else Exercises [10 Exercise Programs]

    This Python loop exercise include the following: -. It contains 18 programs to solve using if-else statements and looping techniques.; Solutions are provided for all questions and tested on Python 3. This exercise is nothing but an assignment to solve, where you can solve and practice different loop programs and challenges.

  15. The 23 Top Python Interview Questions & Answers

    This question is a simple math problem. Find the sum of all elements in the list. ... cheat sheets, and mock questions, and solve coding challenges to pass the interview stage. You need to prepare for general Python questions on native functionality, job-specific questions (data engineer, data scientist, backend developer), and timed code-based ...

  16. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  17. Problem Solving in Python

    Step 4 - Solving or Simplification. Once we have laid out the steps to solve the problem, we try to find the solution to the question. If the solution cannot be found, try to simplify the problem instead. The steps to simplify a problem are as follows: Find the core difficulty.

  18. Mastering Algorithms for Problem Solving in Python

    Algorithms for Coding Interviews in Python. As a developer, mastering the concepts of algorithms and being proficient in implementing them is essential to improving problem-solving skills. This course aims to equip you with an in-depth understanding of algorithms and how they can be utilized for problem-solving in Python.

  19. Python Functions Exercise with Solution [10 Programs]

    Exercise 1: Create a function in Python. Exercise 2: Create a function with variable length of arguments. Exercise 3: Return multiple values from a function. Exercise 4: Create a function with a default argument. Exercise 5: Create an inner function to calculate the addition in the following way. Exercise 6: Create a recursive function.

  20. Python Practice Questions for Coding Interviews

    When you solve questions, it develops problem-solving skills. If you are learning Python and have completed the fundamentals of Python, your next step should be to solve some Python practice questions as a beginner. So, in this article, I will take you through some Python practice questions for coding interviews every beginner should try. ...

  21. Problem Solving with Python

    Website companion for the book Problem Solving with Python by Peter D. Kazarinoff ... Review Questions Chapter 11 Python and External Hardware Chapter 11 Python and External Hardware Introduction PySerial Bytes and Unicode Strings Controlling an LED with Python Reading a Sensor with Python ...

  22. python

    Stack Overflow Public questions & answers; ... I am currently attempting to implement an algorithm to solve the Travelling Salesman Problem by simulated annealing. Based on what I had read into the topic, this is what I had implemented: ... Simulated annealing algorithm to solve the traveling salesman problem in Python. Related questions. 4