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

Python if-else easy python (basic) max score: 10 success rate: 89.68%, arithmetic operators easy python (basic) max score: 10 success rate: 97.40%, python: division easy python (basic) max score: 10 success rate: 98.68%, loops easy python (basic) max score: 10 success rate: 98.10%, write a function medium python (basic) max score: 10 success rate: 90.31%, print function easy python (basic) max score: 20 success rate: 97.28%, list comprehensions easy python (basic) max score: 10 success rate: 97.68%, find the runner-up score easy python (basic) max score: 10 success rate: 94.18%, nested lists easy python (basic) max score: 10 success rate: 91.72%, cookie support is required to access hackerrank.

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

Mastering Algorithms for Problem Solving in Python

Mastering Algorithms for Problem Solving in Python

Intermediate

Certificate of Completion

AI-powered Learning:

This course includes:

Takeaway Skills

A comprehensive understanding of algorithms and their applications in problem solving

Proficiency in implementing recursion and backtracking in Python for complex tasks

An understanding of the concept of memoization and dynamic programming

Ability to apply memoization and dynamic programming for efficient computation in Python

Hands-on experience solving algorithmic challenges in Python

Course Overview

As a developer, mastering the concepts of algorithms and being proficient in implementing them is essential to improving problem-solving skills. This course aims to equip you with an in-depth understanding of algorithms and how they can be utilized for problem-solving in Python. Starting with the basics, you'll gain a foundational understanding of what algorithms are, with topics ranging from simple multiplication algorithms to analyzing algorithms. Then, you’ll delve into more advanced topics like recursi... Show More

Course Content

Expand All Sections

Getting Started

Introduction to Algorithm

Backtracking

Dynamic Programming

Greedy Algorithms

Prove Your Skills: A Five-Chapter Assessment

Basic Graph Algorithms

Depth-First Search

Minimum Spanning Trees

Shortest Paths

All-Pairs Shortest Paths

Pushing Your Limits: A Comprehensive Assessment

Wrapping up

learn problem solving with python

2. Install Python on Your computer.

Once you start writing complex programs and creating projects, you should definitely install Python on your computer. This is especially necessary when you are working with projects that involve multiple files and folders.

To install Python on your device, you can use this guide.

how-to-install-python-2

Getting Started with Python

Learn how you can install and use Python on your own computer.

Last chance to enroll in this weekend's Paradoxes and Infinity Seminar !

Need help finding the right class? Have a question about how classes work?

12 lessons

12 lessons  

May 29 - Aug 14
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Caleb Bilenkin $545 (~$46/week) (~$46/week) CLOSED

Jun 9 - Aug 25
1:00 - 2:30
PM ET  

1:00 - 2:30 PM Eastern
12:00 - 1:30 PM Central
11:00 - 12:30 PM Mountain
10:00 - 11:30 AM Pacific
Caleb Bilenkin $545 (~$46/week) (~$46/week) ENROLL

Jun 11 - Jul 23
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Asa Frank $545 CLOSED

Jun 21 - Sep 13
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Luís Finotti $545 (~$46/week) (~$46/week) ENROLL

Jul 9 - Sep 24
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Thinula De Silva $545 (~$46/week) (~$46/week) ENROLL

Aug 11 - Nov 3
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Luís Finotti $545 (~$46/week) (~$46/week) ENROLL

Sep 25 - Dec 18
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Martha Maria Bernal Guillen $545 (~$46/week) (~$46/week) ENROLL

Dec 2 - Mar 3
7:30 - 9:00
PM ET

7:30 - 9:00 PM Eastern
6:30 - 8:00 PM Central
5:30 - 7:00 PM Mountain
4:30 - 6:00 PM Pacific
Caleb Bilenkin $545 (~$46/week) (~$46/week) ENROLL

AoPS Holidays

Who should take.

This course will assume no previous computer programming experience . Students who are proficient in a programming language other than Python might be better served by studying Python syntax on their own before moving on to our Intermediate Python course. This class is appropriate for middle and high school students who do not have computer programming experience and have completed at least a Prealgebra math course.

Students with prior programming experience in Python might instead consider our Intermediate Programming with Python course. Students with considerable experience with another language might also consider our Intermediate Programming with Python course.

We will be providing a free online textbook for this class, which students can access from the class homepage. Students will also need to download free Python software onto their computers. We will provide detailed instructions for how to install this software prior to the beginning of the course.

1 What is Programming? What is Python?
2 Data Types, Variables, and Expressions
3 Turtles and Loops
4 Functions
5 Conditionals
6 Flow of Control
7 Strings
8 Lists and Tuples
9 File Input/Output
10 Dictionaries
11 Final Project (Part 1)
12 Final Project (Part 2)

This class was really a lot of fun. I liked it a lot. The instructors always gave clear explanations for almost everything, and they taught me some very good and helpful programming techniques. The assistants also answered all the questions I put out. I already signed up for intermediate Python, as I think that course should be as fun and helpful as this one.

Something appears to not have loaded correctly.

Click to refresh .

learn problem solving with python

10 Python Practice Exercises for Beginners with Solutions

Author's photo

  • python basics
  • get started with python
  • online practice

A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills.

Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types. Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level.

If you’re new to Python and looking for a structured way to improve your programming, consider taking the Python Basics Practice course. It includes 17 interactive exercises designed to improve all aspects of your programming and get you into good programming habits early. Read about the course in the March 2023 episode of our series Python Course of the Month .

Take the course Python Practice: Word Games , and you gain experience working with string functions and text files through its 27 interactive exercises.  Its release announcement gives you more information and a feel for how it works.

Each course has enough material to keep you busy for about 10 hours. To give you a little taste of what these courses teach you, we have selected 10 Python practice exercises straight from these courses. We’ll give you the exercises and solutions with detailed explanations about how they work.

To get the most out of this article, have a go at solving the problems before reading the solutions. Some of these practice exercises have a few possible solutions, so also try to come up with an alternative solution after you’ve gone through each exercise.

Let’s get started!

Exercise 1: User Input and Conditional Statements

Write a program that asks the user for a number then prints the following sentence that number of times: ‘I am back to check on my skills!’ If the number is greater than 10, print this sentence instead: ‘Python conditions and loops are a piece of cake.’ Assume you can only pass positive integers.

Here, we start by using the built-in function input() , which accepts user input from the keyboard. The first argument is the prompt displayed on the screen; the input is converted into an integer with int() and saved as the variable number. If the variable number is greater than 10, the first message is printed once on the screen. If not, the second message is printed in a loop number times.

Exercise 2: Lowercase and Uppercase Characters

Below is a string, text . It contains a long string of characters. Your task is to iterate over the characters of the string, count uppercase letters and lowercase letters, and print the result:

We start this one by initializing the two counters for uppercase and lowercase characters. Then, we loop through every letter in text and check if it is lowercase. If so, we increment the lowercase counter by one. If not, we check if it is uppercase and if so, we increment the uppercase counter by one. Finally, we print the results in the required format.

Exercise 3: Building Triangles

Create a function named is_triangle_possible() that accepts three positive numbers. It should return True if it is possible to create a triangle from line segments of given lengths and False otherwise. With 3 numbers, it is sometimes, but not always, possible to create a triangle: You cannot create a triangle from a = 13, b = 2, and c = 3, but you can from a = 13, b = 9, and c = 10.

The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be helpful to start drawing triangles before you start coding anything.

Python Practice Exercises for Beginners

Notice that the sum of any two sides must be larger than the third side to form a triangle. That means we need a + b > c, c + b > a, and a + c > b. All three conditions must be met to form a triangle; hence we need the and condition in the solution. Once you have this insight, the solution is easy!

Exercise 4: Call a Function From Another Function

Create two functions: print_five_times() and speak() . The function print_five_times() should accept one parameter (called sentence) and print it five times. The function speak(sentence, repeat) should have two parameters: sentence (a string of letters), and repeat (a Boolean with a default value set to False ). If the repeat parameter is set to False , the function should just print a sentence once. If the repeat parameter is set to True, the function should call the print_five_times() function.

This is a good example of calling a function in another function. It is something you’ll do often in your programming career. It is also a nice demonstration of how to use a Boolean flag to control the flow of your program.

If the repeat parameter is True, the print_five_times() function is called, which prints the sentence parameter 5 times in a loop. Otherwise, the sentence parameter is just printed once. Note that in Python, writing if repeat is equivalent to if repeat == True .

Exercise 5: Looping and Conditional Statements

Write a function called find_greater_than() that takes two parameters: a list of numbers and an integer threshold. The function should create a new list containing all numbers in the input list greater than the given threshold. The order of numbers in the result list should be the same as in the input list. For example:

Here, we start by defining an empty list to store our results. Then, we loop through all elements in the input list and test if the element is greater than the threshold. If so, we append the element to the new list.

Notice that we do not explicitly need an else and pass to do nothing when integer is not greater than threshold . You may include this if you like.

Exercise 6: Nested Loops and Conditional Statements

Write a function called find_censored_words() that accepts a list of strings and a list of special characters as its arguments, and prints all censored words from it one by one in separate lines. A word is considered censored if it has at least one character from the special_chars list. Use the word_list variable to test your function. We've prepared the two lists for you:

This is another nice example of looping through a list and testing a condition. We start by looping through every word in word_list . Then, we loop through every character in the current word and check if the current character is in the special_chars list.

This time, however, we have a break statement. This exits the inner loop as soon as we detect one special character since it does not matter if we have one or several special characters in the word.

Exercise 7: Lists and Tuples

Create a function find_short_long_word(words_list) . The function should return a tuple of the shortest word in the list and the longest word in the list (in that order). If there are multiple words that qualify as the shortest word, return the first shortest word in the list. And if there are multiple words that qualify as the longest word, return the last longest word in the list. For example, for the following list:

the function should return

Assume the input list is non-empty.

The key to this problem is to start with a “guess” for the shortest and longest words. We do this by creating variables shortest_word and longest_word and setting both to be the first word in the input list.

We loop through the words in the input list and check if the current word is shorter than our initial “guess.” If so, we update the shortest_word variable. If not, we check to see if it is longer than or equal to our initial “guess” for the longest word, and if so, we update the longest_word variable. Having the >= condition ensures the longest word is the last longest word. Finally, we return the shortest and longest words in a tuple.

Exercise 8: Dictionaries

As you see, we've prepared the test_results variable for you. Your task is to iterate over the values of the dictionary and print all names of people who received less than 45 points.

Here, we have an example of how to iterate through a dictionary. Dictionaries are useful data structures that allow you to create a key (the names of the students) and attach a value to it (their test results). Dictionaries have the dictionary.items() method, which returns an object with each key:value pair in a tuple.

The solution shows how to loop through this object and assign a key and a value to two variables. Then, we test whether the value variable is greater than 45. If so, we print the key variable.

Exercise 9: More Dictionaries

Write a function called consonant_vowels_count(frequencies_dictionary, vowels) that takes a dictionary and a list of vowels as arguments. The keys of the dictionary are letters and the values are their frequencies. The function should print the total number of consonants and the total number of vowels in the following format:

For example, for input:

the output should be:

Working with dictionaries is an important skill. So, here’s another exercise that requires you to iterate through dictionary items.

We start by defining a list of vowels. Next, we need to define two counters, one for vowels and one for consonants, both set to zero. Then, we iterate through the input dictionary items and test whether the key is in the vowels list. If so, we increase the vowels counter by one, if not, we increase the consonants counter by one. Finally, we print out the results in the required format.

Exercise 10: String Encryption

Implement the Caesar cipher . This is a simple encryption technique that substitutes every letter in a word with another letter from some fixed number of positions down the alphabet.

For example, consider the string 'word' . If we shift every letter down one position in the alphabet, we have 'xpse' . Shifting by 2 positions gives the string 'yqtf' . Start by defining a string with every letter in the alphabet:

Name your function cipher(word, shift) , which accepts a string to encrypt, and an integer number of positions in the alphabet by which to shift every letter.

This exercise is taken from the Word Games course. We have our string containing all lowercase letters, from which we create a shifted alphabet using a clever little string-slicing technique. Next, we create an empty string to store our encrypted word. Then, we loop through every letter in the word and find its index, or position, in the alphabet. Using this index, we get the corresponding shifted letter from the shifted alphabet string. This letter is added to the end of the new_word string.

This is just one approach to solving this problem, and it only works for lowercase words. Try inputting a word with an uppercase letter; you’ll get a ValueError . When you take the Word Games course, you slowly work up to a better solution step-by-step. This better solution takes advantage of two built-in functions chr() and ord() to make it simpler and more robust. The course contains three similar games, with each game comprising several practice exercises to build up your knowledge.

Do You Want More Python Practice Exercises?

We have given you a taste of the Python practice exercises available in two of our courses, Python Basics Practice and Python Practice: Word Games . These courses are designed to develop skills important to a successful Python programmer, and the exercises above were taken directly from the courses. Sign up for our platform (it’s free!) to find more exercises like these.

We’ve discussed Different Ways to Practice Python in the past, and doing interactive exercises is just one way. Our other tips include reading books, watching videos, and taking on projects. For tips on good books for Python, check out “ The 5 Best Python Books for Beginners .” It’s important to get the basics down first and make sure your practice exercises are fun, as we discuss in “ What’s the Best Way to Practice Python? ” If you keep up with your practice exercises, you’ll become a Python master in no time!

You may also like

learn problem solving with python

How Do You Write a SELECT Statement in SQL?

learn problem solving with python

What Is a Foreign Key in SQL?

learn problem solving with python

Enumerate and Explain All the Basic Elements of an SQL Query

Introduction to Data Science with Python

Join Harvard University instructor Pavlos Protopapas in this online course to learn how to use Python to harness and analyze data.

Course Image for Introduction to Data Science with Python

Associated Schools

Harvard School of Engineering and Applied Sciences

Harvard School of Engineering and Applied Sciences

What you'll learn.

Gain hands-on experience and practice using Python to solve real data science challenges

Practice Python coding for modeling, statistics, and storytelling

Utilize popular libraries such as Pandas, numPy, matplotlib, and SKLearn

Run basic machine learning models using Python, evaluate how those models are performing, and apply those models to real-world problems

Build a foundation for the use of Python in machine learning and artificial intelligence, preparing you for future Python study

Course description

Every single minute, computers across the world collect millions of gigabytes of data. What can you do to make sense of this mountain of data? How do data scientists use this data for the applications that power our modern world?

Data science is an ever-evolving field, using algorithms and scientific methods to parse complex data sets. Data scientists use a range of programming languages, such as Python and R, to harness and analyze data. This course focuses on using Python in data science. By the end of the course, you’ll have a fundamental understanding of machine learning models and basic concepts around Machine Learning (ML) and Artificial Intelligence (AI). 

Using Python, learners will study regression models (Linear, Multilinear, and Polynomial) and classification models (kNN, Logistic), utilizing popular libraries such as sklearn, Pandas, matplotlib, and numPy. The course will cover key concepts of machine learning such as: picking the right complexity, preventing overfitting, regularization, assessing uncertainty, weighing trade-offs, and model evaluation. Participation in this course will build your confidence in using Python, preparing you for more advanced study in Machine Learning (ML) and Artificial Intelligence (AI), and advancement in your career.

Learners must have a minimum baseline of programming knowledge (preferably in Python) and statistics in order to be successful in this course. Python prerequisites can be met with an introductory Python course offered through CS50’s Introduction to Programming with Python, and statistics prerequisites can be met via Fat Chance or with Stat110 offered through HarvardX.

Instructors

Pavlos Protopapas

Pavlos Protopapas

You may also like.

Two people looking at code on a computer screen.

Machine Learning and AI with Python

Learn how to use decision trees, the foundational algorithm for your understanding of machine learning and artificial intelligence.

Illustration

Quantitative Methods for Biology

Learn introductory programming and data analysis in MATLAB, with applications to biology and medicine.

graphic image of silver and gray cubes stacked among each other at different heights

Ciencia de Datos: Fundamentos de R

Sentar las bases de conocimiento en R y aprender a discutir, analizar y visualizar datos.

Join our list to learn more

  • Why Python?
  • The Anaconda Distribution of Python
  • Installing Anaconda on Windows
  • Installing Anaconda on MacOS
  • Installing Anaconda on Linux
  • Installing Python from Python.org
  • Review Questions

Orientation

Introduction.

Welcome to the world of problem solving with Python! This first Orientation chapter will help you get started by guiding you through the process of installing Python on your computer. By the end of this chapter, you will be able to:

Describe why Python is a useful computer language for problem solvers

Describe applications where Python is used

Detail advantages of Python over other programming languages

Know the cost of Python

Know the difference between Python and Anaconda

Install Python on your computer

Install Anaconda on your computer

Hands-On Linear Programming: Optimization With Python

Hands-On Linear Programming: Optimization With Python

Table of Contents

What Is Linear Programming?

What is mixed-integer linear programming, why is linear programming important, linear programming with python, small linear programming problem, infeasible linear programming problem, unbounded linear programming problem, resource allocation problem, installing scipy and pulp, using scipy, linear programming resources, linear programming solvers.

Linear programming is a set of techniques used in mathematical programming , sometimes called mathematical optimization, to solve systems of linear equations and inequalities while maximizing or minimizing some linear function . It’s important in fields like scientific computing, economics, technical sciences, manufacturing, transportation, military, management, energy, and so on.

The Python ecosystem offers several comprehensive and powerful tools for linear programming. You can choose between simple and complex tools as well as between free and commercial ones. It all depends on your needs.

In this tutorial, you’ll learn:

  • What linear programming is and why it’s important
  • Which Python tools are suitable for linear programming
  • How to build a linear programming model in Python
  • How to solve a linear programming problem with Python

You’ll first learn about the fundamentals of linear programming. Then you’ll explore how to implement linear programming techniques in Python. Finally, you’ll look at resources and libraries to help further your linear programming journey.

Free Bonus: 5 Thoughts On Python Mastery , a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

Linear Programming Explanation

In this section, you’ll learn the basics of linear programming and a related discipline, mixed-integer linear programming. In the next section , you’ll see some practical linear programming examples. Later, you’ll solve linear programming and mixed-integer linear programming problems with Python.

Imagine that you have a system of linear equations and inequalities. Such systems often have many possible solutions. Linear programming is a set of mathematical and computational tools that allows you to find a particular solution to this system that corresponds to the maximum or minimum of some other linear function.

Mixed-integer linear programming is an extension of linear programming. It handles problems in which at least one variable takes a discrete integer rather than a continuous value . Although mixed-integer problems look similar to continuous variable problems at first sight, they offer significant advantages in terms of flexibility and precision.

Integer variables are important for properly representing quantities naturally expressed with integers, like the number of airplanes produced or the number of customers served.

A particularly important kind of integer variable is the binary variable . It can take only the values zero or one and is useful in making yes-or-no decisions, such as whether a plant should be built or if a machine should be turned on or off. You can also use them to mimic logical constraints.

Linear programming is a fundamental optimization technique that’s been used for decades in science- and math-intensive fields. It’s precise, relatively fast, and suitable for a range of practical applications.

Mixed-integer linear programming allows you to overcome many of the limitations of linear programming. You can approximate non-linear functions with piecewise linear functions , use semi-continuous variables , model logical constraints, and more. It’s a computationally intensive tool, but the advances in computer hardware and software make it more applicable every day.

Often, when people try to formulate and solve an optimization problem, the first question is whether they can apply linear programming or mixed-integer linear programming.

Some use cases of linear programming and mixed-integer linear programming are illustrated in the following articles:

  • Gurobi Optimization Case Studies
  • Five Areas of Application for Linear Programming Techniques

The importance of linear programming, and especially mixed-integer linear programming, has increased over time as computers have gotten more capable, algorithms have improved, and more user-friendly software solutions have become available.

The basic method for solving linear programming problems is called the simplex method , which has several variants. Another popular approach is the interior-point method .

Mixed-integer linear programming problems are solved with more complex and computationally intensive methods like the branch-and-bound method , which uses linear programming under the hood. Some variants of this method are the branch-and-cut method , which involves the use of cutting planes , and the branch-and-price method .

There are several suitable and well-known Python tools for linear programming and mixed-integer linear programming. Some of them are open source, while others are proprietary. Whether you need a free or paid tool depends on the size and complexity of your problem as well as on the need for speed and flexibility.

It’s worth mentioning that almost all widely used linear programming and mixed-integer linear programming libraries are native to and written in Fortran or C or C++. This is because linear programming requires computationally intensive work with (often large) matrices. Such libraries are called solvers . The Python tools are just wrappers around the solvers.

Python is suitable for building wrappers around native libraries because it works well with C/C++. You’re not going to need any C/C++ (or Fortran) for this tutorial, but if you want to learn more about this cool feature, then check out the following resources:

  • Building a Python C Extension Module
  • CPython Internals
  • Extending Python with C or C++

Basically, when you define and solve a model, you use Python functions or methods to call a low-level library that does the actual optimization job and returns the solution to your Python object.

Several free Python libraries are specialized to interact with linear or mixed-integer linear programming solvers:

  • SciPy Optimization and Root Finding

In this tutorial, you’ll use SciPy and PuLP to define and solve linear programming problems.

Linear Programming Examples

In this section, you’ll see two examples of linear programming problems:

  • A small problem that illustrates what linear programming is
  • A practical problem related to resource allocation that illustrates linear programming concepts in a real-world scenario

You’ll use Python to solve these two problems in the next section .

Consider the following linear programming problem:

mmst-lp-py-eq-1

You need to find x and y such that the red, blue, and yellow inequalities, as well as the inequalities x ≥ 0 and y ≥ 0, are satisfied. At the same time, your solution must correspond to the largest possible value of z .

The independent variables you need to find—in this case x and y —are called the decision variables . The function of the decision variables to be maximized or minimized—in this case z —is called the objective function , the cost function , or just the goal . The inequalities you need to satisfy are called the inequality constraints . You can also have equations among the constraints called equality constraints .

This is how you can visualize the problem:

mmst-lp-py-fig-1

The red line represents the function 2 x + y = 20, and the red area above it shows where the red inequality is not satisfied. Similarly, the blue line is the function −4 x + 5 y = 10, and the blue area is forbidden because it violates the blue inequality. The yellow line is − x + 2 y = −2, and the yellow area below it is where the yellow inequality isn’t valid.

If you disregard the red, blue, and yellow areas, only the gray area remains. Each point of the gray area satisfies all constraints and is a potential solution to the problem. This area is called the feasible region , and its points are feasible solutions . In this case, there’s an infinite number of feasible solutions.

You want to maximize z . The feasible solution that corresponds to maximal z is the optimal solution . If you were trying to minimize the objective function instead, then the optimal solution would correspond to its feasible minimum.

Note that z is linear. You can imagine it as a plane in three-dimensional space. This is why the optimal solution must be on a vertex , or corner, of the feasible region. In this case, the optimal solution is the point where the red and blue lines intersect, as you’ll see later .

Sometimes a whole edge of the feasible region, or even the entire region, can correspond to the same value of z . In that case, you have many optimal solutions.

You’re now ready to expand the problem with the additional equality constraint shown in green:

mmst-lp-py-eq-2

The equation − x + 5 y = 15, written in green, is new. It’s an equality constraint. You can visualize it by adding a corresponding green line to the previous image:

mmst-lp-py-fig-2

The solution now must satisfy the green equality, so the feasible region isn’t the entire gray area anymore. It’s the part of the green line passing through the gray area from the intersection point with the blue line to the intersection point with the red line. The latter point is the solution.

If you insert the demand that all values of x must be integers, then you’ll get a mixed-integer linear programming problem, and the set of feasible solutions will change once again:

mmst-lp-py-fig-3

You no longer have the green line, only the points along the line where the value of x is an integer. The feasible solutions are the green points on the gray background, and the optimal one in this case is nearest to the red line.

These three examples illustrate feasible linear programming problems because they have bounded feasible regions and finite solutions.

A linear programming problem is infeasible if it doesn’t have a solution. This usually happens when no solution can satisfy all constraints at once.

For example, consider what would happen if you added the constraint x + y ≤ −1. Then at least one of the decision variables ( x or y ) would have to be negative. This is in conflict with the given constraints x ≥ 0 and y ≥ 0. Such a system doesn’t have a feasible solution, so it’s called infeasible.

Another example would be adding a second equality constraint parallel to the green line. These two lines wouldn’t have a point in common, so there wouldn’t be a solution that satisfies both constraints.

A linear programming problem is unbounded if its feasible region isn’t bounded and the solution is not finite. This means that at least one of your variables isn’t constrained and can reach to positive or negative infinity, making the objective infinite as well.

For example, say you take the initial problem above and drop the red and yellow constraints. Dropping constraints out of a problem is called relaxing the problem. In such a case, x and y wouldn’t be bounded on the positive side. You’d be able to increase them toward positive infinity, yielding an infinitely large z value.

In the previous sections, you looked at an abstract linear programming problem that wasn’t tied to any real-world application. In this subsection, you’ll find a more concrete and practical optimization problem related to resource allocation in manufacturing.

Say that a factory produces four different products, and that the daily produced amount of the first product is x ₁, the amount produced of the second product is x ₂, and so on. The goal is to determine the profit-maximizing daily production amount for each product, bearing in mind the following conditions:

The profit per unit of product is $20, $12, $40, and $25 for the first, second, third, and fourth product, respectively.

Due to manpower constraints, the total number of units produced per day can’t exceed fifty.

For each unit of the first product, three units of the raw material A are consumed. Each unit of the second product requires two units of the raw material A and one unit of the raw material B. Each unit of the third product needs one unit of A and two units of B. Finally, each unit of the fourth product requires three units of B.

Due to the transportation and storage constraints, the factory can consume up to one hundred units of the raw material A and ninety units of B per day.

The mathematical model can be defined like this:

mmst-lp-py-eq-4

The objective function (profit) is defined in condition 1. The manpower constraint follows from condition 2. The constraints on the raw materials A and B can be derived from conditions 3 and 4 by summing the raw material requirements for each product.

Finally, the product amounts can’t be negative, so all decision variables must be greater than or equal to zero.

Unlike the previous example, you can’t conveniently visualize this one because it has four decision variables. However, the principles remain the same regardless of the dimensionality of the problem.

Linear Programming Python Implementation

In this tutorial, you’ll use two Python packages to solve the linear programming problem described above:

  • SciPy is a general-purpose package for scientific computing with Python.
  • PuLP is a Python linear programming API for defining problems and invoking external solvers.

SciPy is straightforward to set up. Once you install it, you’ll have everything you need to start. Its subpackage scipy.optimize can be used for both linear and nonlinear optimization .

PuLP allows you to choose solvers and formulate problems in a more natural way. The default solver used by PuLP is the COIN-OR Branch and Cut Solver (CBC) . It’s connected to the COIN-OR Linear Programming Solver (CLP) for linear relaxations and the COIN-OR Cut Generator Library (CGL) for cuts generation.

Another great open source solver is the GNU Linear Programming Kit (GLPK) . Some well-known and very powerful commercial and proprietary solutions are Gurobi , CPLEX , and XPRESS .

Besides offering flexibility when defining problems and the ability to run various solvers, PuLP is less complicated to use than alternatives like Pyomo or CVXOPT, which require more time and effort to master.

To follow this tutorial, you’ll need to install SciPy and PuLP. The examples below use version 1.4.1 of SciPy and version 2.1 of PuLP.

You can install both using pip :

You might need to run pulptest or sudo pulptest to enable the default solvers for PuLP, especially if you’re using Linux or Mac:

Optionally, you can download, install, and use GLPK. It’s free and open source and works on Windows, MacOS, and Linux. You’ll see how to use GLPK (in addition to CBC) with PuLP later in this tutorial.

On Windows, you can download the archives and run the installation files.

On MacOS, you can use Homebrew :

On Debian and Ubuntu, use apt to install glpk and glpk-utils :

On Fedora, use dnf with glpk-utils :

You might also find conda useful for installing GLPK:

After completing the installation, you can check the version of GLPK:

See GLPK’s tutorials on installing with Windows executables and Linux packages for more information.

In this section, you’ll learn how to use the SciPy optimization and root-finding library for linear programming.

To define and solve optimization problems with SciPy, you need to import scipy.optimize.linprog() :

Now that you have linprog() imported, you can start optimizing.

Let’s first solve the linear programming problem from above:

linprog() solves only minimization (not maximization) problems and doesn’t allow inequality constraints with the greater than or equal to sign (≥). To work around these issues, you need to modify your problem before starting optimization:

  • Instead of maximizing z = x + 2 y, you can minimize its negative(− z = − x − 2 y).
  • Instead of having the greater than or equal to sign, you can multiply the yellow inequality by −1 and get the opposite less than or equal to sign (≤).

After introducing these changes, you get a new system:

mmst-lp-py-eq-3

This system is equivalent to the original and will have the same solution. The only reason to apply these changes is to overcome the limitations of SciPy related to the problem formulation.

The next step is to define the input values:

You put the values from the system above into the appropriate lists, tuples , or NumPy arrays :

  • obj holds the coefficients from the objective function.
  • lhs_ineq holds the left-side coefficients from the inequality (red, blue, and yellow) constraints.
  • rhs_ineq holds the right-side coefficients from the inequality (red, blue, and yellow) constraints.
  • lhs_eq holds the left-side coefficients from the equality (green) constraint.
  • rhs_eq holds the right-side coefficients from the equality (green) constraint.

Note: Please, be careful with the order of rows and columns!

The order of the rows for the left and right sides of the constraints must be the same. Each row represents one constraint.

The order of the coefficients from the objective function and left sides of the constraints must match. Each column corresponds to a single decision variable.

The next step is to define the bounds for each variable in the same order as the coefficients. In this case, they’re both between zero and positive infinity:

This statement is redundant because linprog() takes these bounds (zero to positive infinity) by default.

Note: Instead of float("inf") , you can use math.inf , numpy.inf , or scipy.inf .

Finally, it’s time to optimize and solve your problem of interest. You can do that with linprog() :

The parameter c refers to the coefficients from the objective function. A_ub and b_ub are related to the coefficients from the left and right sides of the inequality constraints, respectively. Similarly, A_eq and b_eq refer to equality constraints. You can use bounds to provide the lower and upper bounds on the decision variables.

You can use the parameter method to define the linear programming method that you want to use. There are three options:

  • method="interior-point" selects the interior-point method. This option is set by default.
  • method="revised simplex" selects the revised two-phase simplex method.
  • method="simplex" selects the legacy two-phase simplex method.

linprog() returns a data structure with these attributes:

.con is the equality constraints residuals.

.fun is the objective function value at the optimum (if found).

.message is the status of the solution.

.nit is the number of iterations needed to finish the calculation.

.slack is the values of the slack variables, or the differences between the values of the left and right sides of the constraints.

.status is an integer between 0 and 4 that shows the status of the solution, such as 0 for when the optimal solution has been found.

.success is a Boolean that shows whether the optimal solution has been found.

.x is a NumPy array holding the optimal values of the decision variables.

You can access these values separately:

That’s how you get the results of optimization. You can also show them graphically:

mmst-lp-py-fig-5

As discussed earlier, the optimal solutions to linear programming problems lie at the vertices of the feasible regions. In this case, the feasible region is just the portion of the green line between the blue and red lines. The optimal solution is the green square that represents the point of intersection between the green and red lines.

If you want to exclude the equality (green) constraint, just drop the parameters A_eq and b_eq from the linprog() call:

The solution is different from the previous case. You can see it on the chart:

mmst-lp-py-fig-4

In this example, the optimal solution is the purple vertex of the feasible (gray) region where the red and blue constraints intersect. Other vertices, like the yellow one, have higher values for the objective function.

You can use SciPy to solve the resource allocation problem stated in the earlier section :

As in the previous example, you need to extract the necessary vectors and matrix from the problem above, pass them as the arguments to .linprog() , and get the results:

The result tells you that the maximal profit is 1900 and corresponds to x ₁ = 5 and x ₃ = 45. It’s not profitable to produce the second and fourth products under the given conditions. You can draw several interesting conclusions here:

The third product brings the largest profit per unit, so the factory will produce it the most.

The first slack is 0 , which means that the values of the left and right sides of the manpower (first) constraint are the same. The factory produces 50 units per day, and that’s its full capacity.

The second slack is 40 because the factory consumes 60 units of raw material A (15 units for the first product plus 45 for the third) out of a potential 100 units.

The third slack is 0 , which means that the factory consumes all 90 units of the raw material B. This entire amount is consumed for the third product. That’s why the factory can’t produce the second or fourth product at all and can’t produce more than 45 units of the third product. It lacks the raw material B.

opt.status is 0 and opt.success is True , indicating that the optimization problem was successfully solved with the optimal feasible solution.

SciPy’s linear programming capabilities are useful mainly for smaller problems. For larger and more complex problems, you might find other libraries more suitable for the following reasons:

SciPy can’t run various external solvers.

SciPy can’t work with integer decision variables.

SciPy doesn’t provide classes or functions that facilitate model building. You have to define arrays and matrices, which might be a tedious and error-prone task for large problems.

SciPy doesn’t allow you to define maximization problems directly. You must convert them to minimization problems.

SciPy doesn’t allow you to define constraints using the greater-than-or-equal-to sign directly. You must use the less-than-or-equal-to instead.

Fortunately, the Python ecosystem offers several alternative solutions for linear programming that are very useful for larger problems. One of them is PuLP, which you’ll see in action in the next section.

PuLP has a more convenient linear programming API than SciPy. You don’t have to mathematically modify your problem or use vectors and matrices. Everything is cleaner and less prone to errors.

As usual, you start by importing what you need:

Now that you have PuLP imported, you can solve your problems.

You’ll now solve this system with PuLP:

The first step is to initialize an instance of LpProblem to represent your model:

You use the sense parameter to choose whether to perform minimization ( LpMinimize or 1 , which is the default) or maximization ( LpMaximize or -1 ). This choice will affect the result of your problem.

Once that you have the model, you can define the decision variables as instances of the LpVariable class:

You need to provide a lower bound with lowBound=0 because the default value is negative infinity. The parameter upBound defines the upper bound, but you can omit it here because it defaults to positive infinity.

The optional parameter cat defines the category of a decision variable. If you’re working with continuous variables, then you can use the default value "Continuous" .

You can use the variables x and y to create other PuLP objects that represent linear expressions and constraints:

When you multiply a decision variable with a scalar or build a linear combination of multiple decision variables, you get an instance of pulp.LpAffineExpression that represents a linear expression.

Note: You can add or subtract variables or expressions, and you can multiply them with constants because PuLP classes implement some of the Python special methods that emulate numeric types like __add__() , __sub__() , and __mul__() . These methods are used to customize the behavior of operators like + , - , and * .

Similarly, you can combine linear expressions, variables, and scalars with the operators == , <= , or >= to get instances of pulp.LpConstraint that represent the linear constraints of your model.

Note: It’s also possible to build constraints with the rich comparison methods .__eq__() , .__le__() , and .__ge__() that define the behavior of the operators == , <= , and >= .

Having this in mind, the next step is to create the constraints and objective function as well as to assign them to your model. You don’t need to create lists or matrices. Just write Python expressions and use the += operator to append them to the model:

In the above code, you define tuples that hold the constraints and their names. LpProblem allows you to add constraints to a model by specifying them as tuples. The first element is a LpConstraint instance. The second element is a human-readable name for that constraint.

Setting the objective function is very similar:

Alternatively, you can use a shorter notation:

Now you have the objective function added and the model defined.

Note: You can append a constraint or objective to the model with the operator += because its class, LpProblem , implements the special method .__iadd__() , which is used to specify the behavior of += .

For larger problems, it’s often more convenient to use lpSum() with a list or other sequence than to repeat the + operator. For example, you could add the objective function to the model with this statement:

It produces the same result as the previous statement.

You can now see the full definition of this model:

The string representation of the model contains all relevant data: the variables, constraints, objective, and their names.

Note: String representations are built by defining the special method .__repr__() . For more details about .__repr__() , check out Pythonic OOP String Conversion: __repr__ vs __str__ or When Should You Use .__repr__() vs .__str__() in Python? .

Finally, you’re ready to solve the problem. You can do that by calling .solve() on your model object. If you want to use the default solver (CBC), then you don’t need to pass any arguments:

.solve() calls the underlying solver, modifies the model object, and returns the integer status of the solution, which will be 1 if the optimum is found. For the rest of the status codes, see LpStatus[] .

You can get the optimization results as the attributes of model . The function value() and the corresponding method .value() return the actual values of the attributes:

model.objective holds the value of the objective function, model.constraints contains the values of the slack variables, and the objects x and y have the optimal values of the decision variables. model.variables() returns a list with the decision variables:

As you can see, this list contains the exact objects that are created with the constructor of LpVariable .

The results are approximately the same as the ones you got with SciPy.

Note: Be careful with the method .solve() —it changes the state of the objects x and y !

You can see which solver was used by calling .solver :

The output informs you that the solver is CBC. You didn’t specify a solver, so PuLP called the default one.

If you want to run a different solver, then you can specify it as an argument of .solve() . For example, if you want to use GLPK and already have it installed, then you can use solver=GLPK(msg=False) in the last line. Keep in mind that you’ll also need to import it:

Now that you have GLPK imported, you can use it inside .solve() :

The msg parameter is used to display information from the solver. msg=False disables showing this information. If you want to include the information, then just omit msg or set msg=True .

Your model is defined and solved, so you can inspect the results the same way you did in the previous case:

You got practically the same result with GLPK as you did with SciPy and CBC.

Let’s peek and see which solver was used this time:

As you defined above with the highlighted statement model.solve(solver=GLPK(msg=False)) , the solver is GLPK.

You can also use PuLP to solve mixed-integer linear programming problems. To define an integer or binary variable, just pass cat="Integer" or cat="Binary" to LpVariable . Everything else remains the same:

In this example, you have one integer variable and get different results from before:

Now x is an integer, as specified in the model. (Technically it holds a float value with zero after the decimal point.) This fact changes the whole solution. Let’s show this on the graph:

mmst-lp-py-fig-6

As you can see, the optimal solution is the rightmost green point on the gray background. This is the feasible solution with the largest values of both x and y , giving it the maximal objective function value.

GLPK is capable of solving such problems as well.

Now you can use PuLP to solve the resource allocation problem from above:

The approach for defining and solving the problem is the same as in the previous example:

In this case, you use the dictionary x to store all decision variables. This approach is convenient because dictionaries can store the names or indices of decision variables as keys and the corresponding LpVariable objects as values. Lists or tuples of LpVariable instances can be useful as well.

The code above produces the following result:

As you can see, the solution is consistent with the one obtained using SciPy. The most profitable solution is to produce 5.0 units of the first product and 45.0 units of the third product per day.

Let’s make this problem more complicated and interesting. Say the factory can’t produce the first and third products in parallel due to a machinery issue. What’s the most profitable solution in this case?

Now you have another logical constraint: if x ₁ is positive, then x ₃ must be zero and vice versa. This is where binary decision variables are very useful. You’ll use two binary decision variables, y ₁ and y ₃, that’ll denote if the first or third products are generated at all:

The code is very similar to the previous example except for the highlighted lines. Here are the differences:

Line 5 defines the binary decision variables y[1] and y[3] held in the dictionary y .

Line 12 defines an arbitrarily large number M . The value 100 is large enough in this case because you can’t have more than 100 units per day.

Line 13 says that if y[1] is zero, then x[1] must be zero, else it can be any non-negative number.

Line 14 says that if y[3] is zero, then x[3] must be zero, else it can be any non-negative number.

Line 15 says that either y[1] or y[3] is zero (or both are), so either x[1] or x[3] must be zero as well.

Here’s the solution:

It turns out that the optimal approach is to exclude the first product and to produce only the third one.

Linear programming and mixed-integer linear programming are very important topics. If you want to learn more about them—and there’s much more to learn than what you saw here—then you can find plenty of resources. Here are a few to get started with:

  • Wikipedia Linear Programming Article
  • Wikipedia Integer Programming Article
  • MIT Introduction to Mathematical Programming Course
  • Brilliant.org Linear Programming Article
  • CalcWorkshop What Is Linear Programming?
  • BYJU’S Linear Programming Article

Gurobi Optimization is a company that offers a very fast commercial solver with a Python API. It also provides valuable resources on linear programming and mixed-integer linear programming, including the following:

  • Linear Programming (LP) – A Primer on the Basics
  • Mixed-Integer Programming (MIP) – A Primer on the Basics
  • Choosing a Math Programming Solver

If you’re in the mood to learn optimization theory, then there’s plenty of math books out there. Here are a few popular choices:

  • Linear Programming: Foundations and Extensions
  • Convex Optimization
  • Model Building in Mathematical Programming
  • Engineering Optimization: Theory and Practice

This is just a part of what’s available. Linear programming and mixed-integer linear programming are popular and widely used techniques, so you can find countless resources to help deepen your understanding.

Just like there are many resources to help you learn linear programming and mixed-integer linear programming, there’s also a wide range of solvers that have Python wrappers available. Here’s a partial list:

  • SCIP with PySCIPOpt
  • Gurobi Optimizer

Some of these libraries, like Gurobi, include their own Python wrappers. Others use external wrappers. For example, you saw that you can access CBC and GLPK with PuLP.

You now know what linear programming is and how to use Python to solve linear programming problems. You also learned that Python linear programming libraries are just wrappers around native solvers. When the solver finishes its job, the wrapper returns the solution status, the decision variable values, the slack variables, the objective function, and so on.

In this tutorial, you learned how to:

  • Define a model that represents your problem
  • Create a Python program for optimization
  • Run the optimization program to find the solution to the problem
  • Retrieve the result of optimization

You used SciPy with its own solver as well as PuLP with CBC and GLPK, but you also learned that there are many other linear programming solvers and Python wrappers. You’re now ready to dive into the world of linear programming!

If you have any questions or comments, then please put them in the comments section below.

🐍 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 Mirko Stojiljković

Mirko Stojiljković

Mirko has a Ph.D. in Mechanical Engineering and works as a university professor. He is a Pythonista who applies hybrid optimization and machine learning methods to support decision making in the energy sector.

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 data-science

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 Logo

5 Thoughts On Python Mastery

🔒 No spam. We take your privacy seriously.

learn problem solving with python

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

learn problem solving with python

  • Runestone in social media: Follow @iRunestone Our Facebook Page
  • Table of Contents
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • This Chapter
  • 1. Introduction' data-toggle="tooltip" >

Problem Solving with Algorithms and Data Structures using Python ¶

PythonDS Cover

By Brad Miller and David Ranum, Luther College

There is a wonderful collection of YouTube videos recorded by Gerry Jenkins to support all of the chapters in this text.

  • 1.1. Objectives
  • 1.2. Getting Started
  • 1.3. What Is Computer Science?
  • 1.4. What Is Programming?
  • 1.5. Why Study Data Structures and Abstract Data Types?
  • 1.6. Why Study Algorithms?
  • 1.7. Review of Basic Python
  • 1.8.1. Built-in Atomic Data Types
  • 1.8.2. Built-in Collection Data Types
  • 1.9.1. String Formatting
  • 1.10. Control Structures
  • 1.11. Exception Handling
  • 1.12. Defining Functions
  • 1.13.1. A Fraction Class
  • 1.13.2. Inheritance: Logic Gates and Circuits
  • 1.14. Summary
  • 1.15. Key Terms
  • 1.16. Discussion Questions
  • 1.17. Programming Exercises
  • 2.1.1. A Basic implementation of the MSDie class
  • 2.2. Making your Class Comparable
  • 3.1. Objectives
  • 3.2. What Is Algorithm Analysis?
  • 3.3. Big-O Notation
  • 3.4.1. Solution 1: Checking Off
  • 3.4.2. Solution 2: Sort and Compare
  • 3.4.3. Solution 3: Brute Force
  • 3.4.4. Solution 4: Count and Compare
  • 3.5. Performance of Python Data Structures
  • 3.7. Dictionaries
  • 3.8. Summary
  • 3.9. Key Terms
  • 3.10. Discussion Questions
  • 3.11. Programming Exercises
  • 4.1. Objectives
  • 4.2. What Are Linear Structures?
  • 4.3. What is a Stack?
  • 4.4. The Stack Abstract Data Type
  • 4.5. Implementing a Stack in Python
  • 4.6. Simple Balanced Parentheses
  • 4.7. Balanced Symbols (A General Case)
  • 4.8. Converting Decimal Numbers to Binary Numbers
  • 4.9.1. Conversion of Infix Expressions to Prefix and Postfix
  • 4.9.2. General Infix-to-Postfix Conversion
  • 4.9.3. Postfix Evaluation
  • 4.10. What Is a Queue?
  • 4.11. The Queue Abstract Data Type
  • 4.12. Implementing a Queue in Python
  • 4.13. Simulation: Hot Potato
  • 4.14.1. Main Simulation Steps
  • 4.14.2. Python Implementation
  • 4.14.3. Discussion
  • 4.15. What Is a Deque?
  • 4.16. The Deque Abstract Data Type
  • 4.17. Implementing a Deque in Python
  • 4.18. Palindrome-Checker
  • 4.19. Lists
  • 4.20. The Unordered List Abstract Data Type
  • 4.21.1. The Node Class
  • 4.21.2. The Unordered List Class
  • 4.22. The Ordered List Abstract Data Type
  • 4.23.1. Analysis of Linked Lists
  • 4.24. Summary
  • 4.25. Key Terms
  • 4.26. Discussion Questions
  • 4.27. Programming Exercises
  • 5.1. Objectives
  • 5.2. What Is Recursion?
  • 5.3. Calculating the Sum of a List of Numbers
  • 5.4. The Three Laws of Recursion
  • 5.5. Converting an Integer to a String in Any Base
  • 5.6. Stack Frames: Implementing Recursion
  • 5.7. Introduction: Visualizing Recursion
  • 5.8. Sierpinski Triangle
  • 5.9. Complex Recursive Problems
  • 5.10. Tower of Hanoi
  • 5.11. Exploring a Maze
  • 5.12. Dynamic Programming
  • 5.13. Summary
  • 5.14. Key Terms
  • 5.15. Discussion Questions
  • 5.16. Glossary
  • 5.17. Programming Exercises
  • 6.1. Objectives
  • 6.2. Searching
  • 6.3.1. Analysis of Sequential Search
  • 6.4.1. Analysis of Binary Search
  • 6.5.1. Hash Functions
  • 6.5.2. Collision Resolution
  • 6.5.3. Implementing the Map Abstract Data Type
  • 6.5.4. Analysis of Hashing
  • 6.6. Sorting
  • 6.7. The Bubble Sort
  • 6.8. The Selection Sort
  • 6.9. The Insertion Sort
  • 6.10. The Shell Sort
  • 6.11. The Merge Sort
  • 6.12. The Quick Sort
  • 6.13. Summary
  • 6.14. Key Terms
  • 6.15. Discussion Questions
  • 6.16. Programming Exercises
  • 7.1. Objectives
  • 7.2. Examples of Trees
  • 7.3. Vocabulary and Definitions
  • 7.4. List of Lists Representation
  • 7.5. Nodes and References
  • 7.6. Parse Tree
  • 7.7. Tree Traversals
  • 7.8. Priority Queues with Binary Heaps
  • 7.9. Binary Heap Operations
  • 7.10.1. The Structure Property
  • 7.10.2. The Heap Order Property
  • 7.10.3. Heap Operations
  • 7.11. Binary Search Trees
  • 7.12. Search Tree Operations
  • 7.13. Search Tree Implementation
  • 7.14. Search Tree Analysis
  • 7.15. Balanced Binary Search Trees
  • 7.16. AVL Tree Performance
  • 7.17. AVL Tree Implementation
  • 7.18. Summary of Map ADT Implementations
  • 7.19. Summary
  • 7.20. Key Terms
  • 7.21. Discussion Questions
  • 7.22. Programming Exercises
  • 8.1. Objectives
  • 8.2. Vocabulary and Definitions
  • 8.3. The Graph Abstract Data Type
  • 8.4. An Adjacency Matrix
  • 8.5. An Adjacency List
  • 8.6. Implementation
  • 8.7. The Word Ladder Problem
  • 8.8. Building the Word Ladder Graph
  • 8.9. Implementing Breadth First Search
  • 8.10. Breadth First Search Analysis
  • 8.11. The Knight’s Tour Problem
  • 8.12. Building the Knight’s Tour Graph
  • 8.13. Implementing Knight’s Tour
  • 8.14. Knight’s Tour Analysis
  • 8.15. General Depth First Search
  • 8.16. Depth First Search Analysis
  • 8.17. Topological Sorting
  • 8.18. Strongly Connected Components
  • 8.19. Shortest Path Problems
  • 8.20. Dijkstra’s Algorithm
  • 8.21. Analysis of Dijkstra’s Algorithm
  • 8.22. Prim’s Spanning Tree Algorithm
  • 8.23. Summary
  • 8.24. Key Terms
  • 8.25. Discussion Questions
  • 8.26. Programming Exercises

Acknowledgements ¶

We are very grateful to Franklin Beedle Publishers for allowing us to make this interactive textbook freely available. This online version is dedicated to the memory of our first editor, Jim Leisy, who wanted us to “change the world.”

Indices and tables ¶

Search Page

Creative Commons License

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

Python Projects

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

Python Exercise with Practice Questions and Solutions

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

Python Matrix Exercises

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

Python Functions Exercises

  • Python splitfields() Method
  • How to get list of parameters name from a function in Python?
  • How to Print Multiple Arguments in Python?
  • Python program to find the power of a number using recursion
  • Sorting objects of user defined class in Python
  • Assign Function to a Variable in Python
  • Returning a function from a function - Python
  • What are the allowed characters in Python function names?
  • Defining a Python function at runtime
  • Explicitly define datatype in a Python function
  • Functions that accept variable length key value pair as arguments
  • How to find the number of arguments in a Python function?
  • How to check if a Python variable exists?
  • Python - Get Function Signature
  • Python program to convert any base to decimal by using int() method

Python Lambda Exercises

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

Python Pattern printing Exercises

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

Python DateTime Exercises

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

Python OOPS Exercises

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

Python Regex Exercises

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

Python LinkedList Exercises

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

Python Searching Exercises

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

Python Sorting Exercises

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

Python DSA Exercises

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

Python File Handling Exercises

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

Python CSV Exercises

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

Python JSON Exercises

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

Python OS Module Exercises

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

Python Tkinter Exercises

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

Python Web Scraping Exercises

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

Python Selenium Exercises

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

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

Python is a widely used general-purpose high-level language that can be used for many purposes like creating GUI, web Scraping, web development, etc. You might have seen various Python tutorials that explain the concepts in detail but that might not be enough to get hold of this language. The best way to learn is by practising it more and more.

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

learn problem solving with python

List of Python Programming Exercises

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

Python List Exercises

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

>> More Programs on List

Python String Exercises

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

