PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python Exercises

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics, Data structure, to Data analytics. As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.

  • All exercises are tested on Python 3.
  • 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.

Select the exercise you want to solve.

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics: Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics: print() and input(), File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics: If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics: Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics: Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics: Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics: random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Given:

str = 'My Name is Jessa'

Expected Output

yM emaN si asseJ
Show Hint
  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string
Show Solution

Steps to solve this question:

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string

Solution:

# Exercise to reverse each word  of a string
def reverse_words(Sentence):
    # Split string on whitespace
    words = Sentence.split(" ")

    # iterate list and reverse each word using ::-1
    new_word_list = [word[::-1] for word in words]
    
    # Joining the new list of words
    res_str = " ".join(new_word_list)
    return res_str

# Given String
str1 = "My Name is Jessa"
print(reverse_words(str1))

Exercise 2: Read text file into a variable and replace all newlines with space

Given: Assume you have a following text file (sample.txt).

Line1
line2
line3
line4
line5

Expected Output:

Line1 line2 line3 line4 line5
Show Hint
  • First, read a text file.
  • Next, use string replace() function to replace all newlines (\n) with space (' ').
Show Solution

Steps to solve this question: -

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Next, use string replace() function to replace all newlines (\n) with space (' ').
  • Display final string
with open('sample.txt', 'r') as file:
    data = file.read().replace('\n', ' ')
    print(data)

Exercise 3: Remove items from a list while iterating

Description:

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

Given:

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Expected Output: -

[10, 20, 30, 40, 50]
Show Hint
  • Get the list's size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size
Show Solution

Solution 1: Using while loop

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
i = 0
# get list's size
n = len(number_list)
# iterate list till i is smaller than n
while i < n:
    # check if number is greater than 50
    if number_list[i] > 50:
        # delete current index from list
        del number_list[i]
        # reduce the list size
        n = n - 1
    else:
        # move to next item
        i = i + 1
print(number_list)

Solution 2: Using for loop and range()

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in range(len(number_list) - 1, -1, -1):
    if number_list[i] > 50:
        del number_list[i]
print(number_list)

Exercise 4: Reverse Dictionary mapping

Given:

ascii_dict = {'A': 65, 'B': 66, 'C': 67, 'D': 68}

Expected Output:

{65: 'A', 66: 'B', 67: 'C', 68: 'D'}
Show Solution
ascii_dict = {'A': 65, 'B': 66, 'C': 67, 'D': 68}
# Reverse mapping
new_dict = {value: key for key, value in ascii_dict.items()}
print(new_dict)

Exercise 5: Display all duplicate items from a list

Given:

sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]

Expected Output: -

[20, 60, 30]
Show Hint
  1. Use the counter() method of the collection module.
  2. Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2
Show Solution

Solution 1: - Using collections.Counter()

import collections

sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]

duplicates = []
for item, count in collections.Counter(sample_list).items():
    if count > 1:
        duplicates.append(item)
print(duplicates)

Solution 2: -

sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]
exist = {}
duplicates = []

for x in sample_list:
    if x not in exist:
        exist[x] = 1
    else:
        duplicates.append(x)
print(duplicates)

Exercise 6: Filter dictionary to contain keys present in the given list

Given:

# Dictionary
d1 = {'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70}

# Filter dict using following keys
l1 = ['A', 'C', 'F']

Expected Output: -

new dict {'A': 65, 'C': 67, 'F': 70}
Show Solution
# Dictionary
d1 = {'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70}
# Filter dict using following keys
l1 = ['A', 'C', 'F']
new_dict = {key: d1[key] for key in l1}
print(new_dict)

Exercise 7: Print the following number pattern

1 1 1 1 1 
2 2 2 2 
3 3 3 
4 4 
5

Refer to Print patterns in Python to solve this question.

Show Hint
  • set x = 0
  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop
Show Solution
rows = 5
x = 0
# reverse for loop from 5 to 0
for i in range(rows, 0, -1):
    x += 1
    for j in range(1, i + 1):
        print(x, end=' ')
    print('\r')

Exercise 8: Create an inner function

Question description: -

  • Create an outer function that will accept two strings, x and y. (x= 'Emma' and y = 'Kelly'.
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word 'developer' to it.

Expected Output: -

EmmaKellyDevelopers
Show Solution
def manipulate(x, y):
    # concatenate two strings
    def inner_fun(x, y):
        return x + y

    z = inner_fun(x, y)
    return z + 'Developers'

result = manipulate('Emma', 'Kelly')
print(result)

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

Given:

list1 = [5, [10, 15, [20, 25, [30, 35], 40], 45], 50]

Expected Output: -

[5, [10, 15, [20, 25, [30, 3500], 40], 45], 50]
Show Solution
list1 = [5, [10, 15, [20, 25, [30, 35], 40], 45], 50]
# modify item
list1[1][2][2][1] = 3500
# print final result
print(list1)

# print(list1[1]) = [10, 15, [20, 25, [30, 400], 40], 45]
# print(list1[1][2]) = [20, 25, [30, 400], 40]
# print(list1[1][2][2]) = [30, 40]
# print(list1[1][2][2][1]) = 40

Exercise 10: Access the nested key increment from the following dictionary

Given:

emp_dict = {
    "company": {
        "employee": {
            "name": "Jess",
            "payable": {
                "salary": 9000,
                "increment": 12
            }
        }
    }
}
Show Solution
emp_dict = {
    "company": {
        "employee": {
            "name": "Jess",
            "payable": {
                "salary": 9000,
                "increment": 12
            }
        }
    }
}
print(emp_dict['company']['employee']['payable']['increment'])

Under Exercises: -

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on: December 8, 2021 | 47 Comments

Filed Under: Python, Python Exercises, Python Object-Oriented Programming (OOP)

Python Date and Time Exercise with Solutions

Updated on: December 8, 2021 | 9 Comments

Filed Under: Python, Python Exercises

Python Dictionary Exercise with Solutions

Updated on: August 23, 2022 | 49 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Tuple Exercise with Solutions

Updated on: December 8, 2021 | 73 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Set Exercise with Solutions

Updated on: October 20, 2022 | 24 Comments

Filed Under: Python, Python Basics, Python Exercises

Python if else, for loop, and range() Exercises with Solutions

Updated on: September 6, 2021 | 249 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Functions Exercise

Updated on: August 2, 2022 | 117 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Input and Output Exercise

Updated on: September 6, 2021 | 85 Comments

Filed Under: Python, Python Basics, Python Exercises

Python List Exercise with Solutions

Updated on: December 8, 2021 | 171 Comments

Filed Under: Python, Python Basics, Python Exercises

Python JSON Exercise

Updated on: December 8, 2021 | 6 Comments

Filed Under: Python, Python Exercises, Python JSON

Python Data Structure Exercise for Beginners

Updated on: December 8, 2021 | 105 Comments

Filed Under: Python, Python Basics, Python Exercises

Python String Exercise with Solutions

Updated on: October 6, 2021 | 191 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Matplotlib Exercise

Updated on: March 9, 2021 | 22 Comments

Filed Under: Python, Python Exercises

Python Pandas Exercise

Updated on: March 9, 2021 | 45 Comments

Filed Under: Pandas, Python, Python Exercises

Python NumPy Exercise

Updated on: July 20, 2021 | 27 Comments

Filed Under: Python, Python Exercises

Python Basic Exercise for Beginners

Updated on: September 26, 2022 | 414 Comments

Filed Under: Python, Python Basics, Python Exercises

Useful Python Tips and Tricks Every Programmer Should Know

Updated on: May 17, 2021 | 20 Comments

Filed Under: Python, Python Exercises

Python random Data generation Exercise

Updated on: December 8, 2021 | 13 Comments

Filed Under: Python, Python Exercises, Python Random

Python Database Programming Exercise

Updated on: March 9, 2021 | 15 Comments

Filed Under: Python, Python Databases, Python Exercises

Online Python Code Editor

Updated on: June 1, 2022 |

Filed Under: Python, Python Exercises

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

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–2023 pynative.com