PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises

Practice Python Exercises & Challenges with Solutions [320+ Coding Questions]

Free Coding Exercises for Python Developers. Practice Python with 19 topic-wise exercises with over 320+ coding questions covering everything from Python basics and data structures to data analytics.

What included in these Python Exercises?

  • All exercises are tested on Python 3.
  • Each exercise contains 15-30 coding questions or challenges, focusing on specific Python topics to give you targeted practice
  • Reference articles are provided for help.
  • Hint and solutions are provided for every question this enables you to immediately check your code and learn from any mistakes
  • Practice each Exercise in Online Code Editor

Whether you're a beginner taking your first steps or an experienced developer looking to refine your skills, these exercises are designed to be beneficial.

Also, See:

  • Learn Python to solve these exercises.
  • Python Quizzes: 14 Different Python quizzes
  • Python Interview Questions and Answers

Below are the list of exercises. Select the exercise you want to solve. All the Best.

Basic Exercise for Beginners

Total Exercises: 23

This Python beginner’s exercise helps you quickly learn and practice basic skills by solving coding questions and challenges on below topics.

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

Python Input and Output Exercise

Total Exercises: 15

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

Topics: Python I/O, File I/O

Python Loop Exercise

Total Exercises: 22

This exercise contains coding challenges to solve using if-else conditions, for loops, the range() function, and while loops.

Topics: Control flow statements, Loop, and while loop

Python Functions Exercise

Total Exercises: 18

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

Total Exercises: 18

Solve Python string coding questions to learn and practice string operations and manipulations.

Python Data Structure Exercise

Total Exercises: 10

Practice coding questions on widely used Python types such as List, Set, Dictionary, and Tuple.

Python List Exercise

Total Exercises: 23

This exercise contains coding questions to learn and practice list operations, manipulations, functions, and list comprehension.

Topic: Python List

Python Dictionary Exercise

Total Exercises: 20

This exercise contains coding questions to help Python developers to learn and practice dictionary operations and manipulation.

Topic: Python Dictionary

Python Set Exercise

Total Exercises: 16

Practice and solve various set operations, manipulations, and set functions.

Topic: Python Sets

Python Tuple Exercise

Total Exercises: 19

Practice and solve various tuple operations, manipulations, and tuple functions.

Topic: Python Tuples

Python Date and Time Exercise

Total Exercises: 10

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

Topics: Date and Time, time, Date, Calendar.

Python OOP Exercise

Total Exercises: 10

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

Topics: OOP, Object, Classes, Inheritance

Python File Handling Exercise

Total Exercises: 15

This exercise contains coding questions to gain proficiency in file operations such as reading, writing, renaming a file, copying file, deleting a file, managing file properties, content filtering, and replacement.

Topics: File Handling

Python JSON Exercise

Total Exercises: 9

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

Topics: JSON

Python NumPy Exercise

Total Exercises: 50

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

Python Pandas Exercise

Total Exercises: 10

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

Random Data Generation Exercise

Total Exercises: 10

Practice and solve coding questions to learn the various techniques to generate random data in Python.

Topics: random module, secrets module, UUID module

Python Database Exercise

Total Exercises: 5

Solve database coding problems to master database operations step by step.

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

Python Matplotlib Exercise

Total Exercises: 10

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

Exercises for Intermediate developers

Exercise 1: Reverse each word of a string

Given:

str = 'My Name is Jessa'

Expected Output:

yM emaN si asseJ

+ 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

# 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

+ 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:

  • First, open the file in read mode.
  • Next, read all the content from the file using the read() function and assign it to a variable.
  • Next, use the string replace() function to replace all newlines (\n) with a space (' ').
  • Finally, display the resulting string.

with open('sample.txt', 'r') as file:
    data = file.read().replace('\n', ' ')
    print(data)

Exercise 3: Remove items from a list while iterating

In this question, you need to remove items from a list during iteration without creating a separate copy of the 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]

+ Hint

  • Get the size of the list and store it in size variable
  • Iterate through the list using a while loop.
  • Check if the current number is greater than 50.
  • If it is, delete the item using the del keyword.
  • Decrement the list size.

+ Show Solution

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]

+ Hint

  • Use the Counter() method from the collections module.
  • Create a dictionary to maintain the count of each item in the list. \
  • Next, fetch all keys with a value 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

Given:

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.

+ Hint

  • Set x to 0.
  • Use two for loops.
  • The outer loop will be a reverse for loop, iterating from 5 down to 0 (inclusive).
  • Increment the value of x by 1 in each iteration of the outer loop.
  • The inner loop will iterate from 0 up to the current value of i from the outer loop (exclusive).
  • Print the value of x in each iteration of the inner loop.
  • Print a newline character at the end of each iteration of the 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 accepts two strings, x and y (where x = 'Emma' and y = 'Kelly').
  • Create an inner function within the outer function that concatenates x and y.
  • Finally, the outer function will join the word 'developer' to the result of the inner function's concatenation.

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

Given:

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

Change the element 35 to 3500.

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'])

Python File Handling Exercises

Updated on: April 30, 2025 | 4 Comments

Filed Under: Python, Python Exercises, Python File Handling

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

Updated on: April 17, 2025 | 55 Comments

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

Python Date and Time Exercise with Solutions

Updated on: June 5, 2025 | 10 Comments

Filed Under: Python, Python Exercises

Python Dictionary Exercise with Solutions

Updated on: May 30, 2025 | 65 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Tuple Exercise with Solutions

Updated on: June 3, 2025 | 101 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Set Exercise with Solutions

Updated on: May 31, 2025 | 30 Comments

Filed Under: Python, Python Basics, Python Exercises

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

Updated on: April 19, 2025 | 324 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Functions Exercise

Updated on: May 22, 2025 | 163 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Input and Output Exercise

Updated on: June 8, 2025 | 111 Comments

Filed Under: Python, Python Basics, Python Exercises

Python List Exercise with Solutions

Updated on: May 23, 2025 | 207 Comments

Filed Under: Python, Python Basics, Python Exercises

Python JSON Exercise

Updated on: December 8, 2021 | 9 Comments

Filed Under: Python, Python Exercises, Python JSON

Python Data Structure Exercise for Beginners

Updated on: May 22, 2025 | 119 Comments

Filed Under: Python, Python Basics, Python Exercises

Python String Exercise with Solutions

Updated on: March 13, 2025 | 234 Comments

Filed Under: Python, Python Basics, Python Exercises

Python Matplotlib Exercise

Updated on: March 9, 2021 | 25 Comments

Filed Under: Python, Python Exercises

Python Pandas Exercise

Updated on: March 9, 2021 | 55 Comments

Filed Under: Pandas, Python, Python Exercises

Python NumPy Exercise: 50 Questions With Solutions (Beginner to Advanced)

Updated on: August 31, 2025 | 32 Comments

Filed Under: Python, Python Exercises

Python Basic Exercise for Beginners

Updated on: April 30, 2025 | 521 Comments

Filed Under: Python, Python Basics, Python Exercises

Useful Python Tips and Tricks Every Programmer Should Know

Updated on: May 17, 2021 | 23 Comments

Filed Under: Python, Python Exercises

Python Random Data Generation Exercise

Updated on: June 5, 2025 | 13 Comments

Filed Under: Python, Python Exercises, Python Random

Python Database Programming Exercise

Updated on: June 5, 2025 | 17 Comments

Filed Under: Python, Python Databases, Python Exercises

Online Python Code Editor

Updated on: November 25, 2025 |

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement