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

Python if-else easy python (basic) max score: 10 success rate: 89.61%, arithmetic operators easy python (basic) max score: 10 success rate: 97.34%, python: division easy python (basic) max score: 10 success rate: 98.67%, loops easy python (basic) max score: 10 success rate: 98.07%, write a function medium python (basic) max score: 10 success rate: 90.28%, print function easy python (basic) max score: 20 success rate: 97.30%, list comprehensions easy python (basic) max score: 10 success rate: 97.64%, find the runner-up score easy python (basic) max score: 10 success rate: 94.21%, nested lists easy python (basic) max score: 10 success rate: 91.80%, cookie support is required to access hackerrank.

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

Learn Python right now with pychallenger

A structured and easy way to learn python programming online with interactive tutorials, python exercises, and code quizzes., online python exercises.

No need to download Python, code directly in your browser.

No login required

Start right away and sign up later

Python for all levels

Choose the topic and difficulty that you want to start with.

A hands-on Python experience

Pychallenger provides interactive online Python courses featuring coding tasks, practice problems, lessons, and quizzes.

Guided Python Learning Journey

Pychallenger offers a beginner-friendly and progressive learning journey, advancing in difficulty over time.

Build a learning streak

Pychallenger tracks your progress, ensuring motivation and seamless continuation of your learning journey.

Type and execute code yourself

Type real Python and see the output of your code. Pychallenger provides Python practice online directly in your browser.

Practice oriented Python learning , served in tiny bites.

Engaging lessons.

  • Code Examples
  • Mobile Friendly

Exercise: Call existing function

Python coding challenges.

  • Online Python Editor
  • Syntax Highlighting
  • Immediate Feedback

Interactive Coding Exams

  • Python Quiz
  • Multiple-Choice
  • Instant Feedback

Progressive Learning Path

  • Sequential Learning
  • Gradual Increase
  • Various Activities
  • Subscription

Python Practice: 93 Unique Online Coding Exercises

Whether you're just starting your learning journey or looking to brush up before a job interview, getting the right kind of Python practice can make a big difference.

Research shows that hands-on practice is the most effective way to learn, * and luckily there are so many different ways to practice that you're bound to find one that works best for you.

In this post, we'll share 93 ways to practice Python online by writing actual code, broken down into different practice methods.

Table of Contents

Core python programming (great for beginners), intermediate python programming, data handling and manipulation with numpy, data handling and manipulation with pandas, data analysis, complexity and algorithms, python introduction (great for beginners), data analysis and visualization, data cleaning.

  • Machine Learning

AI and Deep Learning

Probability and statistics, beginner projects, data analysis projects, data engineering projects, machine learning and ai projects, core python concepts (great for beginners), intermediate techniques, data analysis and data science, frequently asked questions, where can i practice python programming.

  • How can I practice Python programming?

Can I learn Python in 30 days?

Can i practice python on mobile, how quickly can i learn python, ai is advancing so quickly - should i still learn python, practice with free python coding exercises.

Exercises are a great way to practice a specific topic with targeted efficiency. For example, do you have an upcoming job interview where you know you'll be asked about Python dictionaries? Completing exercises about dictionaries will help refresh your skills and ensure you can confidently speak to this Pythonic datatype.

  • Basic Mathematical Operators (free) — Use Python to perform calculations and printing results to the screen.
  • Variables and data types (free) — Work with variables and doing calculations with variables.
  • Lists and loops (free) — Practice using Python lists and for loops.
  • Dictionaries 1 (free) — Use dictionaries in Python.
  • Dictionaries 2 (free) — More practice with dictionaries and frequency tables.
  • Lists (free) — Practice using lists in Python.
  • Conditional statements (if-else) — Use conditional statements in Python.
  • Sets — Practice using sets in Python.
  • Python functions — Define and call functions.
  • Intermediate Python functions — Practice more advanced usage of functions like returning multiple values.
  • Object oriented programming (OOP) — Define classes, methods, and attributes.
  • NumPy index selection (free) — Select values from ndarrays.
  • NumPy creating ndarrays — Create ndarrays with specific values and shapes.
  • NumPy ndarray methods — Use ndarray methods to perform calculations.
  • NumPy broadcasting — Work with ndarrays with different shapes and using broadcasting to create ndarrays.
  • NumPy boolean masks — Select data from ndarrays use boolean masks
  • NumPy datatypes — Work with NumPy datatypes
  • NumPy sorting — Practice sorting ndarrays
  • NumPy stacking and splitting — Stack and split ndarrays
  • Pandas series (free) — Use and build pandas series.
  • Creating and manipulating dataframes — Create and manipulate pandas dataframes.
  • Selecting data with Pandas — Select data from dataframes.
  • Loading and exploring data — Load data into dataframes and explore it.
  • Pandas boolean masks — Use boolean masks to select data from dataframes.
  • Pandas Data Cleaning — Clean data in a dataframe.
  • Cleaning and preparing data (free) — Write functions to remove incorrect characters and fill missing values.
  • Data analysis basics — Manipulate data from CSV files using Python dictionaries and functions.
  • Working with dates and times — Practice with the datetime module in Python.
  • Time complexity of algorithms (free) — Identify the type of time complexity of Python functions.
  • Constant time complexity — Find the constant time complexity of functions.
  • Logarithmic complexity — Practice finding the logarithmic time complexity of functions.
  • Sorting algorithms — Create and work with sorting algorithms in Python.
  • Space complexity — Practice space complexity by writing Python functions.

Explore our full library of Python practice problems to continue improving your skills.

Practice with Online Python Courses

If you're looking for more structure, then practicing with Python courses online may resonate with you. Courses guide you through a topic, so if you want to gain a new skill or you're rusty on an old one, completing a course is an excellent way to go.

Throughout these courses, you'll be given questions and assignments to test your skills. Additionally, some of these courses contain a guided project that allows you to apply everything you've learned.

See below for some recommended courses.

  • Introduction to Python — Write code using Python syntax; work with different types of data; and perform basic Python operations such as working with variables, processing numerical and text data, and manipulating lists.
  • Basic Operators and Data Structures in Python — Learn the fundamentals of Python for loops, dictionaries, and conditional logic (if-else).
  • Python Functions and Jupyter Notebook — Write Python functions, build functions that employ multiple return statements and return multiple variables, and install and use Jupyter Notebook.
  • Python for Data Science: Intermediate — Manipulate text, clean messy data, work with object-oriented programming concepts, and use dates and times in Python.
  • Pandas and NumPy Fundamentals — Use NumPy and pandas for data exploration, preparation, and analysis.
  • Data Visualization Fundamentals — Balance graph creation and statistics in your visualizations using tools such as Matplotlib and Seaborn.
  • Storytelling Data Visualization and Information Design — Use information design and data visualization to tell compelling stories.
  • Data Cleaning and Analysis — Manipulate, combine, transform, and merge data; manipulate strings; and work with missing values in Python.
  • Data Cleaning in Python: Advanced — Clean and manipulate text data using basic and advanced regular expressions, how to resolve missing data, and how to employ lambda functions and list comprehension with pandas.
  • Data Cleaning Project Walkthrough — Combine multiple datasets and prepare them for analysis.
  • Intro to Supervised Machine Learning — Build a supervised machine learning model in Python, and train and improve it for better performance and accuracy.
  • Intro to Unsupervised Machine Learning — Learn about unsupervised machine learning models in Python, when to apply them, and what differentiates them from supervised machine learning models.
  • Linear Regression Modeling — Build, evaluate, and interpret the results of a linear regression model, as well as using linear regression models for inference and prediction.
  • Gradient Descent Modeling — Learn the fundamentals of gradient descent and how to implement this algorithm in Python.
  • Logistic Regression Modeling — Build and evaluate logistic regression models, both from scratch and using scikit-learn.
  • Decision Tree and Random Forest Modeling — Learn the foundations of Decision Trees including identifying the key components of trees, interpreting them, classifying new observations using decision trees and calculating optimal thresholds for both classification and regression trees.
  • Optimizing Machine Learning Models — Explore the most common methods and techniques that will enable you to optimize your machine learning models for better efficiency.
  • APIs for AI Applications — Use Python for retrieving, analyzing, and manipulating real-world data from various sources including the World Development Indicators database.
  • Prompting Large Language Models (LLMs) — Create an AI-powered chatbot using Python, that incorporates key concepts like prompt engineering, managing conversation histories, and efficiently regulating token usage within an AI framework.
  • Intro to Deep Learning in Tensorflow — Learn the fundamentals of deep learning, as well as how to build, train, and evaluate models using the TensorFlow framework.
  • Introduction to Statistics in Python — Work with techniques for sampling data, concepts such as discrete variables and random variables, and the different types of charts and graphs you might use to visualize frequency distributions.
  • Intermediate Statistics in Python — Summarize distributions using mean, median, and mode. You’ll also learn to measure variability using variance or standard deviation and how to locate and compare values using z-scores.
  • Introduction to Probability in Python — Estimate probabilities, work with the addition and multiplication rules, and define permutations and combinations.
  • Introduction to Conditional Probability in Python — Assign probabilities to events based on certain conditions, evaluate whether they are in a relationship of statistical independence or not, and on prior knowledge by using Bayes’s theorem.
  • Hypothesis Testing in Python — Learn advanced statistical concepts like significance testing and multi-category chi-square testing,

These courses are a great way to practice Python online, and they're all free to start. If you're looking for more courses, you can find them on Dataquest's course page .

Practice with Python Projects

One of the most effective ways to practice Python online is with projects. When I was learning Python, it was easy to forget newly acquired skills. When I discovered that I could do projects to practice my newfound knowledge, it helped me remember new syntax. Additionally, I built a great portfolio of work to show potential employers.

Here are a few projects you can use to start practicing right now.

  • Profitable App Profiles for the App Store and Google Play Markets (free) — Assume the role of a data analyst at a company that builds apps for Android and iOS. Since the company’s revenue depends on in-app ads, your task is analyzing historical data from app markets to determine which apps attract the most users.
  • Learn and Install Jupyter Notebook (free) — Run Python code in a Jupyter Notebook and learn how to install Jupyter locally.
  • Build a Word Guessing Game (free) — Have some fun, and create a functional and interactive word-guessing game using Python.
  • Build a Garden Simulator Text Based Game (free) — Create an interactive text-based “Garden Simulator” using object-oriented programming, error handling, and randomness.
  • Build a Food Ordering App — Create a functional and interactive food ordering application using Python.
  • Investigating Fandango Movie Ratings (free) — Step into the role of a data journalist to analyze movie ratings data and determine if there’s evidence of bias in Fandango’s rating system.
  • Exploring Hacker News Posts (free) — Analyze a dataset from Hacker News and apply your Python skills in string handling, object-oriented programming, and data management to uncover trends in user submissions.
  • Exploring eBay Car Sales Data — Use Python to work with a scraped dataset of used cars from eBay Kleinanzeigen, a classifieds section of the German eBay website.
  • Finding Heavy Traffic Indicators on I-94 — Explore how using the pandas plotting functionality along with the Jupyter Notebook interface allows us to explore data quickly using visualizations.
  • Storytelling Data Visualization on Exchange Rates — Quickly create multiple subsetted plots using one or more conditions.
  • Clean and Analyze Employee Exit Surveys — Work with exit surveys from employees of the Department of Education in Queensland, Australia. Play the role of a data analyst and pretend the stakeholders want answers to important data questions.
  • Analyzing NYC High School Data — Discover the SAT performance of different demographics using scatter plots and maps.
  • Building Fast Queries on a CSV (free) — Act as a Python developer to build an inventory system for a laptop store. You’ll apply efficient data structures and algorithms to enable fast queries.
  • Analyzing Wikipedia Pages (free) — Process over 54 MB of Wikipedia articles to find specific text matches. Using Python and MapReduce, you’ll build a parallel solution to search the dataset and return match details efficiently.
  • Building a database for crime reports — Use PostgreSQL to build a database with proper schemas, tables, and user roles to store and manage crime report data efficiently.
  • Predicting Heart Disease (free) — Act as a data scientist at a healthcare solutions company to build a model that predicts a patient’s risk of developing heart disease based on their medical data.
  • Predicting Insurance Costs — Use linear regession modeling to predict insurance costs.
  • Developing a Dynamic AI Chatbot — Create an AI chatbot that can take on different personas and keep track of conversation history.

If these didn't spark your interest, here are plenty of other online Python projects you can try.

Practice with Online Python Tutorials

If online practice exercises, courses, and projects don't appeal to you, here are a few blog-style tutorials to help you learn Python. I like to use this type of resource when I'm on my phone to get some productive reading done, even when I can't code on my computer!

  • Python strings — See how to declare the string data type, the relationship between the string data type and the ASCII table, the properties of the string data type, and some important string methods and operations.
  • Python dictionaries — Learn how to create a Python dictionary, how to use its methods, and dictionary comprehension.
  • Python data structures — Read about what data structures exist in Python, when to apply them, and their pros and cons.
  • Python classes — Learn how to create and work with Python classes. See what Python classes are, why we use them, what types of classes exist, how to define a class in Python and declare/adjust class objects,
  • Python lists — Read how to define, create, and slice lists, as well as how to add/remove items and use a for loop to iterate over a list.
  • If statements — Use conditional logic with if, elif, and else to streamline your code's efficiency.
  • Python datetime — Learn the uses of the datetime module, extract dates, and work with timestamps.
  • Python ternary — Understand what a Python ternary operator is and when it's useful.
  • Python subprocess — See how to use the subprocess module in Python to run different subprocesses during the course of a regular python script.
  • Python math module — Read about the common constants and functions implemented in the math module — and how to use them.
  • Read files in Python — Learn how to open files, use the with context manager, read text, CSV, and JSON files, and understand different file modes.
  • Lambda functions — Define lambda functions in Python and explore the advantages and limitations of employing them.
  • Reset index in pandas — Discusses the reset_index() pandas method, why we may need to reset the index of a DataFrame in pandas, and how we can apply and tune this method.
  • GroupBy in pandas — Explore how to create a GroupBy object in pandas library of Python and how this object works.
  • Getting Started with APIs — Understand how to retrieve data for AI and data science projects using APIs (Application Programming Interfaces).
  • Introduction to Keras — Learn how to install and start using Keras; the Sequential API; and the steps for building, compiling, and training a model..
  • Implement Support Vector Machines (SVMs) — Read about support vector machines, one of the most popular classification algorithms. Learn how to implement SVMs for a classification task in Python.

The web is also full of thousands of other beginner Python tutorials. As long as you've got a solid foundation in the Python basics, you can find great practice through many of them.

Dataquest.io has dozens of free interactive practice questions, as well as free interactive lessons, project ideas and walkthroughs, tutorials, and more.

HackerRank is a great site for practice that’s also interactive.

CodingGame is a fun platform for practice that supports Python.

Edabit has Python challenges that can be good for practicing or self-testing.

You can also practice Python using all of the interactive lessons listed above

How can I practice Python at home?

Install Python on your machine. You can download it directly here , or download a program like Anaconda Individual Edition that makes the process easier. Or you can find an interactive online platform like Dataquest and write code in your browser without installing anything.

Find a good Python project or some practice problems to work on.

Make detailed plans. Scheduling your practice sessions will make you more likely to follow through.

Join an online community. It's always great to get help from a real person. Reddit has great Python communities, and Dataquest's community is great if you're learning Python data skills.

In 30 days, you can definitely learn enough Python to be able to build some cool things. You won't be able to master Python that quickly, but you could learn to complete a specific project or do things like automate some aspects of your job.

Read more about how long it takes to learn Python .

Yes, there are many apps that allow you to practice Python on both iOS and Android. However, this shouldn't be your primary form of practice if you aspire to use Python in your career— it's good to practice installing and working with Python on desktops and laptops since that's how most professional programming work is done.

You can learn the fundamentals of Python in a weekend. If you're diligent, you can learn enough to complete small projects and genuinely impact your work within a month or so. Mastering Python takes much longer, but you don't need to become a master to get things done!

Absolutely, Python remains essential in the AI field. It's foundational for developing AI technologies and continuously updated to integrate with the latest AI advancements. Python libraries like TensorFlow and Keras facilitate efficient building and training of complex AI models. Learning Python also ensures you understand the underlying mechanisms of AI tools, making you a more proficient developer.

More learning resources

Python exceptions: the ultimate beginner’s guide (with examples), beginner python tutorial: analyze your personal netflix data.

Learn data skills 10x faster

Headshot

Join 1M+ learners

Enroll for free

  • Data Analyst (Python)
  • Gen AI (Python)
  • Business Analyst (Power BI)
  • Business Analyst (Tableau)
  • Data Analyst (R)

Python Programming Challenges

Practice your Python skills with these programming challenges. The tasks are meant to be challenging for beginners. If you find them too difficult, try completing our lessons for beginners first.

All challenges have hints and curated example solutions. They also work on your phone, so you can practice Python on the go.

Click a challenge to start.

Challenge Difficulty Status
2 / 10 2 / 10 2 / 10 2 / 10 2 / 10 3 / 10 3 / 10 3 / 10 3 / 10 3 / 10 3 / 10 3 / 10 4 / 10 4 / 10 4 / 10 4 / 10 4 / 10 4 / 10 5 / 10 5 / 10 5 / 10 5 / 10 5 / 10 7 / 10unsolved

python problem solving websites

Practice Python

follow us in feedly

Beginner Python exercises

  • Why Practice Python?
  • Why Chilis?
  • Resources for learners

All Exercises

python problem solving websites

All Solutions

  • 1: Character Input Solutions
  • 2: Odd Or Even Solutions
  • 3: List Less Than Ten Solutions
  • 4: Divisors Solutions
  • 5: List Overlap Solutions
  • 6: String Lists Solutions
  • 7: List Comprehensions Solutions
  • 8: Rock Paper Scissors Solutions
  • 9: Guessing Game One Solutions
  • 10: List Overlap Comprehensions Solutions
  • 11: Check Primality Functions Solutions
  • 12: List Ends Solutions
  • 13: Fibonacci Solutions
  • 14: List Remove Duplicates Solutions
  • 15: Reverse Word Order Solutions
  • 16: Password Generator Solutions
  • 17: Decode A Web Page Solutions
  • 18: Cows And Bulls Solutions
  • 19: Decode A Web Page Two Solutions
  • 20: Element Search Solutions
  • 21: Write To A File Solutions
  • 22: Read From File Solutions
  • 23: File Overlap Solutions
  • 24: Draw A Game Board Solutions
  • 25: Guessing Game Two Solutions
  • 26: Check Tic Tac Toe Solutions
  • 27: Tic Tac Toe Draw Solutions
  • 28: Max Of Three Solutions
  • 29: Tic Tac Toe Game Solutions
  • 30: Pick Word Solutions
  • 31: Guess Letters Solutions
  • 32: Hangman Solutions
  • 33: Birthday Dictionaries Solutions
  • 34: Birthday Json Solutions
  • 35: Birthday Months Solutions
  • 36: Birthday Plots Solutions
  • 37: Functions Refactor Solution
  • 38: f Strings Solution
  • 39: Character Input Datetime Solution
  • 40: Error Checking Solution

Top online courses in Programming Languages

The 10 Most Popular Coding Challenge Websites [Updated for 2021]

freeCodeCamp

By Daniel Borowski

A great way to improve your skills when learning to code is by solving coding challenges. Solving different types of challenges and puzzles can help you become a better problem solver, learn the intricacies of a programming language, prepare for job interviews, learn new algorithms, and more.

Below is a list of some popular coding challenge websites with a short description of what each one offers.

1. TopCoder

Image

TopCoder is one of the original platforms for competitive programming online. It provides a list of algorithmic challenges from the past that you can complete on your own directly online using their code editor. Their popular Single Round Matches are offered a few times per month at a specific time where you compete against others to solve challenges the fastest with the best score.

The top ranked users on TopCoder are very good competitive programmers and regularly compete in programming competitions. The top ranked user maintains his own blog titled Algorithms weekly by Petr Mitrichev where he writes about coding competitions, algorithms, math, and more.

2. Coderbyte

Image

Coderbyte provides 200+ coding challenges you can solve directly online in one of 10 programming languages (check out this example ). The challenges range from easy (finding the largest word in a string) to hard (print the maximum cardinality matching of a graph).

They also provide a collection of algorithm tutorials , introductory videos, and interview preparation courses . Unlike HackerRank and other similar websites, you are able to view the solutions other users provide for any challenge aside from the official solutions posted by Coderbyte.

3. Project Euler

Image

Project Euler provides a large collection of challenges in the domain of computer science and mathematics. The challenges typically involve writing a small program to figure out the solution to a clever mathematical formula or equation, such as finding the sum of digits of all numbers preceding each number in a series.

You cannot directly code on the website in an editor, so you would need to write a solution on your own computer and then provide the solution on their website.

4. HackerRank

Image

HackerRank provides challenges for several different domains such as Algorithms, Mathematics, SQL, Functional Programming, AI, and more. You can solve all the challenge directly online (check out this example ).

They provide a discussion and leaderboard for every challenge, and most challenges come with an editorial that explains more about the challenge and how to approach it to come up with a solution.

Currently, if you don't solve the problem, then you can't see the solution of others. If you also try to check the editorial before solving the problem, then you won't get the point for solving the problem at all.

As an example, here I haven't solved the problem, and I am trying to check others' submissions:

Image

And here, I haven't solved the problem, and I am trying to check the editorial:

Image

HackerRank also provides the ability for users to submit applications and apply to jobs by solving company-sponsored coding challenges.

5. CodeChef

Image

CodeChef is an Indian-based competitive programming website that provides hundreds of challenges. You are able to write code in their online editor and view a collections of challenges that are separated into different categories depending on your skill level (check out this example ). They have a large community of coders that contribute to the forums, write tutorials , and take part in CodeChef’s coding competitions .

6. Exercism.io

Image

Exercism is a coding challenge website that offers 3100+ challenges spanning 52 different programming languages. After picking a language that you'd like to master, you tackle the coding challenges right on your machine (Exercism has their own command line interface that you can download from GitHub).

It is a bit different from other challenge websites, however, because you work with a mentor after completing each challenge. The mentor reviews your answers online and helps you improve them if needed. Once your answers have been approved and submitted, you unlock more challenges.

7. Codewars

Image

Codewars provides a large collection of coding challenges submitted and edited by their own community. You can solve the challenges directly online in their editor in one of several languages. You can view a discussion for each challenges as well as user solutions.

8. LeetCode

Image

LeetCode is a popular Online Judge that provides a list of 190+ challenges that can help you prepare for technical job interviews. You can solve the challenges directly online in one of 9 programming languages. You are not able to view other users' solutions, but you are provided statistics for your own solutions such as how fast your code ran when compared to other users' code.

They also have a Mock Interview section that is specifically for job interview preparation, they host their own coding contests , and they have a section for articles to help you better understand certain problems.

Image

Sphere Online Judge (SPOJ) is an online judge that provides over 20k coding challenges. You are able to submit your code in an online editor . SPOJ also hosts their own contests and has an area for users to discuss coding challenges. They do not currently provide any official solutions or editorials like some other websites do, though.

10. CodinGame

Image

CodinGame is a bit different from the other websites, because instead of simply solving coding challenges in an editor, you actually take part in writing the code for games that you play directly online. You can see a list of games currently offered here and an example of one here . The game comes with a problem description, test cases, and an editor where you can write your code in one of 20+ programming languages.

Although this website is different than typical competitive programming websites such as the ones mentioned above, it is still popular amongst programmers who enjoy solving challenges and taking part in contests.

This list was based on a few things: my own experiences using the websites, some Google searches , Quora posts , and articles such as this one and this one . I also frequented some forums and subreddits such as r/learnprogramming to see what websites were usually recommended by the users there. Disclaimer: I work at Coderbyte which is one of the websites mentioned above.

Learn to code. Build projects. Earn certifications—All for free.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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

python problem solving websites

How Do You Write a SELECT Statement in SQL?

python problem solving websites

What Is a Foreign Key in SQL?

python problem solving websites

Enumerate and Explain All the Basic Elements of an SQL Query

Python Practice Problems: Prepare for Your Next Interview

Python Practice Problems: Get Ready for Your Next Interview

Table of Contents

Problem Description

Problem solution.

Are you a Python developer brushing up on your skills before an interview ? If so, then this tutorial will usher you through a series of Python practice problems meant to simulate common coding test scenarios. After you develop your own solutions, you’ll walk through the Real Python team’s answers so you can optimize your code, impress your interviewer, and land your dream job!

In this tutorial, you’ll learn how to:

  • Write code for interview-style problems
  • Discuss your solutions during the interview
  • Work through frequently overlooked details
  • Talk about design decisions and trade-offs

This tutorial is aimed at intermediate Python developers. It assumes a basic knowledge of Python and an ability to solve problems in Python. You can get skeleton code with failing unit tests for each of the problems you’ll see in this tutorial by clicking on the link below:

Download the sample code: Click here to get the code you’ll use to work through the Python practice problems in this tutorial.

Each of the problems below shows the file header from this skeleton code describing the problem requirements. So download the code, fire up your favorite editor, and let’s dive into some Python practice problems!

Python Practice Problem 1: Sum of a Range of Integers

Let’s start with a warm-up question. In the first practice problem, you’ll write code to sum a list of integers . Each practice problem includes a problem description. This description is pulled directly from the skeleton files in the repo to make it easier to remember while you’re working on your solution.

You’ll see a solution section for each problem as well. Most of the discussion will be in a collapsed section below that. Clone that repo if you haven’t already, work out a solution to the following problem, then expand the solution box to review your work.

Here’s your first problem:

Sum of Integers Up To n ( integersums.py ) Write a function, add_it_up() , that takes a single integer as input and returns the sum of the integers from zero to the input parameter. The function should return 0 if a non-integer is passed in.

Remember to run the unit tests until you get them passing!

Here’s some discussion of a couple of possible solutions.

Note: Remember, don’t open the collapsed section below until you’re ready to look at the answer for this Python practice problem!

Solution for Sum of a Range of Integers Show/Hide

How did writing the solution go? Ready to look at the answer?

For this problem, you’ll look at a few different solutions. The first of these is not so good:

In this solution, you manually build a while loop to run through the numbers 1 through n . You keep a running sum and then return it when you’ve finished the loop.

This solution works, but it has two problems:

It doesn’t display your knowledge of Python and how the language simplifies tasks like this.

It doesn’t meet the error conditions in the problem description. Passing in a string will result in the function throwing an exception when it should just return 0 .

You’ll deal with the error conditions in the final answer below, but first let’s refine the core solution to be a bit more Pythonic .

The first thing to think about is that while loop . Python has powerful mechanisms for iterating over lists and ranges. Creating your own is usually unnecessary, and that’s certainly the case here. You can replace the while loop with a loop that iterates over a range() :

You can see that the for...range() construct has replaced your while loop and shortened the code. One thing to note is that range() goes up to but does not include the number given, so you need to use n + 1 here.

This was a nice step! It removes some of the boilerplate code of looping over a range and makes your intention clearer. But there’s still more you can do here.

Summing a list of integers is another thing Python is good at:

Wow! By using the built-in sum() , you got this down to one line of code! While code golf generally doesn’t produce the most readable code, in this case you have a win-win: shorter and more readable code.

There’s one problem remaining, however. This code still doesn’t handle the error conditions correctly. To fix that, you can wrap your previous code in a try...except block:

This solves the problem and handles the error conditions correctly. Way to go!

Occasionally, interviewers will ask this question with a fixed limit, something like “Print the sum of the first nine integers.” When the problem is phrased that way, one correct solution would be print(45) .

If you give this answer, however, then you should follow up with code that solves the problem step by step. The trick answer is a good place to start your answer, but it’s not a great place to end.

If you’d like to extend this problem, try adding an optional lower limit to add_it_up() to give it more flexibility!

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. For this problem, you’re free to use any part of the Python standard library to do the transform.

Hint: There’s a function in the str class that will make this task much easier!

The problem statement is at the top of the skeleton source file:

Caesar Cipher ( caesar.py ) A Caesar cipher is a simple substitution cipher in which each letter of the plain text is substituted with a letter found by moving n places down the alphabet. For example, assume the input plain text is the following: abcd xyz If the shift value, n , is 4, then the encrypted text would be the following: efgh bcd You are to write a function that accepts two arguments, a plain-text message and a number of letters to shift in the cipher. The function will return an encrypted string with all letters transformed and all punctuation and whitespace remaining unchanged. Note: You can assume the plain text is all lowercase ASCII except for whitespace and punctuation.

Remember, this part of the question is really about how well you can get around in the standard library. If you find yourself figuring out how to do the transform without the library, then save that thought! You’ll need it later!

Here’s a solution to the Caesar cipher problem described above.

Note: Remember, don’t open the collapsed section below until you’re ready to look at the answers for this Python practice problem!

Solution for Caesar Cipher Show/Hide

This solution makes use of .translate() from the str class in the standard library. If you struggled with this problem, then you might want to pause a moment and consider how you could use .translate() in your solution.

Okay, now that you’re ready, let’s look at this solution:

You can see that the function makes use of three things from the string module:

  • .ascii_lowercase
  • .maketrans()
  • .translate()

In the first two lines, you create a variable with all the lowercase letters of the alphabet (ASCII only for this program) and then create a mask , which is the same set of letters, only shifted. The slicing syntax is not always obvious, so let’s walk through it with a real-world example:

You can see that x[3:] is all the letters after the third letter, 'c' , while x[:3] is just the first three letters.

Line 6 in the solution, letters[shift_num:] + letters[:shift_num] , creates a list of letters shifted by shift_num letters, with the letters at the end wrapped around to the front. Once you have the list of letters and the mask of letters you want to map to, you call .maketrans() to create a translation table.

Next, you pass the translation table to the string method .translate() . It maps all characters in letters to the corresponding letters in mask and leaves all other characters alone.

This question is an exercise in knowing and using the standard library. You may be asked a question like this at some point during an interview. If that happens to you, it’s good to spend some time thinking about possible answers. If you can remember the method— .translate() in this case—then you’re all set.

But there are a couple of other scenarios to consider:

You may completely draw a blank. In this case, you’ll probably solve this problem the way you solve the next one , and that’s an acceptable answer.

You may remember that the standard library has a function to do what you want but not remember the details.

If you were doing normal work and hit either of these situations, then you’d just do some searching and be on your way. But in an interview situation, it will help your cause to talk through the problem out loud.

Asking the interviewer for specific help is far better than just ignoring it. Try something like “I think there’s a function that maps one set of characters to another. Can you help me remember what it’s called?”

In an interview situation, it’s often better to admit that you don’t know something than to try to bluff your way through.

Now that you’ve seen a solution using the Python standard library, let’s try the same problem again, but without that help!

Python Practice Problem 3: Caesar Cipher Redux

For the third practice problem, you’ll solve the Caesar cipher again, but this time you’ll do it without using .translate() .

The description of this problem is the same as the previous problem. Before you dive into the solution, you might be wondering why you’re repeating the same exercise, just without the help of .translate() .

That’s a great question. In normal life, when your goal is to get a working, maintainable program, rewriting parts of the standard library is a poor choice. The Python standard library is packed with working, well-tested, and fast solutions for problems large and small. Taking full advantage of it is a mark of a good programmer.

That said, this is not a work project or a program you’re building to satisfy a need. This is a learning exercise, and it’s the type of question that might be asked during an interview. The goal for both is to see how you can solve the problem and what interesting design trade-offs you make while doing it.

So, in the spirit of learning, let’s try to resolve the Caesar cipher without .translate() .

For this problem, you’ll have two different solutions to look at when you’re ready to expand the section below.

Solutions for Caesar Cipher Redux Show/Hide

For this problem, two different solutions are provided. Check out both and see which one you prefer!

For the first solution, you follow the problem description closely, adding an amount to each character and flipping it back to the beginning of the alphabet when it goes on beyond z :

Starting on line 14, you can see that caesar() does a list comprehension , calling a helper function for each letter in message . It then does a .join() to create the new encoded string. This is short and sweet, and you’ll see a similar structure in the second solution. The interesting part happens in shift_n() .

Here you can see another use for string.ascii_lowercase , this time filtering out any letter that isn’t in that group. Once you’re certain you’ve filtered out any non-letters, you can proceed to encoding. In this version of encoding, you use two functions from the Python standard library:

Again, you’re encouraged not only to learn these functions but also to consider how you might respond in an interview situation if you couldn’t remember their names.

ord() does the work of converting a letter to a number, and chr() converts it back to a letter. This is handy as it allows you to do arithmetic on letters, which is what you want for this problem.

The first step of your encoding on line 7 gets the numeric value of the encoded letter by using ord() to get the numeric value of the original letter. ord() returns the Unicode code point of the character, which turns out to be the ASCII value.

For many letters with small shift values, you can convert the letter back to a character and you’ll be done. But consider the starting letter, z .

A shift of one character should result in the letter a . To achieve this wraparound, you find the difference from the encoded letter to the letter z . If that difference is positive, then you need to wrap back to the beginning.

You do this in lines 8 to 11 by repeatedly adding 26 to or subtracting it from the character until it’s in the range of ASCII characters. Note that this is a fairly inefficient method for fixing this issue. You’ll see a better solution in the next answer.

Finally, on line 12, your conversion shift function takes the numeric value of the new letter and converts it back to a letter to return it.

While this solution takes a literal approach to solving the Caesar cipher problem, you could also use a different approach modeled after the .translate() solution in practice problem 2 .

The second solution to this problem mimics the behavior of Python’s built-in method .translate() . Instead of shifting each letter by a given amount, it creates a translation map and uses it to encode each letter:

Starting with caesar() on line 11, you start by fixing the problem of amount being greater than 26 . In the previous solution, you looped repeatedly until the result was in the proper range. Here, you take a more direct and more efficient approach using the mod operator ( % ).

The mod operator produces the remainder from an integer division. In this case, you divide by 26 , which means the results are guaranteed to be between 0 and 25 , inclusive.

Next, you create the translation table. This is a change from the previous solutions and is worth some attention. You’ll see more about this toward the end of this section.

Once you create the table , the rest of caesar() is identical to the previous solution: a list comprehension to encrypt each letter and a .join() to create a string.

shift_n() finds the index of the given letter in the alphabet and then uses this to pull a letter from the table . The try...except block catches those cases that aren’t found in the list of lowercase letters.

Now let’s discuss the table creation issue. For this toy example, it probably doesn’t matter too much, but it illustrates a situation that occurs frequently in everyday development: balancing clarity of code against known performance bottlenecks.

If you examine the code again, you’ll see that table is used only inside shift_n() . This indicates that, in normal circumstances, it should have been created in, and thus have its scope limited to, shift_n() :

The issue with that approach is that it spends time calculating the same table for every letter of the message. For small messages, this time will be negligible, but it might add up for larger messages.

Another possible way that you could avoid this performance penalty would be to make table a global variable . While this also cuts down on the construction penalty, it makes the scope of table even larger. This doesn’t seem better than the approach shown above.

At the end of the day, the choice between creating table once up front and giving it a larger scope or just creating it for every letter is what’s called a design decision . You need to choose the design based on what you know about the actual problem you’re trying to solve.

If this is a small project and you know it will be used to encode large messages, then creating the table only once could be the right decision. If this is only a portion of a larger project, meaning maintainability is key, then perhaps creating the table each time is the better option.

Since you’ve looked at two solutions, it’s worth taking a moment to discuss their similarities and differences.

Solution Comparison

You’ve seen two solutions in this part of the Caesar cipher, and they’re fairly similar in many ways. They’re about the same number of lines. The two main routines are identical except for limiting amount and creating table . It’s only when you look at the two versions of the helper function, shift_n() , that the differences appear.

The first shift_n() is an almost literal translation of what the problem is asking for: “Shift the letter down the alphabet and wrap it around at z .” This clearly maps back to the problem statement, but it has a few drawbacks.

Although it’s about the same length as the second version, the first version of shift_n() is more complex. This complexity comes from the letter conversion and math needed to do the translation. The details involved—converting to numbers, subtracting, and wrapping—mask the operation you’re performing. The second shift_n() is far less involved in its details.

The first version of the function is also specific to solving this particular problem. The second version of shift_n() , like the standard library’s .translate() that it’s modeled after, is more general-purpose and can be used to solve a larger set of problems. Note that this is not necessarily a good design goal.

One of the mantras that came out of the Extreme Programming movement is “You aren’t gonna need it” (YAGNI). Frequently, software developers will look at a function like shift_n() and decide that it would be better and more general-purpose if they made it even more flexible, perhaps by passing in a parameter instead of using string.ascii_lowercase .

While that would indeed make the function more general-purpose, it would also make it more complex. The YAGNI mantra is there to remind you not to add complexity before you have a specific use case for it.

To wrap up your Caesar cipher section, there are clear trade-offs between the two solutions, but the second shift_n() seems like a slightly better and more Pythonic function.

Now that you’ve written the Caesar cipher three different ways, let’s move on to a new problem.

Python Practice Problem 4: Log Parser

The log parser problem is one that occurs frequently in software development. Many systems produce log files during normal operation, and sometimes you’ll need to parse these files to find anomalies or general information about the running system.

For this problem, you’ll need to parse a log file with a specified format and generate a report:

Log Parser ( logparse.py ) Accepts a filename on the command line. The file is a Linux-like log file from a system you are debugging. Mixed in among the various statements are messages indicating the state of the device. They look like this: Jul 11 16:11:51:490 [139681125603136] dut: Device State: ON The device state message has many possible values, but this program cares about only three: ON , OFF , and ERR . Your program will parse the given log file and print out a report giving how long the device was ON and the timestamp of any ERR conditions.

Note that the provided skeleton code doesn’t include unit tests. This was omitted since the exact format of the report is up to you. Think about and write your own during the process.

A test.log file is included, which provides you with an example. The solution you’ll examine produces the following output:

While that format is generated by the Real Python solution, you’re free to design your own format for the output. The sample input file should generate equivalent information.

In the collapsed section below, you’ll find a possible solution to the log parser problem. When you’re ready, expand the box and compare it with what you came up with!

Solution for Log Parser Problem Show/Hide

Full Solution

Since this solution is longer than what you saw for the integer sums or the Caesar cipher problems, let’s start with the full program:

That’s your full solution. You can see that the program consists of three functions and the main section. You’ll work through them from the top.

Helper Function: get_next_event()

First up is get_next_event() :

Because it contains a yield statement, this function is a generator . That means you can use it to generate one event from the log file at a time.

You could have just used for line in datafile , but instead you add a little bit of filtering. The calling routine will get only those events that have dut: Device State: in them. This keeps all the file-specific parsing contained in a single function.

This might make get_next_event() a bit more complicated, but it’s a relatively small function, so it remains short enough to read and comprehend. It also keeps that complicated code encapsulated in a single location.

You might be wondering when datafile gets closed. As long as you call the generator until all of the lines are read from datafile , the for loop will complete, allowing you to leave the with block and exit from the function.

Helper Function: compute_time_diff_seconds()

The second function is compute_time_diff_seconds() , which, as the name suggests, computes the number of seconds between two timestamps:

There are a few interesting points to this function. The first is that subtracting the two datetime objects results in a datetime.timedelta . For this problem, you will report total seconds, so returning .total_seconds() from the timedelta is appropriate.

The second item of note is that there are many, many packages in Python that simplify handling dates and times. In this case, your use model is simple enough that it doesn’t warrant the complexity of pulling in an external library when the standard library functions will suffice.

That said, datetime.datetime.strptime() is worthy of mention. When passed a string and a specific format, .strptime() parses that string with the given format and produces a datetime object.

This is another place where, in an interview situation, it’s important not to panic if you can’t remember the exact names of the Python standard library functions.

Helper Function: extract_data()

Next up is extract_data() , which does the bulk of the work in this program. Before you dive into the code, let’s step back and talk about state machines.

State machines are software (or hardware) devices that transition from one state to another depending on specific inputs. That’s a really broad definition that might be difficult to grasp, so let’s look at a diagram of the state machine you’ll be using below:

State machine with two states: ON and OFF with transitions between the states.

In this diagram, the states are represented by the labeled boxes. There are only two states here, ON and OFF , which correspond to the state of the device. There are also two input signals, Device State: ON and Device State: OFF . The diagram uses arrows to show what happens when an input occurs while the machine is in each state.

For example, if the machine is in the ON state and the Device State: ON input occurs, then the machine stays in the ON state. No change happens. Conversely, if the machine receives the Device State: OFF input when it’s in the ON state, then it will transition to the OFF state.

While the state machine here is only two states with two inputs, state machines are often much more complex. Creating a diagram of expected behavior can help you make the code that implements the state machine more concise.

Let’s move back to extract_data() :

It might be hard to see the state machine here. Usually, state machines require a variable to hold the state. In this case, you use time_on_started to serve two purposes:

  • Indicate state: time_on_started holds the state of your state machine. If it’s None , then the machine is in the OFF state. If it’s not None , then the machine is ON .
  • Store start time: If the state is ON , then time_on_started also holds the timestamp of when the device turned on. You use this timestamp to call compute_time_diff_seconds() .

The top of extract_data() sets up your state variable, time_on_started , and also the two outputs you want. errs is a list of timestamps at which the ERR message was found, and total_time_on is the sum of all periods when the device was on.

Once you’ve completed the initial setup, you call the get_next_event() generator to retrieve each event and timestamp. The action it receives is used to drive the state machine, but before it checks for state changes, it first uses an if block to filter out any ERR conditions and add those to errs .

After the error check, the first elif block handles transitions to the ON state. You can transition to ON only when you’re in the OFF state, which is signaled by time_on_started being False . If you’re not already in the ON state and the action is "ON" , then you store the timestamp , putting the machine into the ON state.

The second elif handles the transition to the OFF state. On this transition, extract_data() needs to compute the number of seconds the device was on. It does this using the compute_time_diff_seconds() you saw above. It adds this time to the running total_time_on and sets time_on_started back to None , effectively putting the machine back into the OFF state.

Main Function

Finally, you can move on to the __main__ section. This final section passes sys.argv[1] , which is the first command-line argument , to extract_data() and then presents a report of the results:

To call this solution, you run the script and pass the name of the log file. Running your example code results in this output:

Your solution might have different formatting, but the information should be the same for the sample log file.

There are many ways to solve a problem like this. Remember that in an interview situation, talking through the problem and your thought process can be more important than which solution you choose to implement.

That’s it for the log-parsing solution. Let’s move on to the final challenge: sudoku!

Python Practice Problem 5: Sudoku Solver

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 selected for readability rather than speed, but you’re free to optimize your solution as much as you want.

The description for the sudoku solver is a little more involved than the previous problems:

Sudoku Solver ( sudokusolve.py ) Given a string in SDM format, described below, write a program to find and return the solution for the sudoku puzzle in the string. The solution should be returned in the same SDM format as the input. Some puzzles will not be solvable. In that case, return the string “Unsolvable”. The general SDM format is described here . For our purposes, each SDM string will be a sequence of 81 digits, one for each position on the sudoku puzzle. Known numbers will be given, and unknown positions will have a zero value. For example, assume you’re given this string of digits: 004006079000000602056092300078061030509000406020540890007410920105000000840600100 The string represents this starting sudoku puzzle: 0 0 4 0 0 6 0 7 9 0 0 0 0 0 0 6 0 2 0 5 6 0 9 2 3 0 0 0 7 8 0 6 1 0 3 0 5 0 9 0 0 0 4 0 6 0 2 0 5 4 0 8 9 0 0 0 7 4 1 0 9 2 0 1 0 5 0 0 0 0 0 0 8 4 0 6 0 0 1 0 0 The provided unit tests may take a while to run, so be patient. Note: A description of the sudoku puzzle can be found on Wikipedia .

You can see that you’ll need to deal with reading and writing to a particular format as well as generating a solution.

When you’re ready, you can find a detailed explanation of a solution to the sudoku problem in the box below. A skeleton file with unit tests is provided in the repo.

Solution for Sudoku Solver Show/Hide

This is a larger and more complex problem than you’ve looked at so far in this tutorial. You’ll walk through the problem step by step, ending with a recursive function that solves the puzzle. Here’s a rough outline of the steps you’ll take:

  • Read the puzzle into a grid form.
  • Place the number in the cell.
  • Remove that number from the row, column, and small square.
  • Move to the next position.
  • If no possible numbers remain, then declare the puzzle unsolvable .
  • If all cells are filled, then return the solution .

The tricky part of this algorithm is keeping track of the grid at each step of the process. You’ll use recursion, making a new copy of the grid at each level of the recursion, to maintain this information.

With that outline in mind, let’s start with the first step, creating the grid.

Generating a Grid From a Line

To start, it’s helpful to convert the puzzle data into a more usable format. Even if you eventually want to solve the puzzle in the given SDM format , you’ll likely make faster progress working through the details of your algorithm with the data in a grid form. Once you have a solution that works, then you can convert it to work on a different data structure.

To this end, let’s start with a couple of conversion functions:

Your first function, line_to_grid() , converts the data from a single string of eighty-one digits to a list of lists. For example, it converts the string line to a grid like start :

Each inner list here represents a horizontal row in your sudoku puzzle.

You start with an empty grid and an empty line . You then build each line by converting nine characters from the values string to single-digit integers and then appending them to the current line . Once you have nine values in a line , as indicated by index % 9 == 0 on line 7, you insert that line into the grid and start a new one.

The function ends by appending the final line to the grid . You need this because the for loop will end with the last line still stored in the local variable and not yet appended to grid .

The inverse function, grid_to_line() , is slightly shorter. It uses a generator expression with .join() to create a nine-digit string for each row. It then appends that string to the overall line and returns it. Note that it’s possible to use nested generators to create this result in fewer lines of code, but the readability of the solution starts to fall off dramatically.

Now that you’ve got the data in the data structure you want, let’s start working with it.

Generating a Small Square Iterator

Your next function is a generator that will help you search for the smaller three-by-three square a given position is in. Given the x- and y-coordinates of the cell in question, this generator will produce a list of coordinates that match the square that contains it:

A Sudoku grid with one of the small squares highlighted.

In the image above, you’re examining cell (3, 1) , so your generator will produce coordinate pairs corresponding to all the lightly shaded cells, skipping the coordinates that were passed in:

Putting the logic for determining this small square in a separate utility function keeps the flow of your other functions more readable. Making this a generator allows you to use it in a for loop to iterate through each of the values.

The function to do this involves using the limitations of integer math:

There are a lot of threes in a couple of those lines, which makes lines like ((x + 3) // 3) * 3 look confusing. Here’s what happens when x is 1 .

Using the rounding of integer math allows you to get the next-highest multiple of three above a given value. Once you have this, subtracting three will give you the multiple of three below the given number.

There are a few more low-level utility functions to examine before you start building on top of them.

Moving to the Next Spot

Your solution will need to walk through the grid structure one cell at a time. This means that at some point, you’ll need to figure out what the next position should be. compute_next_position() to the rescue!

compute_next_position() takes the current x- and y-coordinates as input and returns a tuple containing a finished flag along with the x- and y-coordinates of the next position:

The finished flag tells the caller that the algorithm has walked off the end of the puzzle and has completed all the squares. You’ll see how that’s used in a later section.

Removing Impossible Numbers

Your final low-level utility is quite small. It takes an integer value and an iterable. If the value is nonzero and appears in the iterable, then the function removes it from the iterable:

Typically, you wouldn’t make this small bit of functionality into a function. You’ll use this function several times, though, so it’s best to follow the DRY principle and pull it up to a function.

Now you’ve seen the bottom level of the functionality pyramid. It’s time to step up and use those tools to build a more complex function. You’re almost ready to solve the puzzle!

Finding What’s Possible

Your next function makes use of some of the low-level functions you’ve just walked through. Given a grid and a position on that grid, it determines what values that position could still have:

A Sudoku grid showing a starting point to indicate possible values for a specific cell.

For the grid above, at the position (3, 1) , the possible values are [1, 5, 8] because the other values are all present, either in that row or column or in the small square you looked at earlier.

This is the responsibility of detect_possible() :

The function starts by checking if the given position at x and y already has a nonzero value. If so, then that’s the only possible value and it returns.

If not, then the function creates a set of the numbers one through nine. The function proceeds to check different blocking numbers and removes those from this set.

It starts by checking the column and row of the given position. This can be done with a single loop by just alternating which subscript changes. grid[x][index] checks values in the same column, while grid[index][y] checks those values in the same row. You can see that you’re using test_and_remove() here to simplify the code.

Once those values have been removed from your possible set, the function moves on to the small square. This is where the small_square() generator you created before comes in handy. You can use it to iterate over each position in the small square, again using test_and_remove() to eliminate any known values from your possible list.

Once all the known blocking values have been removed from your set, you have the list of all possible values for that position on that grid.

You might wonder why the code and its description make a point about the position being “on that grid.” In your next function, you’ll see that the program makes many copies of the grid as it tries to solve it.

You’ve reached the heart of this solution: solve() ! This function is recursive, so a little up-front explanation might help.

The general design of solve() is based on testing a single position at a time. For the position of interest, the algorithm gets the list of possible values and then selects those values, one at a time, to be in this position.

For each of these values, it creates a grid with the guessed value in this position. It then calls a function to test for a solution, passing in the new grid and the next position.

It just so happens that the function it calls is itself.

For any recursion, you need a termination condition. This algorithm has four of them:

  • There are no possible values for this position. That indicates the solution it’s testing can’t work.
  • It’s walked to the end of the grid and found a possible value for each position. The puzzle is solved!
  • One of the guesses at this position, when passed back to the solver, returns a solution.
  • It’s tried all possible values at this position and none of them will work.

Let’s look at the code for this and see how it all plays out:

The first thing to note in this function is that it makes a .deepcopy() of the grid. It does a deep copy because the algorithm needs to keep track of exactly where it was at any point in the recursion. If the function made only a shallow copy, then every recursive version of this function would use the same grid.

Once the grid is copied, solve() can work with the new copy, temp . A position on the grid was passed in, so that’s the number that this version of the function will solve. The first step is to see what values are possible in this position. As you saw earlier, detect_possible() returns a list of possible values that may be empty.

If there are no possible values, then you’ve hit the first termination condition for the recursion. The function returns False , and the calling routine moves on.

If there are possible values, then you need to move on and see if any of them is a solution. Before you do that, you can add a little optimization to the code. If there’s only a single possible value, then you can insert that value and move on to the next position. The solution shown does this in a loop, so you can place multiple numbers into the grid without having to recur.

This may seem like a small improvement, and I’ll admit my first implementation did not include this. But some testing showed that this solution was dramatically faster than simply recurring here at the price of more complex code.

Note: This is an excellent point to bring up during an interview even if you don’t add the code to do this. Showing them that you’re thinking about trading off speed against complexity is a strong positive signal to interviewers.

Sometimes, of course, there will be multiple possible values for the current position, and you’ll need to decide if any of them will lead to a solution. Fortunately, you’ve already determined the next position in the grid, so you can forgo placing the possible values.

If the next position is off the end of the grid, then the current position is the final one to fill. If you know that there’s at least one possible value for this position, then you’ve found a solution! The current position is filled in and the completed grid is returned up to the calling function.

If the next position is still on the grid, then you loop through each possible value for the current spot, filling in the guess at the current position and then calling solve() with the temp grid and the new position to test.

solve() can return only a completed grid or False , so if any of the possible guesses returns a result that isn’t False , then a result has been found, and that grid can be returned up the stack.

If all possible guesses have been made and none of them is a solution, then the grid that was passed in is unsolvable. If this is the top-level call, then that means the puzzle is unsolvable. If the call is lower in the recursion tree, then it just means that this branch of the recursion tree isn’t viable.

Putting It All Together

At this point, you’re almost through the solution. There’s only one final function left, sudoku_solve() :

This function does three things:

  • Converts the input string into a grid
  • Calls solve() with that grid to get a solution
  • Returns the solution as a string or "Unsolvable" if there’s no solution

That’s it! You’ve walked through a solution for the sudoku solver problem.

Interview Discussion Topics

The sudoku solver solution you just walked through is a good deal of code for an interview situation. Part of an interview process would likely be to discuss some of the code and, more importantly, some of the design trade-offs you made. Let’s look at a few of those trade-offs.

The biggest design decision revolves around using recursion. It’s possible to write a non-recursive solution to any problem that has a recursive solution. Why choose recursion over another option?

This is a discussion that depends not only on the problem but also on the developers involved in writing and maintaining the solution. Some problems lend themselves to rather clean recursive solutions, and some don’t.

In general, recursive solutions will take more time to run and use more memory than non-recursive solutions. But that’s not always true and, more importantly, it’s not always important .

Similarly, some teams of developers are comfortable with recursive solutions, while others find them exotic or unnecessarily complex. Maintainability should play into your design decisions as well.

One good discussion to have about a decision like this is around performance. How fast does this solution need to execute? Will it be used to solve billions of puzzles or just a handful? Will it run on a small embedded system with memory constraints, or will it be on a large server?

These external factors can help you decide which is a better design decision. These are great topics to bring up in an interview as you’re working through a problem or discussing code. A single product might have places where performance is critical (doing ray tracing on a graphics algorithm, for example) and places where it doesn’t matter at all (such as parsing the version number during installation).

Bringing up topics like this during an interview shows that you’re not only thinking about solving an abstract problem, but you’re also willing and able to take it to the next level and solve a specific problem facing the team.

Readability and Maintainability

Sometimes it’s worth picking a solution that’s slower in order to make a solution that’s easier to work with, debug, and extend. The decision in the sudoku solver challenge to convert the data structure to a grid is one of those decisions.

That design decision likely slows down the program, but unless you’ve measured, you don’t know. Even if it does, putting the data structure into a form that’s natural for the problem can make the code easier to comprehend.

It’s entirely possible to write a solver that operates on the linear strings you’re given as input. It’s likely faster and probably takes less memory, but small_square() , among others, will be a lot harder to write, read, and maintain in this version.

Another thing to discuss with an interviewer, whether you’re live coding or discussing code you wrote offline, is the mistakes and false turns you took along the way.

This is a little less obvious and can be slightly detrimental, but particularly if you’re live coding, taking a step to refactor code that isn’t right or could be better can show how you work. Few developers can write perfect code the first time. Heck, few developers can write good code the first time.

Good developers write the code, then go back and refactor it and fix it. For example, my first implementation of detect_possible() looked like this:

Ignoring that it doesn’t consider the small_square() information, this code can be improved. If you compare this to the final version of detect_possible() above, you’ll see that the final version uses a single loop to test both the horizontal and the vertical dimensions.

Wrapping Up

That’s your tour through a sudoku solver solution. There’s more information available on formats for storing puzzles and a huge list of sudoku puzzles you can test your algorithm on.

That’s the end of your Python practice problems adventure! But if you’d like more, head on over to the video course Write and Test a Python Function: Interview Practice to see an experienced developer tackle an interview problem in real time.

Congratulations on working through this set of Python practice problems! You’ve gotten some practice applying your Python skills and also spent some time thinking about how you can respond in different interviewing situations.

In this tutorial, you learned how to:

Remember, you can download the skeleton code for these problems by clicking on the link below:

Feel free to reach out in the comments section with any questions you have or suggestions for other Python practice problems you’d like to see! Also check out our “Ace Your Python Coding Interview” Learning Path to get more resources and for boosting your Python interview skills.

Good luck with the interview!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Jim Anderson

Jim Anderson

Jim has been programming for a long time in a variety of languages. He has worked on embedded systems, built distributed build systems, done off-shore vendor management, and sat in many, many meetings.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices career

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Practice Problems Sample Code

🔒 No spam. We take your privacy seriously.

python problem solving websites

Table of Contents

Best Websites to Practice Python

Best Websites to Practice Python

Have you ever wondered how you could dive into the world of programming without spending a dime?

Today, we’re exploring the best websites to practice Python for free, a perfect starting point for anyone looking to break into tech. Let’s find out how you can start your coding journey today!

10 Best Websites for Practicing Python – Overview

Here’s an overview of the top 10 websites to practice Python:

S.No.Website NamePricingCertificationWebsite Link
1GUVIFreemiumNo
2HackerRankFreeYes
3LeetCodeFree/PaidYes
4CodewarsFreeNo
5PYnativeFreeNo
6EdabitFreeNo
7CheckiOFreeNo
8FreeCodeCampFreeNo
9RosalindFreeNo
10CodingBatFreeNo

python course desktop banner horizontal

Below is the list of best websites to practice Python for beginners:

CodeKata hosts a diverse range of coding problems used by top companies like Microsoft, Walmart, and Samsung, aimed at sharpening coding skills.

Practicing on CodeKata elevates users’ coding skills, making them attractive candidates for tech recruiters.

Questions Diversity: Students can practice topics such as Arrays, Mathematics, Strings, Basics, Sorting, Matrix, Hashing, Dynamic Programming, and various data structures including Linked Lists, Trees, Graphs, and more.

Pricing: Freemium

Certifications and Rewards: Rewards are available in the form of “Geekoins” earned by solving challenges.

Language Options: English

Community and Support: Nil

Practice Now

2. HackerRank

HackerRank’s Python domain is a structured learning path to grasp Python—a powerful yet straightforward programming language to learn.

Users can improve their programming skills through practical challenges that enhance problem-solving abilities in a real-world context.

Questions Diversity: Challenges range from basic syntax exercises to complex problem-solving scenarios covering various topics such as data types, strings, sets, math operations, collections, regex, and more, classified under difficulty levels of easy, medium, and hard.

Pricing: Free

Certifications and Rewards: Shareable certificates

Community and Support: HackerRank supports a robust community platform where users can discuss problems, solutions, and share insights.

3. LeetCode

LeetCode offers a comprehensive platform for boosting coding interview skills, featuring a broad range of problems frequently asked by top-tier companies, designed to improve coding proficiency and confidence.

Questions Diversity: The platform includes challenges across various topics like arrays, strings, hash tables, math, dynamic programming, sorting, and more, classified under categories like data structures, algorithms, and databases. The problems are further categorized by difficulty: easy, medium, and hard.

Pricing: Free and paid subscription options, with the paid tier (LeetCode Premium) providing access to more questions and company-specific practice sets.

Certifications and Rewards: Nil

Community and Support: LeetCode features a community section where users can discuss problems, share solutions, and participate in contests.

4. Codewars

Codewars offers a competitive platform for developers to engage in coding challenges, known as “kata,” that improve their programming skills through practice and competition.

Participants can earn ranks and honors by solving problems and can refine their skills through repeated practice.

Questions Diversity: The platform features a variety of challenges categorized by programming topics such as algorithms, regular expressions, strings, geometry, mathematics, and puzzles, covering fundamental to advanced levels.

Community and Support: Codewars has a vibrant community with features like leaderboards, a Discord server for live chat, and a Github Discussions board.

5. PYnative

PYnative provides a comprehensive suite of Python coding exercises designed to help developers of all skill levels improve through practice on topic-specific challenges, ranging from Python basics to more advanced topics like data analytics.

Questions Diversity: The site offers exercises across a variety of Python topics including basics, loops, functions, strings, lists, dictionaries, sets, tuples, date and time, OOP, JSON, NumPy, Pandas, and Matplotlib. Each topic includes a set of exercises aimed at reinforcing specific programming skills.

Edabit provides a gamified learning experience similar to Duolingo but for coding, offering over 10,000 interactive challenges to help learners code with fun and engaging tasks.

The platform aims to make learning to code as enjoyable as playing a game, where users can earn experience points, and unlock achievements.

Questions Diversity: The challenges span a variety of programming languages, primarily focused on JavaScript, with difficulties ranging from very easy to more advanced levels.

CheckiO offers an interactive platform where both beginners and advanced programmers can enhance their coding skills through engaging games and challenges.

It primarily focuses on Python and TypeScript, making it a versatile tool for learning and applying different programming concepts.

Questions Diversity: The platform provides a wide range of coding challenges and games that cater to different skill levels, promoting learning in an enjoyable and practical way.

Language Options: English, Russian, and Ukrainian

Community and Support: Supports educational environments by allowing teachers to create classrooms and use the platform as a supplementary tool.

8. freeCodeCamp

freeCodeCamp’s Project Euler section offers a challenging yet educational way to enhance both mathematical and algorithmic skills through a series of programming challenges drawn from the extensive Project Euler archives.

Questions Diversity: The problems range in difficulty, requiring users to apply various mathematical concepts like the Fibonacci sequence, prime number theory, and combinatorics. Each problem is designed to introduce a new concept or technique, progressively building more complex skills.

Community and Support: Supportive community through forums and additional resources like articles and tutorials.

9. Rosalind

Rosalind is a unique platform tailored for learning bioinformatics and programming through problem-solving. It encourages users to understand and apply programming and scientific methods to complex biological data.

Questions Diversity: The site offers structured learning paths, such as Python Village for beginners, Bioinformatics Stronghold for complex algorithm challenges, Bioinformatics Armory for using existing tools, and more detailed courses linked to academic textbooks.

10. CodingBat

CodingBat offers a focused environment for practicing Python programming with exercises that help sharpen programming skills through hands-on practice in a simplified interface.

Questions Diversity: Includes simple warm-up problems to get started, string manipulation exercises, basic to medium list problems, and basic to medium boolean logic puzzles.

Frequently Asked Questions

1. what are the best websites for practicing python.

The best websites for practicing python are:

  • freeCodeCamp

2. Why should I choose website for practicing Python?

Websites for practicing Python offer interactive exercises, immediate feedback, and a structured learning path, making it easier to learn and apply Python concepts practically.

3. How do I choose the right website for practicing Python?

To choose the right website for practicing Python, consider factors like the range of difficulty levels, specific topics covered, the presence of step-by-step solutions, and community support.

4. Can a beginner practice Python effectively through websites?

Yes, a beginner can effectively practice Python through websites. These platforms often provide beginner-friendly tutorials, exercises graded by difficulty, and instant feedback.

5. Are there websites that offer content in multiple languages for practicing Python?

Yes, websites like CheckiO provide Python practice content in multiple languages.

Final Words

With so many excellent resources available at no cost, starting your journey into Python has never been easier or more accessible.

Keep checking this article as we will keep updating this space as more websites make space in the heart and study schedule of students preparing for placements and competitive exams.

Explore More Python Resources

  • Python Learning Websites
  • Python YouTube Channels
  • Python Project Ideas
  • Python IDEs

Explore More Practice Websites

  • HTML & CSS
  • C Programming
  • Data Structures & Algorithms

zen-class

Thirumoorthy

Thirumoorthy serves as a teacher and coach. He obtained a 99 percentile on the CAT. He cleared numerous IT jobs and public sector job interviews, but he still decided to pursue a career in education. He desires to elevate the underprivileged sections of society through education

fb-icon

Related Posts

Best Websites to Practice Python

Top React Native Interview Questions for Freshers

Are you preparing for your first React Native interview and wondering what questions you might face? Understanding the key React …

Best Websites to Practice Python

Top Django Interview Questions for Freshers

Are you preparing for your first Django interview and wondering what questions you might face? Understanding the key Django interview …

Best Websites to Practice Python

Top MongoDB Interview Questions for Freshers

Are you preparing for your first MongoDB interview and wondering what questions you might face? Understanding the key MongoDB interview …

Python Programming

Python Basic Exercise for Beginners

Updated on:  August 29, 2024 | 498 Comments

This essential Python exercise helps Python beginners learn necessary Python skills quickly.

Immerse yourself in the practice of Python’s foundational concepts, such as loops, control flow, data types, operators, list, strings, input-output, and built-in functions. This beginner’s exercise is sure to elevate your understanding of Python.

Also, See :

  • Python Quizzes : Solve quizzes to test your knowledge of fundamental concepts.
  • Python Basics : Learn the basics to solve this exercise.

What questions are included in this Python fundamental exercise?

  • The exercise contains  15 Python programs to solve , ranging from beginner to intermediate difficulty.
  • The hints and solutions are provided for each question.
  • Tips and essential learning resources accompany each question . These will assist you in solving the exercise and empower you with the knowledge to tackle similar problems in the future, boosting your confidence and capability. As you progress, you’ll become more familiar with the basics of Python.

Use Online Code Editor to solve exercises.

This Python exercise covers questions on the following topics :

  • Python for loop and while loop
  • Python list , set , tuple , dictionary , input, and output

Also, try to solve the basic Python Quiz for beginners

Exercise 1: Calculate the multiplication and sum of two numbers

Given two integer numbers, write a Python code to return their product only if the product is equal to or lower than 1000. Otherwise, return their sum.

Expected Output :

  • Accept user input in Python
  • Calculate an Average in Python
  • Create a function that will take two numbers as parameters
  • Next, Inside a function, multiply two numbers and save their product in a product variable
  • Next, use the if condition to check if the product >1000 . If yes, return the product
  • Otherwise, use the else block to calculate the sum of two numbers and return it.

Exercise 2: Print the Sum of a Current Number and a Previous number

Write a Python code to iterate the first 10 numbers, and in each iteration, print the sum of the current and previous number.

Reference article for help :

  • Python range() function
  • Calculate sum and average in Python
  • Create a  variable  called  previous_num  and assigning it to 0
  • Next, iterate through the first 10 numbers using the for loop  and  range()  function
  • Next, display the current number ( i ), the previous number, and the addition of both numbers in each iteration of a loop
  • Finally, you need to update the previous_num for the next iteration. To do this, assign the value of the current number to the previous number ( previous_num = i).

Exercise 3: Print characters present at an even index number

Write a Python code to accept a string from the user and display characters present at an even index number.

For example, str = "PYnative" . so your code should display ‘P’, ‘n’, ‘t’, ‘v’.

Reference article for help: Python Input and Output

  • Use the Python input() function to accept a string from a user.
  • Calculate the length of the string using the len() function
  • Next, iterate characters of a string using the loop and range() function.
  • Use start = 0, stop = len(s)-1, and step =2. the step is 2 because we want only even index numbers
  • In each iteration of a loop, use s[i] to print characters present at the current even index number

Solution 1 :

Solution 2 : Using list slicing

Exercise 4: Remove first n characters from a string

Write a Python code to remove characters from a string from 0 to n and return a new string.

For Example:

  • remove_chars("PYnative", 4) so output must be tive . Here, you need to remove the first four characters from a string.
  • remove_chars("PYnative", 2) so output must be native . Here, you need to remove the first two characters from a string.

Note : n must be less than the length of the string.

Use string slicing to get a substring. For example, remove the first four characters using s[4:] .

Also, try to solve  Python string exercises

Exercise 5: Check if the first and last numbers of a list are the same

Write a code to return True if the list’s first and last numbers are the same. If the numbers are different, return False .

Exercise 6: Display numbers divisible by 5

Write a Python code to display numbers from a list divisible by 5

Also, try to solve  Python list Exercise

Exercise 7: Find the number of occurrences of a substring in a string

Write a Python code to find how often the substring “ Emma ” appears in the given string.

Use string method count() .

Solution 1 : Use the count() method

Solution 2 : Without the string method

Exercise 8: Print the following pattern

Hint : Print Pattern using for loop

Exercise 9: Check Palindrome Number

Write a Python code to check if the given number is palindrome. A palindrome number is a number that is the same after reverse. For example, 545 is the palindrome number .

  • Reverse the given number and save it in a different variable
  • Use the if condition to check if the original and reverse numbers are identical. If yes, return True .

Exercise 10: Merge two lists using the following condition

Given two lists of numbers, write a Python code to create a new list such that the latest list should contain odd numbers from the first list and even numbers from the second list .

  • Create an empty list named result_list
  • Iterate the first list using a for loop
  • In each iteration check if the current number is odd using the num % 2 != 0 formula. If the current number is odd, add it to the result list
  • Now, Iterate the second list using a loop.
  • In each iteration check if the current number is even using the num % 2 == 0 formula. If the current number is even, add it to the result list.
  • Print the result list.

Note: Try to solve the Python list exercises

Exercise 11: Get each digit from a number in the reverse order.

For example, If the given integer number is 7536 , the output shall be “ 6 3 5 7 “, with a space separating the digits.

Use while loop

Exercise 12: Calculate income tax

Calculate income tax for the given income by adhering to the rules below

Taxable IncomeRate (in %)
First $10,0000
Next $10,00010
The remaining20

For example, suppose the income is 45000, and the income tax payable is

10000*0% + 10000*10%  + 25000*20% = $6000.

Exercise 13: Print multiplication table from 1 to 10

See : How to use nested loops in Python

  • Create the outer for loop to iterate numbers from 1 to 10. Thus, the outer loop’s total number of iterations is 10.
  • Create an inner loop to iterate 10 times.
  • For each outer loop iteration, the inner loop will execute 10 times.
  • The number is 1 in the first iteration of the outer loop. In the next, it is 2, and so on until it reaches 10.
  • In each iteration of an inner loop, we perform a simple calculation: the multiplication of two numbers. (current outer number and current inner number)

Exercise 14: Print a downward half-pyramid pattern of stars

Exercise 15: get an int value of base raises to the power of exponent.

Write a function called exponent(base, exp) that returns an int value of base raises to the power of exp.

Note here exp is a non-negative integer, and the base is an integer.

Expected output

I want to hear from you. What do you think of this essential exercise? If you have better alternative answers to the above questions, please help others by commenting on this exercise.

I have shown only 15 questions in this exercise because we have Topic-specific exercises to cover each topic exercise in detail. Please refer to all Python exercises .

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

python problem solving websites

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

Achieve mastery through challenge

Improve your development skills by training with your peers on code kata that continuously challenge and push your coding practice.

python problem solving websites

Sharpen your coding skills

Challenge yourself on small coding exercises called "kata". Each kata is crafted by the community to help you strengthen different coding techniques. Master your current language of choice, or quickly pick up any of the 55+ programming languages supported.

python problem solving websites

Get instant feedback

Solve kata with your coding style right in the browser and use test cases (TDD) to check it as you progress. Retrain with new, creative, and optimized approaches. Find all of the bugs in your programming practice.

python problem solving websites

Earn ranks and honor

Kata code challenges are ranked from beginner to expert level. As you complete higher-ranked kata, you level up your profile and push your software development skills to your highest potential.

python problem solving websites

An engaged software development community

Codewars is a collective effort by its users. They are creators—authoring kata to teach various techniques, solving kata with solutions that enlighten others, and commenting with constructive feedback.

Community members added every month

Kata completed every month

Kata created by our community

Tap into the collective wisdom

Compare your solution with others after each kata for greater understanding. Discuss kata, best practices, and innovative techniques with the community. Have your mind blown by how different other solutions can be from your own.

python problem solving websites

Create your own kata

Author kata that focus on your interests and train specific skill sets. Challenge the community with your insight and code understanding. Create everything from common developer interview questions to challenges that push the limits of your creativity. Gain honor within the coding dojo.

python problem solving websites

What can I use Codewars for?

From beginner to expert and beyond...

Get new perspectives

Solve challenges then view how others solved the same challenge. Pickup new techniques from some of the most skilled developers in the world.

Learn new languages

Solve challenges in a language you are comfortable with, then do it in a language you want to improve with. Level up across different languages.

Compete with peers

Compete against your friends, colleagues, and the community at large. Allow competition to motivate you  towards mastering your craft.

Extremely well done and an excellent example of mastery learning.

python problem solving websites

Ahmed Omran

@this_ahmed

Accidentally got addicted to codewars, oops.

python problem solving websites

Kelly Williams

Build self-confidence

Not sure if you are progressing well as a programmer? Push yourself to your limits and show yourself what you are really made of.

Become a mentor

Lend your expertise to others, either indirectly by contributing great solutions or directly by creating your own kata and reviewing code.

Insights from Codewars staff and community.

Author's Corner, meet geoffp

Author's Corner, meet geoffp

python problem solving websites

What's new in Codewars: April highlights

python problem solving websites

Introducing the EPIC Challenge 2024

Codewars is built on.

The world's most advanced coding assessment platform for organizations looking to scale their hiring, upskilling, and certification programs.

Achieve mastery through challenge.

Top languages

  • Data Science
  • Courses 90% Refund Ending

Featured Sprints

IMAGES

  1. Python Problem Solving Session (Platform Walkthrough & Basic Question

    python problem solving websites

  2. Solving an Optimization Problem with Python

    python problem solving websites

  3. SOLUTION: Problem solving using python

    python problem solving websites

  4. solve my python problem

    python problem solving websites

  5. Python Problem Solving Course (Beginners)

    python problem solving websites

  6. Solving Problems in Python using Functions

    python problem solving websites

VIDEO

  1. Python Problem Set-6 Lists and 2D Lists. 14 Examples

  2. Solving Problems Using input method in Python

  3. Where did all the pythons go?

  4. PYTHON : CONCEPT OF PROBLEM SOLVING

  5. Solving Problems Using input() method in Python

  6. Python problem solving

COMMENTS

  1. Solve Python

    Solve Python | HackerRank ... Solve Python

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

    There is a single operator in Python, capable of providing the remainder of a division operation. Two numbers are passed as parameters. The first parameter divided by the second parameter will have a remainder, possibly zero. Return that value. Examples remainder(1, 3) 1 remainder(3, 4) 3 remainder(5, 5) 0 remainde …

  3. Problems

    Problems - LeetCode

  4. Python Exercises, Practice, Challenges

    Practice Python Exercises and Challenges with Solutions

  5. Practice Python

    Practice Python - CodeChef ... Practice Python

  6. Python exercises online

    Instead of watching another boring video tutorial, learn Python the fun way. We offer a carefully designed mix of bite-sized lessons, Python coding challenges, and engaging quizzes. Home Python Tutorial Introduction Conditionals. temperature = 60. if temperature. > 70: print ("It's warm outside") else: print ("It's cold outside")

  7. Python Practice: 93 Unique Online Coding Exercises

    Python Practice: 93 Unique Online Coding Exercises

  8. py.CheckiO

    py.CheckiO - Python practice online. Improve your coding skills by solving coding challenges and exercises online with your friends in a fun way. Exchanges experience with other users online through fun coding activities.

  9. PYnative: Learn Python with Tutorials, Exercises, and Quizzes

    PYnative: Learn Python with Tutorials, Exercises, and Quizzes

  10. Online Python Challenges

    Online Python Challenges

  11. Exercises and Solutions

    Beginner Python exercises. Home; Why Practice Python? Why Chilis? Resources for learners; All Exercises. 1: Character Input 2: Odd Or Even 3: List Less Than Ten 4: Divisors 5: List Overlap 6: String Lists 7: List Comprehensions 8: Rock Paper Scissors 9: Guessing Game One 10: List Overlap Comprehensions 11: Check Primality Functions 12: List Ends 13: Fibonacci 14: List Remove Duplicates

  12. The 10 Most Popular Coding Challenge Websites [Updated for 2021]

    The 10 Most Popular Coding Challenge Websites ...

  13. 8 Websites you can practice Python for Data Science

    You can use LeetCode to practice your Python skills by solving coding problems that are focused on data structures, algorithms, and mathematical computations. 5. Google Code-in

  14. Learn Problem solving in Python

    Problem solving in Python. Learn problem solving in Python from our online course and tutorial. You will learn basic math, conditionals and step by step logic building to solve problems easily. 4.5 (3977 reviews) 18 lessons Beginner level. 51.4k Learners.

  15. Python Practice for Beginners: 15 Hands-On Problems

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

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

    Python Practice Problems: Get Ready for Your Next Interview

  17. Best Websites to Practice Python

    Below is the list of best websites to practice Python for beginners: 1. GUVI. CodeKata hosts a diverse range of coding problems used by top companies like Microsoft, Walmart, and Samsung, aimed at sharpening coding skills. Practicing on CodeKata elevates users' coding skills, making them attractive candidates for tech recruiters.

  18. Online Coding Practice Problems & Challenges

    Online Coding Practice Problems & Challenges

  19. Python Basic Exercise for Beginners with Solutions

    Python Basic Exercise for Beginners with Solutions

  20. Codewars

    Codewars - Achieve mastery through coding practice and ...

  21. Top 10 Coding Challenges Websites to Enhance Your ...

    It is unique in doing team-oriented problem solving and showcases your talent to an employer. 5. CodeChef. CodeChef is one of the popular competitive programming websites where you can go in and take challenges in real practice to develop and refine your programming skills.

  22. 10,000+ Coding Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this: function hello () { } All you have to do is type return "hello edabit.com" between the curly braces { } and then click the Check button. If you did this correctly, the button will turn red and ...

  23. Practice

    A computer science portal for geeks