>> More Programs on String

Python Tuple Exercises

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

>> More Programs on Tuple

Python Dictionary Exercises

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

>> More Programs on Dictionary

Python Set Exercises

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

>> More Programs on Sets

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

>> More Programs on Matrices

>> More Programs on Functions

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

>> More Programs on Lambda

  • Programs for printing pyramid patterns in Python

>> More Programs on Python Pattern Printing

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

>> More Programs on DateTime

>> More Programs on Python OOPS

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

>> More Programs on Python Regex

>> More Programs on Linked Lists

>> More Programs on Python Searching

  • Python Program for Bubble Sort
  • Python Program for QuickSort
  • Python Program for Insertion Sort
  • Python Program for Selection Sort
  • Python Program for Heap Sort

>> More Programs on Python Sorting

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

>> More Programs on Python DSA

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

>> More Programs on Python File Handling

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

>> More Programs on Python CSV

>> More Programs on Python JSON

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

>> More Programs on OS Module

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

>> More Programs on Python Tkinter

NumPy Exercises

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

>> More Programs on NumPy

Pandas Exercises

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

>> More Programs on Python Pandas

>> More Programs on Web Scraping

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

>> More Programs on Python Selenium

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

>> More Projects in Python

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

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Python Programming

Python Basic Exercise for Beginners

Updated on:  August 31, 2023 | 492 Comments

This Python essential exercise is to help Python beginners to 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 certain to elevate your understanding of Python.

Also, See :

  • Python Quizzes : Solve quizzes to check 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 programs to solve. The hint and solution is provided for each question.
  • I have added tips and required learning resources for each question, which will help you solve the exercise. When you complete each question, you get more familiar with the basics of Python.

Use Online Code Editor to solve exercise questions.

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, 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 the current number and the previous number

Write a program 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 assign it to 0
  • Iterate the first 10 numbers one by one using for loop and range() function
  • Next, display the current number ( i ), previous number, and the addition of both numbers in each iteration of the loop. Finally, change the value of the previous number to the current number ( previous_num = i ).

Exercise 3: Print characters from a string that are present at an even index number

Write a program to accept a string from the user and display characters that are present at an even index number.

For example, str = "pynative" so you 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 each character of a string using for 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 program to remove characters from a string starting from zero up to n and return a new string.

For example:

  • remove_chars("pynative", 4) so output must be tive . Here, we need to remove the first four characters from a string.
  • remove_chars("pynative", 2) so output must be native . Here, we 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 the substring. For example, to remove the first four characters and the remaining use s[4:] .

Also, try to solve  Python String Exercise

Exercise 5: Check if the first and last number of a list is the same

Write a function to return True if the first and last number of a given list is same. If numbers are different then return False .

Exercise 6: Display numbers divisible by 5 from a list

Iterate the given list of numbers and print only those numbers which are divisible by 5

Also, try to solve  Python list Exercise

Exercise 7: Return the count of a given substring from a string

Write a program to find how many times substring “ Emma ” appears in the given string.

Use string method count() .

Solution 1 : Use the count() method

Solution 2 : Without string method

Exercise 8: Print the following pattern

Hint : Print Pattern using for loop

Exercise 9: Check Palindrome Number

Write a program to check if the given number is a palindrome number.

A palindrome number is a number that is the same after reverse. For example, 545, is the palindrome numbers

  • 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: Create a new list from two list using the following condition

Create a new list from two list using the following condition

Given two list of numbers, write a program to create a new list such that the new 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 number using num % 2 != 0 formula. If the current number is an odd number, add it to the result list
  • Now, Iterate the first list using a loop.
  • In each iteration, check if the current number is odd number using num % 2 == 0 formula. If the current number is an even number, add it to the result list
  • Print the result list

Note: Try to solve the Python list Exercise

Exercise 11: Write a Program to extract each digit from an integer in the reverse order.

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

Use while loop

Exercise 12: 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 taxable 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 two use nested loops in Python

  • Create the outer for loop to iterate numbers from 1 to 10. So, the total number of iterations of the outer loop is 10.
  • Create an inner loop to iterate 10 times.
  • For each outer loop iteration, the inner loop will execute ten times.
  • In the first iteration of the nested loop, the number is 1. In the next, it 2. and so on till 10.
  • In each iteration of an inner loop, we calculated the multiplication of two numbers. (current outer number and current inner number)

Exercise 14: Print a downward Half-Pyramid Pattern of Star (asterisk)

Exercise 15: 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 basic 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 solve 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

learn problem solving with python

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

The-Most-Important-Soft-Skill-for-Developers-—-How-to-Get-Better-at-It.webp

The Most Important Soft Skill for Developers & How to Get Better at It

Cory-Stieg-Headshot-e1697134432604.webp?w=338

  • Share article on Twitter
  • Share article on Facebook
  • Share article on LinkedIn

At its core, programming is just solving problems so a computer can execute a task. Or, as one of our engineers Nick Duckwiler aptly put it: “A lot of engineering is just solving headaches.” Indeed, between fixing bugs and dreaming up app ideas that can address real world difficulties, devs need to be enthusiastic about solving problems of all sizes.   

On top of all the technical knowledge that’s required for engineering roles, you also should work on soft skills, which are personal attributes that enable you to work well with others. Problem solving is one of the most essential soft skills to have in technical positions , and luckily, there are plenty of ways to get better at tackling challenges and finding solutions.

Next month, we’re hosting an exclusive three-part livestream series all about developing core soft skills: problem solving, planning, setting priorities, and critical thinking. The events will be led by Merri Lemmex, a management and leadership expert who has decades of experience training people who work in tech and business. The first session on November 1 is focused on problem solving approaches and tools. Be sure to register today for the virtual events and read on to learn more about the problem-solving strategies that developers use in their work.

Learn something new for free

Intro to chatgpt, write out the problem.

Your problem won’t always come right out and say: “It’s me, hi. I’m the problem , it’s me.” In fact, something that often gets in the way of solving a problem is that we zero in on the wrong problem.

When pinpointing a problem, you can try borrowing a UX research technique that’s part of the design thinking process. After you’ve done some initial research or information gathering, you delineate your problem space and write a problem statement, which is a concise couple of sentences that succinctly define the task and offer a clear sense of direction. Write out the who, what, where, when, and why of your problem.

Getting to the core of your fundamental issue will make addressing the symptoms much easier. You can learn more about this strategy in our free course Learn Design Thinking: Ideation .

Don’t try to solve it alone

Rather than spinning your wheels trying to fix a problem on your own, consider having other people weigh in. Set up a brainstorming session for the problem you’re trying to solve, see if anyone can pair program with you, or send a Slack message to your team and see what your collective intelligence can accomplish.

It’s easy to get tunnel vision when you’re working on a project and become fixated on one part of it. Getting more people involved in the problem-solving process will enable you to address blind spots, consider fresh perspectives, and ultimately get valuable feedback and validation for your idea. Not to mention, you’ll get experience collaborating with other people, which is a soft skill in and of itself.

Say it out loud

Ever seen a rubber duck on a programmer’s desk and wondered what it’s doing there? There’s a popular debugging technique called “ rubberducking ,” where you describe out loud what your code is supposed to do to the duck. As you verbally articulate your code and thoughts to the silent, non-judgmental duck, you may identify issues or problems that you skipped over before. Though you might have to work up the courage to talk to an inanimate object at your desk, you’ll be surprised how effective and practical rubberducking can be when it comes to pinpointing a problem.

See how other people approached the problem

Remember: You’re probably not the first person to have experienced this problem. There’s a plethora of resources that developers use to ask questions, get feedback, or crowd-source solutions for bugs. Go to Stack Overflow and see if someone else has experienced your issue and created a workaround. Or look through Docs , our open-contribution code documentation for popular languages, to see if you can find a solution. (Better yet, once you figure your issue out, you could take what you learned and contribute a Doc for folks to reference in the future.)

Learn problem-solving skills in our new course

Join us next month for an engaging three-part livestream series dedicated to honing essential soft skills, including problem solving, strategic planning, priority setting, and critical thinking. These skills are your secret sauce for nailing your next job interview, making an impression on your team leader, or feeling confident at a networking event. By the end of the livestream series, you’ll have a soft skills toolkit that you can continue to refine throughout your whole career.

Our first session on November 1 delves into effective problem-solving techniques and tools. Secure your spot for these virtual events today. Quick note: These are only available to Codecademy Pro and Codecademy Plus members, so make sure you upgrade your account or start a free seven-day trial to attend.

Related courses

Learn to code with blockly, choosing a programming language, choosing a career in tech, subscribe for news, tips, and more, related articles.

