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

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

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

Python Practice for Beginners: 15 Hands-On Problems

Author's photo

  • online practice

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

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

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

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

Python Practice Problem 1: Average Expenses for Each Semester

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

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

Explanation

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

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

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

Python Practice Problem 2: Who Spent More?

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

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

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

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

Python Practice Problem 3: All of Our Friends

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

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

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

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

Python Practice Problem 4: Find the Common Friends

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

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

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

Python Practice Problem 5: Find the Basketball Players

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

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

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

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

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

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

Python Practice Problem 6: Count the Votes

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

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

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

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

Python Practice Problem 7: Sum the Scores

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

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

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

Python Practice Problem 8: Calculate the Statistics

Given any list of numbers in Python, such as …

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

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

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

Python Practice Problem 9: Longest and Shortest Words

Given the list of words below ..

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

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

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

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

Python Practice Problem 10: Filter a List by Frequency

Given a list of numbers …

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

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

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

Python Practice Problem 11: The Second-Best Score

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

Find the second-highest score in the list.

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

Python Practice Problem 12: Check If a List Is Symmetrical

Given the lists of numbers below …

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

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

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

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

Python Practice Problem 13: Sort By Number of Vowels

Given this list of strings …

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

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

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

Python Practice Problem 14: Sorting a Mixed List

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

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

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

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

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

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

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

Python Practice Problem 15: Filter and Reorder

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

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

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

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

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

Want Even More Python Practice Problems?

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

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

You may also like

problem solving python programming

How Do You Write a SELECT Statement in SQL?

problem solving python programming

What Is a Foreign Key in SQL?

problem solving python programming

Enumerate and Explain All the Basic Elements of an SQL Query

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

problem solving python programming

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.

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Top Courses
  • Online Degrees
  • Find your New Career
  • Join for Free

University of Pennsylvania

Introduction to Python Programming

This course is part of Introduction to Programming with Python and Java Specialization

Taught in English

Some content may not be translated

Brandon Krakowsky

Instructor: Brandon Krakowsky

Financial aid available

76,484 already enrolled

Coursera Plus

(1,051 reviews)

Recommended experience

Beginner level

High school or college math.

Minimal prior programming exposure may be helpful but not needed (e.g. Computational Thinking for Problem Solving ).

What you'll learn

Identify core aspects of programming and features of the Python language

Understand and apply core programming concepts like data structures, conditionals, loops, variables, and functions

Use different tools for writing and running Python code

Design and write fully-functional Python programs using commonly used data structures, custom functions, and reading and writing to files

Skills you'll gain

  • Programming Principles
  • Python Syntax And Semantics
  • Computer Programming
  • Python Programming
  • Python Tools

Details to know

problem solving python programming

Add to your LinkedIn profile

See how employees at top companies are mastering in-demand skills

Placeholder

Build your subject-matter expertise

  • Learn new concepts from industry experts
  • Gain a foundational understanding of a subject or tool
  • Develop job-relevant skills with hands-on projects
  • Earn a shareable career certificate

Placeholder

Earn a career certificate

Add this credential to your LinkedIn profile, resume, or CV

Share it on social media and in your performance review

Placeholder

There are 4 modules in this course

This course provides an introduction to programming and the Python language. Students are introduced to core programming concepts like data structures, conditionals, loops, variables, and functions. This course includes an overview of the various tools available for writing and running Python, and gets students coding quickly. It also provides hands-on coding exercises using commonly used data structures, writing custom functions, and reading and writing to files. This course may be more robust than some other introductory python courses, as it delves deeper into certain essential programming topics.

Module 1 : Course Introduction, Intro to Programming and The Python Language, Variables, Conditionals, Jupyter Notebook, and IDLE

This first module covers an intro to programming and the Python language. We’ll start by downloading and installing the necessary tools to begin programming and writing code in Python. After learning how to print to the console, we’ll get an understanding of Python’s basic data types, and how to do simple math. We’ll follow up by creating our first Python script, and learn how to define and assign variables, while controlling the flow of our program using conditionals. We’ll also learn how to get input from the user, including some very basic error checking. Let’s get started!

What's included

42 videos 10 readings 3 quizzes 2 programming assignments

42 videos • Total 78 minutes

  • About the Instructor : Brandon Krakowsky • 1 minute • Preview module
  • What you should expect from this Course • 1 minute
  • Why begin with Python? • 0 minutes
  • Module Intro • 0 minutes
  • What is Programming? • 0 minutes
  • Client-side vs. server-side programming • 0 minutes
  • Introduction to core programming concepts: Data structures, Conditionals, Variables, Functions, and Loops • 1 minute
  • What is Python? • 0 minutes
  • Python is interpreted • 0 minutes
  • Why Python? • 0 minutes
  • Downloading & installing Python • 0 minutes
  • Downloading & Installing Jupyter Notebook • 0 minutes
  • Using Jupyter Notebook • 3 minutes
  • How do I write Python? • 0 minutes
  • Printing • 2 minutes
  • Basic Data Types • 2 minutes
  • Arithmetic operators • 1 minute
  • About division • 1 minute
  • Boolean values • 1 minute
  • Comparison operators • 0 minutes
  • Code Along Exercise : Even/Odd • 0 minutes
  • Strings • 2 minutes
  • Casting • 3 minutes
  • How to use Coursera Labs & understand Autograder output • 9 minutes
  • Downloading & installing IDLE • 0 minutes
  • Using the IDLE shell • 1 minute
  • Running a Python script • 1 minute
  • Adding comments to Python scripts • 1 minute
  • Code Along Exercise : Comment the program to greet user • 1 minute
  • Assigning a variable • 0 minutes
  • Boolean operators • 1 minute
  • Variable substitution • 2 minutes
  • Combining variables • 1 minute
  • Code Along Exercise : Cats & dogs • 1 minute
  • Getting user input • 3 minutes
  • Code Along Exercise : Calculate total bill • 6 minutes
  • The if … elif … else statement • 2 minutes
  • Code Along Exercise : Numerical grade to letter grade • 2 minutes
  • Multiple if conditionals • 1 minute
  • Checking user input • 1 minute
  • Coding Demonstration : Common Python Errors • 6 minutes
  • Coding Demonstration : Creating a function to convert numerical grade to letter grade • 3 minutes

10 readings • Total 100 minutes

  • Course Layout & Syllabus • 15 minutes
  • Tips to succeed in this course • 10 minutes
  • Module 1 Resources (DOWNLOAD RELEVANT CODE AND/OR DATA FILES FOR THIS MODULE HERE) • 30 minutes
  • Python - Getting Help • 2 minutes
  • Quick Intro to Variables • 5 minutes
  • Homework 1a : Instructions • 10 minutes
  • What is a Python script? • 3 minutes
  • Python Errors • 10 minutes
  • Reading : Quick Intro to Functions • 5 minutes
  • Homework 1b : Instructions • 10 minutes

3 quizzes • Total 60 minutes

  • Quiz 1 - Intro to Python & The Python Language • 10 minutes
  • Quiz 2 - Variables & Conditionals • 20 minutes
  • Practice Quiz - Variables & data types • 30 minutes

2 programming assignments • Total 270 minutes

  • Homework 1a - Math Practice • 120 minutes
  • Homework 1b - Practice Writing Python & Calculating How Old Your Dog is in Human Years • 150 minutes

Module 2 : Intro to Lists, Loops, and Functions

We’ll start this module with a brief intro to lists, one of Python’s most commonly used data structures. We’ll learn just enough to get us started with loops, which are used to repeat a process or run a block of code multiple times. We’ll get into functions, which are blocks of organized code used to perform a single, related action. We’ll review some of Python’s built-in functions and learn how to design our own user-defined functions to use as building blocks in our own programs. Along the way, we’ll learn best practices for documenting our code for 2 different audiences: The users who are using our code and want to understand it at a high level, and the programmers who are reading it and want to know how it works.

31 videos 2 readings 3 quizzes 1 programming assignment

31 videos • Total 56 minutes

  • Module Introduction • 1 minute • Preview module
  • Creating a list • 0 minutes
  • Updating a list • 1 minute
  • Types of Loops • 0 minutes
  • Executing code a given number of times • 1 minute
  • Iterating over a list • 3 minutes
  • Code Along Exercise : Find minimum value • 2 minutes
  • Iterating over strings • 1 minute
  • Iterate over a string • 1 minute
  • Code Along Exercise : Iterate over a name • 1 minute
  • 'for' loops using range • 4 minutes
  • Repeatedly executing code based on a condition • 1 minute
  • Waiting for user input • 0 minutes
  • Code Along Exercise : Secret password • 1 minute
  • Exiting a loop using break • 1 minute
  • Exiting a loop using continue • 1 minute
  • Nested loops • 1 minute
  • Code Along Exercise : Multiplication tables • 1 minute
  • Coding Demonstration : Average program • 4 minutes
  • Coding Demonstration : Word reversal • 1 minute
  • What is a function? • 0 minutes
  • Built-in functions • 0 minutes
  • User-defined functions • 0 minutes
  • Code Along Exercise : Square • 0 minutes
  • Code Along Exercise : Greater than • 1 minute
  • Docstrings (Documentation Strings) • 0 minutes
  • Code Along Exercise : Get factors • 2 minutes
  • Code Along Exercise : Unique list • 2 minutes
  • Execution order • 0 minutes
  • The main function • 0 minutes
  • Coding Demonstration : Vowel/word counter • 9 minutes

2 readings • Total 40 minutes

  • Module 2 Resources (DOWNLOAD RELEVANT CODE AND/OR DATA FILES FOR THIS MODULE HERE) • 30 minutes
  • Homework 2 : Instructions • 10 minutes

3 quizzes • Total 58 minutes

  • Quiz 3 - Intro to Lists & Loops • 18 minutes
  • Quiz 4 - Functions • 10 minutes
  • Practice Quiz : Intro to Lists, Loops, and Functions • 30 minutes

1 programming assignment • Total 240 minutes

  • Homework 2 - Number Properties • 240 minutes

Module 3 : More with Lists, Strings, Tuples, Sets, and PyCharm

In this module, we’re going to start using PyCharm, another IDE for writing and running Python code. It has enhanced features that go way beyond the limited functionality of IDLE, and it’s also an industry standard. After revisiting lists, including more advanced usage of the commonly used sequence, we’ll take a deep dive into two other very important data structures : sets and tuples. We’ll learn how they can be leveraged to both store and manipulate information. And while we already have some experience working with strings, this module will explore the intricacies and more powerful functionality of strings.

16 videos 3 readings 3 quizzes 1 programming assignment

16 videos • Total 25 minutes

  • Module introduction • 0 minutes • Preview module
  • About PyCharm • 0 minutes
  • Downloading & installing PyCharm • 0 minutes
  • Running code • 1 minute
  • A review of lists • 2 minutes
  • More list operations • 0 minutes
  • List functions • 0 minutes
  • Slicing lists • 6 minutes
  • Strings vs. lists • 0 minutes
  • Slicing strings • 1 minute
  • Code Along Exercise : Name Substring • 1 minute
  • Split and join • 1 minute
  • Creating a tuple • 1 minute
  • Code Along Exercise : Max and min function • 4 minutes
  • Creating a set • 1 minute
  • Iterating over and updating a set • 0 minutes

3 readings • Total 45 minutes

  • Module 3 Resources (DOWNLOAD RELEVANT CODE AND/OR DATA FILES FOR THIS MODULE HERE) • 30 minutes
  • String functions • 5 minutes
  • Homework 3 : Instructions • 10 minutes

3 quizzes • Total 50 minutes

  • Quiz 5 - Lists & Strings • 10 minutes
  • Quiz 6 - Tuples & Sets • 10 minutes
  • Practice Quiz : Jupyter Notebook, IDLE, & PyCharm • 30 minutes
  • Homework 3 - Implement Functions Related to Strings, Lists, Sets, & Tuples • 240 minutes

Module 4 : Dictionaries and Files

There are multiple ways of loading and storing data in Python. Information can be saved in dictionaries, a data structure that is extremely useful for storing multiple attributes (or data points) about a single thing. Data can also be stored in external files and then loaded into Python. This module will allow us to work with dictionaries in a variety of ways and to interact with the local file system by opening, reading from, and writing to, external files. With these added skills, you’ll begin to get a better sense of the dynamic power of Python and how it can be easily integrated with other systems.

17 videos 2 readings 3 quizzes 1 programming assignment

17 videos • Total 54 minutes

  • Module Introduction • 0 minutes • Preview module
  • Creating a dictionary • 0 minutes
  • Key:value pairs • 0 minutes
  • Updating a dictionary • 0 minutes
  • Code Along Exercise : Grade/attendance book • 9 minutes
  • Opening a file • 0 minutes
  • Basics of file open method modes • 1 minute
  • Reading a file • 0 minutes
  • Newline characters • 0 minutes
  • Writing to a file • 0 minutes
  • Closing a file • 0 minutes
  • Coding Demonstration : Open and read a file • 3 minutes
  • Coding Demonstration : Open, read, and append to new file • 3 minutes
  • Coding Demonstration : Open, read, and append to same file • 3 minutes
  • Coding Demonstration : Open, read, and write to new file • 2 minutes
  • Coding Demonstration : File to Dictionary • 11 minutes
  • Intro to Homework 4 • 13 minutes
  • Module 4 Resources (DOWNLOAD RELEVANT CODE AND/OR DATA FILES FOR THIS MODULE HERE) • 30 minutes
  • Homework 4 : Instructions • 10 minutes

3 quizzes • Total 56 minutes

  • Quiz 7 - Dictionaries • 14 minutes
  • Quiz 8 - File I/O • 12 minutes
  • Practice Quiz : Python Dictionaries & Files • 30 minutes
  • Homework 4 - Online Banking System • 240 minutes

Instructor ratings

We asked all learners to give feedback on our instructors based on the quality of their teaching style.

problem solving python programming

The University of Pennsylvania (commonly referred to as Penn) is a private university, located in Philadelphia, Pennsylvania, United States. A member of the Ivy League, Penn is the fourth-oldest institution of higher education in the United States, and considers itself to be the first university in the United States with both undergraduate and graduate studies.

Recommended if you're interested in Software Development

problem solving python programming

University of Pennsylvania

Introduction to Programming with Python and Java

Specialization

problem solving python programming

Data Analysis Using Python

problem solving python programming

Duke University

Python Programming Fundamentals

problem solving python programming

Rice University

Introduction to Scripting in Python

Why people choose coursera for their career.

problem solving python programming

Learner reviews

Showing 3 of 1051

1,051 reviews

Reviewed on Dec 7, 2021

I learned a lot from this course! Thank you Brandon and team. The course has more coverage than the one offered by Michigan U which I took prior to this.

Reviewed on Apr 12, 2021

The course was really good. The assignments were challenging. It was very pleasure to solve the assignments and practice them to become perfect with the basics of Python language

Reviewed on Jun 10, 2021

Clarity in some of the assignment questions needed. As someone with prior experience, the assignments were quite straightforward, but i was stumped by the lack of clarity.

New to Software Development? Start here.

Placeholder

Open new doors with Coursera Plus

Unlimited access to 7,000+ world-class courses, hands-on projects, and job-ready certificate programs - all included in your subscription

Advance your career with an online degree

Earn a degree from world-class universities - 100% online

Join over 3,400 global companies that choose Coursera for Business

Upskill your employees to excel in the digital economy

Frequently asked questions

Do i need to know how to program or have studied computer science in order to take this course.

No, definitely not! This Specialization is intended for anyone who has an interest in problem solving and wants to learn introductory Python or Java. No prior computer science or programming experience is required.

How much math do I need to know to take this course?

The only math that learners will need for this Specialization is arithmetic and basic concepts in logic.

This course was fun. How can I learn more?

This course is the first in the Introduction to Programming with Python and Java Specialization. If you enjoyed it, we recommend Courses 2, 3 and 4 in the series!

If you would like to learn the fundamentals of computer science beyond the basics of programming, consider applying to the Master of Computer and Information and Technology (MCIT) at the University of Pennsylvania, an Ivy League computer science master’s program for people without a computer science background. For an on-campus experience, explore here Opens in a new tab . If you prefer an online setting, apply to MCIT Online Opens in a new tab . In fact, the lectures in this series are also used in the online degree program! The Specialization certificate will be viewed favorably by the admissions committee, so be sure to mention it when you apply.

When will I have access to the lectures and assignments?

Access to lectures and assignments depends on your type of enrollment. If you take a course in audit mode, you will be able to see most course materials for free. To access graded assignments and to earn a Certificate, you will need to purchase the Certificate experience, during or after your audit. If you don't see the audit option:

The course may not offer an audit option. You can try a Free Trial instead, or apply for Financial Aid.

The course may offer 'Full Course, No Certificate' instead. This option lets you see all course materials, submit required assessments, and get a final grade. This also means that you will not be able to purchase a Certificate experience.

What will I get if I subscribe to this Specialization?

When you enroll in the course, you get access to all of the courses in the Specialization, and you earn a certificate when you complete the work. Your electronic Certificate will be added to your Accomplishments page - from there, you can print your Certificate or add it to your LinkedIn profile. If you only want to read and view the course content, you can audit the course for free.

What is the refund policy?

If you subscribed, you get a 7-day free trial during which you can cancel at no penalty. After that, we don’t give refunds, but you can cancel your subscription at any time. See our full refund policy Opens in a new tab .

Is financial aid available?

Yes. In select learning programs, you can apply for financial aid or a scholarship if you can’t afford the enrollment fee. If fin aid or scholarship is available for your learning program selection, you’ll find a link to apply on the description page.

More questions

Mastering Algorithms for Problem Solving in Python

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

Code With C

The Way to Programming

  • C Tutorials
  • Java Tutorials
  • Python Tutorials
  • PHP Tutorials
  • Java Projects

Solving Common Python Programming Problems: Tips and Tricks

CodeLikeAGirl

Sure, I’ll get started on crafting a humorous and fun blog post on solving common Python programming problems based on the provided outlines. Let’s dive into the world of Python programming with a touch of humor! 🐍✨

Identifying and Handling Common Python Programming Problems

Python programming can sometimes feel like herding cats 🐱‍💻—you think you’ve got everything under control until a wild syntax error jumps out of nowhere! 🙀 In this blog post, we will explore some of the most common Python programming problems and equip you with tips and tricks to tackle them head-on. So, grab your coding cape and let’s dive into the wacky world of Python problem-solving! 🦸‍♀️🚀

Syntax Errors

Understanding common syntax mistakes.

Picture this: you’re cruising through your Python code , feeling like a coding wizard 🧙‍♂️, when suddenly, a syntax error slaps you in the face! It’s like a sneaky ninja waiting to trip you up. From missing colons to unmatched parentheses, syntax errors can turn your code from hero to zero in seconds. But fear not, fellow coder! We’ve all been there, and with a few tricks up your sleeve, you’ll be dodging syntax errors like Neo dodges bullets! 💥💻

Let’s uncover the mysteries behind common syntax mistakes and how to outsmart them:

  • Tip: Always double-check your indentation and sprinkle those colons like confetti! 🎉
  • Tip: Pair up those parentheses and brackets like a match made in coding heaven! 💑

Debugging Techniques for Syntax Errors

Now, when it comes to debugging syntax errors, it’s all about channeling your inner detective 🕵️‍♀️. Sherlock your way through the code, follow the clues, and before you know it, you’ll be cracking the case of the elusive syntax bug! 🔍🐞 Here are some nifty techniques to up your debugging game:

  • Print statements are your best friends! Sprinkle them like breadcrumbs through your code to track the elusive bug.
  • Use an integrated development environment (IDE) with built-in syntax highlighting and error checking to catch those pesky mistakes before they catch you.

Logical Errors

Identifying logical flaws in code.

Logical errors are the mischievous pranksters of programming 🃏. Your code runs without a hiccup, but the output is as nonsensical as a unicorn in a library! 🦄📚 Identifying these sneaky buggers requires a keen eye for detail and a dash of Sherlock’s logic.

Here are some clues to uncover logical flaws in your code:

  • Check your assumptions: Are you sure that variable should be a string and not an integer? Double-check your assumptions to reveal hidden gremlins.
  • Walk through your code step by step: Sometimes, a manual run-through of your code can reveal logic leaps that only a trained sloth could make! 🦥💨

Strategies to Debug and Fix Logical Errors

When it’s time to face the music and debug those logical gremlins, arm yourself with these battle-tested strategies:

  • Rubber ducky debugging: Yes, you heard that right! Explain your code to a rubber ducky or an unsuspecting friend 🦆. The act of verbalizing can miraculously unearth logical bugs.
  • Divide and conquer: Break down your code into smaller chunks and test each part independently. It’s like chopping up a coding puzzle into bite-sized pieces.

Stay tuned for the next part where we’ll tackle performance issues, module import errors, and dive into the fascinating world of exception handling in Python! 🎩✨

Anxiously awaiting Part 2? Stay tuned for more Python problem-solving shenanigans coming your way! 🚀

Thank you for bearing with me through this fun-filled Python programming adventure! Remember, coding is not just about solving problems; it’s about enjoying the journey. Happy coding, fellow Pythonistas! 🐍💻🌟

Program Code – Solving Common Python Programming Problems: Tips and Tricks

Code output:.

  • Reversed string: olleh
  • First non-repeating character: w
  • Convert list to number: 1234

Code Explanation:

The Python code snippet above solves three common programming problems with efficient solutions.

  • Reverse a string without using string functions: We define a function reverse_string that takes a string s as input and reverses it without using any built-in string functions. The method iterates through each character in the input string, prepending it to a new string, resulting in a reversed string.
  • Find the first non-repeated character in a string: The function first_non_repeating_char finds the first character in a string that does not repeat. It uses a dictionary counts to keep track of character occurrences and a list char_order to remember the order in which characters appear. The function then iterates through the ordered list of characters and returns the first one with a count of 1. If all characters repeat or if the string is empty, it returns ‘None’.
  • Convert a list of numbers to a single number: The function convert_list_to_number takes a list of numbers and converts them into a single number by concatenating their digits. This is achieved by first converting each number in the list to a string, using the map function, and then joining them together before converting back to an integer.

Each of these functions showcases a common problem-solving approach in Python, highlighting the language’s capability to implement concise and effective solutions with minimal code. The code is written with clarity and is meticulously commented to ensure understanding and readability, demonstrating how to address some typical Python programming problems in an efficient manner.

Frequently Asked Questions (F&Q) on Solving Common Python Programming Problems: Tips and Tricks

Q1: what are some common python programming problems that developers face.

A: Common Python programming problems include issues with syntax errors, logic errors, and handling exceptions. Understanding these common pitfalls can help developers write more robust code.

Q2: How can I efficiently debug Python programming problems?

A: Use debugging tools like print statements, logging, and Python’s built-in debugger (pdb). Also, consider using IDEs with debugging capabilities such as PyCharm or Visual Studio Code .

Q3: Are there any tips for optimizing Python code to prevent performance problems?

A: Yes, optimizing Python code involves techniques like using appropriate data structures , avoiding unnecessary loops, and utilizing libraries like NumPy for numerical computations.

Q4: What should I do when facing challenges with Python package dependencies?

A: Managing dependencies in Python can be tricky. Utilize virtual environments (e.g., virtualenv or conda), use a package manager like pip , and consider using requirements.txt files to manage dependencies effectively.

Q5: How can I stay updated on best practices for Python programming to avoid common pitfalls?

A: Stay connected with the Python community through forums, blogs (like RealPython and Python.org), attend Python meetups or conferences, and follow influential Python developers on social media for valuable insights.

Q6: Is there a recommended approach for handling file I/O errors in Python programming?

A: When dealing with file I/O errors, use try-except blocks to catch specific exceptions (e.g., FileNotFoundError) and handle them gracefully. It’s also essential to close files properly to prevent resource leaks.

You Might Also Like

Adaptive software development: embracing change in technology projects, python vs. other programming languages: what sets it apart, getting started with the python programming language, the evolution of computer languages: python’s rise to prominence, utilizing python to write data to a file: techniques and tips.

Avatar photo

Leave a Reply Cancel reply

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

Latest Posts

93 Top Machine Learning Projects in Python with Source Code for Your Next Project

Top Machine Learning Projects in Python with Source Code for Your Next Project

86 Machine Learning Projects for Final Year with Source Code: A Comprehensive Guide to Success

Machine Learning Projects for Final Year with Source Code: A Comprehensive Guide to Success

87 Top 10 Machine Learning Projects for Students to Excel in Machine Learning Project

Top 10 Machine Learning Projects for Students to Excel in Machine Learning Project

82 Top Machine Learning Projects for Students: A Compilation of Exciting ML Projects to Boost Your Skills in 2022 Project

Top Machine Learning Projects for Students: A Compilation of Exciting ML Projects to Boost Your Skills in 2022 Project

75 Top Machine Learning Projects on GitHub for Deep Learning Enthusiasts - Dive into Exciting Project Ideas Now!

Top Machine Learning Projects on GitHub for Deep Learning Enthusiasts – Dive into Exciting Project Ideas Now!

Privacy overview.

Sign in to your account

Username or Email Address

Remember Me

Pythonista Planet Logo

35 Python Programming Exercises and Solutions

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

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

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

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

problem solving python programming

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

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

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

Happy coding.

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

11 thoughts on “ 35 Python Programming Exercises and Solutions ”

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

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

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

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

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

very good, tnks

Please who can help me with this question asap

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

We are so to run the code in phyton

this is best app

Hello Ashwin, Thanks for sharing a Python practice

May be in a better way for reverse.

#”’ Reverse of a string

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

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

#Reverse of a string ”’

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

Leave a Reply Cancel reply

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

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

Recent Posts

Introduction to Modular Programming with Flask

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

Introduction to ORM with Flask-SQLAlchemy

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

problem solving python programming

Algo Up: Learn Programming 4+

Algorithms, python, javascript, artem bobrov, designed for ipad, screenshots, description.

Welcome to Algo Up, the ultimate iOS app designed to elevate your programming and algorithms skills through intuitive blend of visual programming, Python, and JavaScript. With Algo Up, solving complex programming problems becomes a breeze, whether you're a beginner or an experienced coder. Dive into a world of endless possibilities, sharpen your skills, and unleash your coding potential. • Visual Programming Mastery: Dive into the world of coding with our intuitive visual programming interface. Solve complex problems effortlessly by arranging blocks, making programming accessible to learners of all levels. • Multi-Language Support: Choose your preferred language—Python or JavaScript—and sharpen your coding proficiency across different programming paradigms. Seamlessly switch between languages to expand your skill set. • Offline Evaluation & Testing: Evaluate and test your solutions offline, empowering you to practice coding anywhere, anytime. No internet connection required, ensuring uninterrupted learning and problem-solving sessions. • Customizable Code Editor: Personalize your coding environment with a variety of themes and fonts. Tailor the editor to suit your preferences and coding style, optimizing productivity and comfort. • Extensive Documentation & Hints: Access our extensive documentation library, complete with hints and tips to guide you through problem-solving challenges. Leverage expert insights to overcome obstacles and refine your coding techniques. • Built-in Tutorial: Jumpstart your coding journey with our built-in tutorial. Explore fundamental concepts and advanced strategies through interactive lessons, paving the way for mastery in problem-solving. • Code Playground for Experimentation: Unleash your creativity in our Code Playground. Experiment with code, test ideas, and explore new concepts in a safe and supportive environment, fueling innovation and discovery. Download Algo Up now and embark on a transformative journey to become a proficient problem solver and master coder. Elevate your skills, conquer challenges, and unleash your coding potential with Algo Up!

Version 1.1.1

We've squashed those troublesome bugs! Our app is now smoother, faster, and more efficient. You can now enjoy an even better coding journey, free from interruptions.

App Privacy

The developer, Artem Bobrov , indicated that the app’s privacy practices may include handling of data as described below. For more information, see the developer’s privacy policy .

Data Not Linked to You

The following data may be collected but it is not linked to your identity:

  • Diagnostics

Privacy practices may vary, for example, based on the features you use or your age. Learn More

Information

English, French, German, Russian

  • App Support
  • Privacy Policy

You Might Also Like

Learn Pentesting like a Pro!

Flix4Fun:Movies Box & TV Show

Ethical Hacking University App

Easy Coder : Learn Java

Readbay.ai - Just 1 Daily Read

COMMENTS

  1. Solve Python

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

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

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

  5. Python Exercise with Practice Questions and Solutions

    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. ... In closing, we just want to say that the practice or solving Python problems always helps to clear your core concepts and ...

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

  7. Problem Solving, Python Programming, and Video Games

    There are 12 modules in this course. 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.

  8. Python Basics: Problem Solving with Code

    In this course you will see how to author more complex ideas and capabilities in Python. In technical terms, you will learn dictionaries and how to work with them and nest them, functions, refactoring, and debugging, all of which are also thinking tools for the art of problem solving. We'll use this knowledge to explore our browsing history ...

  9. Introduction to Python Programming

    This course provides an introduction to programming and the Python language. Students are introduced to core programming concepts like data structures, conditionals, loops, variables, and functions. ... This Specialization is intended for anyone who has an interest in problem solving and wants to learn introductory Python or Java. No prior ...

  10. Art of Problem Solving

    Python is a useful and popular computer programming language. Confusingly, Python has two major versions (2 and 3) and they are not fully compatible. We recommend using the most recent release of version 3. (This is the version that our Introduction to Programming with Python course uses -- if you are enrolled in that class, you must have ...

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

  13. Problems

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

  14. Hands-On Linear Programming: Optimization With Python

    You'll use Python to solve these two problems in the next section. Small Linear Programming Problem. Consider the following linear programming problem: 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.

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

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

  17. Programming and Problem Solving using Python

    This textbook is designed to learn python programming from scratch. At the beginning of the book general problem solving concepts such as types of problems, difficulties in problem solving, and problem solving aspects are discussed.From this book, you will start learning the Python programming by knowing about the variables, constants, keywords, data types, indentation and various programming ...

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

  19. Solving Common Python Programming Problems: Tips and Tricks

    Copy Code. # Solving Common Python Programming Problems: Tips and Tricks. # Problem 1: Reverse a string without using string functions. def reverse_string(s): '''. This function takes a string and returns the reversed string without using built-in functions. '''. reversed_string = ''. for char in s:

  20. 35 Python Programming Exercises and Solutions

    If you've completed learning the syntax of Python programming language, it is the right time to do some practice programs. In this article, I'll list down some problems that I've done and the answer code for each exercise. Analyze each problem and try to solve it by yourself. If you have any doubts, you can check the code that I've ...

  21. 7 Best Platforms to Practice Python

    Python is a beginner-friendly programming language to learn. You can learn Python's syntax and other fundamentals in a few hours and start writing simple programs. ... Challenges range from beginner to advanced levels and cover various topics in algorithms, data structures, and general problem-solving techniques. Edabit has tutorials and ...

  22. Python Exercises, Practice, Solution

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

  23. How Python Programming Can Help You Solve Everyday Problems

    To wrap things up. Python is an incredibly flexible language and can be used in a number of ways to help you solve everyday problems. Python can be used for automation, data analysis and ...

  24. PDF Notes of Lesson Ge3151- Problem Solving and Python Programming

    PROBLEM SOLVING TECHNIQUES Problem solving technique is a set of techniques that helps in providing logic for solving a problem. Problem solving can be expressed in the form of 1. Algorithms. 2. Flowcharts. 3. Pseudo codes. 4. Programs 1.ALGORITHM It is defined as a sequence of instructions that describe a method for solving a problem. In other ...

  25. Python for Algorithmic Thinking: Problem-Solving Skills

    Share This: Share Python for Algorithmic Thinking: Problem-Solving Skills on Facebook Share Python for Algorithmic Thinking: Problem-Solving Skills on LinkedIn Share Python for Algorithmic Thinking: ... The need for competent problem solvers has never been greater, and Python has become an important programming language. Because of…

  26. Algo Up: Learn Programming 4+

    Welcome to Algo Up, the ultimate iOS app designed to elevate your programming and algorithms skills through intuitive blend of visual programming, Python, and JavaScript. With Algo Up, solving complex programming problems becomes a breeze, whether you're a beginner or an experienced coder. Dive into a world of endless possibilities, sharpen ...