Header-Image_2083x875-14.png?w=1024

What Does a Technical Writer Do?

And how important is it to be technical, or a good writer?

TipsForApplyingToJobsInTechIfYoureReallyBusy_Thumbnail.png?w=1024

8 Tips For Applying To Jobs In Tech If You’re Really Busy

Use these tips to help you apply to jobs ​​in tech when you don’t have a lot of time to dedicate to your search.

050224_learner_stories_illustrations_F_Header_image_John-King.webp?w=1024

I Have 20 Years of Web Architect Experience — Here’s What I’m Learning Next

Today’s story is from John King, a 60-year-old Web Architect, living in Austin, Texas.

Header-Image_2083x875-12.png?w=1024

What is the Waterfall Model?

T​​he waterfall model follows a linear sequential flow where each phase of development is completed and approved before the next begins. Here’s how it works.

what-is-html.png?w=1024

What is HTML? Common Uses & Defining Features

HTML lies at the heart of web development and forms the structure of our favorite websites.

Pride-Day_R1_Blog2.webp?w=1024

10 Python Code Challenges to Try During Pride

Celebrate Pride with these bite-sized Python coding challenges.

Tech-Organizations-that-Support-the-LGBTQ-Community.webp?w=1024

9 Tech Organizations that Support the LGBTQ+ Community

Get involved with these organizations during Pride Month and beyond.

IMAGES

  1. Problem Solving using Python

    learn problem solving with python

  2. learn problem solving with python

    learn problem solving with python

  3. Python Problem Solving Course (Beginners)

    learn problem solving with python

  4. Python For Beginners

    learn problem solving with python

  5. Best Python Real Life Problem Solving Project #Python

    learn problem solving with python

  6. Complete Python with Problem Solving

    learn problem solving with python

VIDEO

  1. File Handling and Dictionaries

  2. Problem Solving Using Python Programming

  3. problem solving python #python #problem #solving

  4. The Process of Computational problem solving

  5. Solving Summation problem with python #python #calculus #maths

  6. Problem solving & python programming important questions from AU question papers

COMMENTS

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

  2. Python Exercises, Practice, Challenges

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

  3. Python Basics: Problem Solving with Code

    This course is part of the Python Basics for Online Research Specialization. When you enroll in this course, you'll also be enrolled in this Specialization. Learn new concepts from industry experts. Gain a foundational understanding of a subject or tool. Develop job-relevant skills with hands-on projects.

  4. Solve Python

    Classes. Built-Ins. Python Functionals. Regex and Parsing. XML. Closures and Decorators. Numpy. Debugging. Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  5. 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 (3347 reviews) 18 lessons Beginner level. 42.6k Learners.

  6. Python Tutorials

    Python Tutorials → In-depth articles and video courses Learning Paths → Guided study plans for accelerated learning Quizzes → Check your learning progress Browse Topics → Focus on a specific area or skill level Community Chat → Learn with other Pythonistas Office Hours → Live Q&A calls with Python experts Podcast → Hear what's new in the world of Python Books →

  7. Problem Solving, Python Programming, and Video Games

    This course is an introduction to computer science and programming in Python. Upon successful completion of this course, you will be able to: 1. Take a new computational problem and solve it, using several problem solving techniques including abstraction and problem decomposition. 2. Follow a design creation process that includes: descriptions ...

  8. Mastering Algorithms for Problem Solving in Python

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

  9. Learn Python Programming

    On the other hand, Python's clear, English-like syntax allows you to concentrate on problem-solving and building logic without being concerned about unnecessary complexities. ... If you want to learn Python for free with a well-organized, step-by-step tutorial, you can use our free Python tutorials.

  10. Python Programming Bootcamp: Learn Python Through Problem Solving

    Learn how to Solve Real Programming Problems with a Focus on Teaching Problem Solving Skills. Understand Python as an Object Oriented and Functional Programming Language. Create GUI Applications using TkInter, Kivy and soon PyQt. Create Applications that Utilize Databases. We will Expand into Algorithms, Django, Flask and Machine Learning.

  11. Introduction to Programming with Python

    Introduction to Programming with Python. A first course in computer programming using the Python programming language. This course covers basic programming concepts such as variables, data types, iteration, flow of control, input/output, and functions. 12 lessons. Diagnostics.

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

    Python Exercises. Learn by doing. Exercises will help you to understand the topic deeply. Exercise for each tutorial topic so you can practice and improve your Python skills. Exercises cover Python basics to data structures and other advanced topics. Each Exercise contains ten questions to solve. Practice each Exercise using Code Editor.

  13. Python courses

    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. ... Beginner DSA in Python Beginner. Now that you have learnt how to approach a problem in Python, let us learn more about basic topics like Arrays, String and Maths. This will ...

  14. Computational Thinking for Problem Solving

    Computational thinking is a problem-solving process in which the last step is expressing the solution so that it can be executed on a computer. However, before we are able to write a program to implement an algorithm, we must understand what the computer is capable of doing -- in particular, how it executes instructions and how it uses data.

  15. Learn Python By Solving 100+ Challenges

    This course is for Python beginners that want to learn with hands on problems rather than long theory classes. People that maybe know the Python basics but lack the problem solving skills.(all theory required to solve the problems will be in lessons) Show more Show less. Instructor. Anton Cristian.

  16. 10 Python Practice Exercises for Beginners with Solutions

    In this article, we give you 10 Python practice exercises to boost your skills. Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types.

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

    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.

  18. Introduction to Data Science with Python

    Data scientists use a range of programming languages, such as Python and R, to harness and analyze data. This course focuses on using Python in data science. By the end of the course, you'll have a fundamental understanding of machine learning models and basic concepts around Machine Learning (ML) and Artificial Intelligence (AI).

  19. Introduction

    Welcome to the world of problem solving with Python! This first Orientation chapter will help you get started by guiding you through the process of installing Python on your computer. By the end of this chapter, you will be able to: Describe why Python is a useful computer language for problem solvers. Describe applications where Python is used.

  20. Hands-On Linear Programming: Optimization With Python

    In this section, you'll learn how to use the SciPy optimization and root-finding library for linear programming. To define and solve optimization problems with SciPy, you need to import scipy.optimize.linprog(): Python. >>> from scipy.optimize import linprog.

  21. Practice Python

    Solve Python coding problems online with Practice Python on CodeChef. Write code for over 195 Python coding exercises and boost your confidence in programming. ... CodeChef Learn Problem Solving: 287: Multiple Choice Question: NA: Learning SQL: 339: Multiple Choice Question: NA: Parking Charges: 416: 6.

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

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

  23. Online Python 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. Practice your Python skills with online programming challenges.

  24. Problem Solving with Algorithms and Data Structures using Python

    Problem Solving with Algorithms and Data Structures using Python¶. By Brad Miller and David Ranum, Luther College. Assignments; There is a wonderful collection of YouTube videos recorded by Gerry Jenkins to support all of the chapters in this text.

  25. Python Exercise with Practice Questions and Solutions

    The best way to learn is by practising it more and more. The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains.

  26. Python Basic Exercise for Beginners with Solutions

    Also, try to solve Python list Exercise. Exercise 7: Return the count of a given substring from a string. Write a program to find how many times substring "Emma" appears in the given string. Given: str_x = "Emma is good developer. Emma is a writer" Code language: Python (python) Expected Output: Emma appeared 2 times

  27. Problem-Solving Strategies for Software Engineers

    Learn effective problem-solving strategies to use in programming and software engineering. Plus, a live soft skills series for Codecademy Pro and Plus learners. ... 10 Python Code Challenges to Try During Pride. 06/03/2024. 4 minutes. By Cory Stieg. Celebrate Pride with these bite-sized Python coding challenges.

  28. Get started with SQLite3 in Python Creating Tables & Fetching Rows

    Additionally, the Python library sqlite3 is a simple interface for interacting with SQLite. In this blog post, we will use SQLite and the sqlite3 library to learn two major concepts: Some elementary ways of using the most basic and useful commands of SQL such as CREATE TABLE, INSERT INTO, and SELECT — FROM.

  29. Solving the "Missing Data" Problem in Python: A Practical Guide

    Reduced accuracy: Missing values can decrease the precision of machine learning models. Increased uncertainty: Incomplete data can make it difficult to draw meaningful insights. The Solution. Fortunately, Python provides a range of libraries and techniques to tackle the missing data problem. We'll explore three approaches: 1. Mean/Median ...

  30. What Is Python Used For? A Beginner's Guide

    Here's a closer look at some of these common ways Python is used. Data analysis and machine learning. Python has become a staple in data science, allowing data analysts and other professionals to use the language to conduct complex statistical calculations, create data visualizations, build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks.