Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python exercises.

You can test your Python skills with W3Schools' Exercises.

We have gathered a variety of Python exercises (with answers) for each Python Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start Python Exercises

Start Python Exercises ❯

If you don't know Python, we suggest that you read our Python Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

python assignments for practice

Practice Python

follow us in feedly

Beginner Python exercises

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

All Exercises

python assignments for practice

All Solutions

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

Top online courses in Programming Languages

10 Python Practice Exercises for Beginners with Solutions

Author's photo

  • python basics
  • get started with python
  • online practice

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

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

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

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

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

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

Let’s get started!

Exercise 1: User Input and Conditional Statements

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

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

Exercise 2: Lowercase and Uppercase Characters

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

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

Exercise 3: Building Triangles

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

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

Python Practice Exercises for Beginners

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

Exercise 4: Call a Function From Another Function

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

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

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

Exercise 5: Looping and Conditional Statements

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

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

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

Exercise 6: Nested Loops and Conditional Statements

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

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

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

Exercise 7: Lists and Tuples

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

the function should return

Assume the input list is non-empty.

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

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

Exercise 8: Dictionaries

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

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

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

Exercise 9: More Dictionaries

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

For example, for input:

the output should be:

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

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

Exercise 10: String Encryption

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

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

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

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

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

Do You Want More Python Practice Exercises?

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

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

You may also like

python assignments for practice

How Do You Write a SELECT Statement in SQL?

python assignments for practice

What Is a Foreign Key in SQL?

python assignments for practice

Enumerate and Explain All the Basic Elements of an SQL Query

Uploaded avatar of jeffdparker

Practice 140 exercises in Python

Learn and practice Python by completing 140 exercises that explore different concepts and ideas.

Explore the Python exercises on Exercism

Unlock more exercises as you progress. They’re great practice and fun to do!

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs

Python Projects

  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

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.

python assignments for practice

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.

  • 10 Best Slack Integrations to Enhance Your Team's Productivity
  • 10 Best Zendesk Alternatives and Competitors
  • 10 Best Trello Power-Ups for Maximizing Project Management
  • Google Rolls Out Gemini In Android Studio For Coding Assistance
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Python if-else easy python (basic) max score: 10 success rate: 89.73%, 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.15%, nested lists easy python (basic) max score: 10 success rate: 91.65%, cookie support is required to access hackerrank.

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

25 Python Projects for Beginners – Easy Ideas to Get Started Coding Python

Jessica Wilkins

The best way to learn a new programming language is to build projects with it.

I have created a list of 25 beginner friendly project tutorials in Python.

My advice for tutorials would be to watch the video, build the project, break it apart and rebuild it your own way. Experiment with adding new features or using different methods.

That will test if you have really learned the concepts or not.

You can click on any of the projects listed below to jump to that section of the article.

If you are not familiar with the basics of Python, then I would suggest watching this beginner freeCodeCamp Python tutorial .

Python Projects You Can Build

  • Guess the Number Game (computer)
  • Guess the Number Game (user)
  • Rock, paper, scissors
  • Countdown Timer
  • Password Generator
  • QR code encoder / decoder
  • Tic-Tac-Toe
  • Tic-Tac-Toe AI
  • Binary Search
  • Minesweeper
  • Sudoku Solver
  • Photo manipulation in Python
  • Markov Chain Text Composer
  • Connect Four
  • Online Multiplayer Game
  • Web Scraping Program
  • Bulk file renamer
  • Weather Program

Code a Discord Bot with Python - Host for Free in the Cloud

  • Space invaders game

Mad libs Python Project

In this Kylie Ying tutorial, you will learn how to get input from the user, work with f-strings, and see your results printed to the console.

This is a great starter project to get comfortable doing string concatenation in Python.

Guess the Number Game Python Project (computer)

In this Kylie Ying tutorial, you will learn how to work with Python's random module , build functions, work with while loops and conditionals, and get user input.

Guess the Number Game Python Project (user)

In this Kylie Ying tutorial, you will build a guessing game where the computer has to guess the correct number. You will work with Python's random module , build functions, work with while loops and conditionals, and get user input.

Rock, paper, scissors Python Project

In this Kylie Ying tutorial , you will work with random.choice() , if statements, and getting user input. This is a great project to help you build on the fundamentals like conditionals and functions.

Hangman Python Project

In this Kylie Ying tutorial, you will learn how to work with dictionaries, lists, and nested if statements. You will also learn how to work with the string and random Python modules.

Countdown Timer Python Project

In this Code With Tomi tutorial , you will learn how to build a countdown timer using the time Python module. This is a great beginner project to get you used to working with while loops in Python.

Password Generator Python Project

In this Code With Tomi tutorial , you will learn how to build a random password generator. You will collect data from the user on the number of passwords and their lengths and output a collection of passwords with random characters.

This project will give you more practice working with for loops and the random Python module.

QR code encoder / decoder Python Project

In this Code With Tomi tutorial , you will learn how to create your own QR codes and encode/decode information from them. This project uses the qrcode library.

This is a great project for beginners to get comfortable working with and installing different Python modules.

Tic-Tac-Toe Python Project

In this Kylie Ying tutorial, you will learn how to build a tic-tac-toe game with various players in the command line. You will learn how to work with Python's time and math modules as well as get continual practice with nested if statements.

Tic-Tac-Toe AI Python Project

In this Kylie Ying tutorial, you will learn how to build a tic-tac-toe game where the computer never loses. This project utilizes the minimax algorithm which is a recursive algorithm used for decision making.

Binary Search Python Project

In this Kylie Ying tutorial, you will learn how to implement the divide and conquer algorithm called binary search. This is a common searching algorithm which comes up in job interviews, which is why it is important to know how to implement it in code.

Minesweeper Python Project

In this Kylie Ying tutorial, you will build the classic minesweeper game in the command line. This project focuses on recursion and classes.

Sudoku Solver Python Project

In this Kylie Ying tutorial, you will learn how to build a sudoku solver which utilizes the backtracking technique. Backtracking is a recursive technique that searches for every possible combination to help solve the problem.

Photo Manipulation in Python Project

In this Kylie Ying tutorial, you will learn how to create an image filter and change the contrast, brightness, and blur of images. Before starting the project, you will need to download the starter files .

Markov Chain Text Composer Python Project

In this Kylie Ying tutorial, you will learn about the Markov chain graph model and how it can be applied the relationship of song lyrics. This project is a great introduction into artificial intelligence in Python.

Pong Python Project

In this Christian Thompson tutorial , you will learn how to recreate the classic pong game in Python. You will be working with the os and turtle Python modules which are great for creating graphics for games.

Snake Python Project

In this Tech with Tim tutorial, you will learn how to recreate the classic snake game in Python. This project uses Object-oriented programming and Pygame which is a popular Python module for creating games.

Connect Four Python Project

In this Keith Galli tutorial, you will learn how to build the classic connect four game. This project utilizes the numpy , math , pygame and sys Python modules.

This project is great if you have already built some smaller beginner Python projects. But if you haven't built any Python projects, then I would highly suggest starting with one of the earlier projects on the list and working your way up to this one.

Tetris Python Project

In this Tech with Tim tutorial, you will learn how to recreate the classic Tetris game. This project utilizes Pygame and is great for beginner developers to take their skills to the next level.

Online Multiplayer Game Python Project

In this Tech with Tim tutorial, you will learn how to build an online multiplayer game where you can play with anyone around the world. This project is a great introduction to working with sockets, networking, and Pygame.

Web Scraping Program Python Project

In this Code With Tomi tutorial , you will learn how to ask for user input for a GitHub user link and output the profile image link through web scraping. Web scraping is a technique that collects data from a web page.

Bulk File Re-namer Python Project

In this Code With Tomi tutorial , you will learn how to build a program that can go into any folder on your computer and rename all of the files based on the conditions set in your Python code.

Weather Program Python Project

In this Code With Tomi tutorial , you will learn how to build a program that collects user data on a specific location and outputs the weather details of that provided location. This is a great project to start learning how to get data from API's.

In this Beau Carnes tutorial , you will learn how to build your own bot that works in Discord which is a platform where people can come together and chat online. This project will teach you how to work with the Discord API and Replit IDE.

After this video was released, Replit changed how you can store your environments variables in your program. Please read through this tutorial on how to properly store environment variables in Replit.  

Space Invaders Game Python Project

In this buildwithpython tutorial ,  you will learn how to build a space invaders game using Pygame. You will learn a lot of basics in game development like game loops, collision detection, key press events, and more.

I am a musician and a programmer.

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

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

Python and Excel Projects for practice

Python Exercises

el master

  • Install Python-Resources-Datasets

PYTHON EXERCISES

Python exercises and practice questions are vital for learning the programming language effectively. They are not just a way to test your knowledge, but also a way to reinforce what you have learned and gain practical experience. By solving Python problems and practicing exercises, you are able to apply the concepts you have learned in a real-world context, which greatly enhances your understanding of the language.

One of the main benefits of solving Python exercises is that it helps you build problem-solving skills. Programming is all about finding solutions to problems, so when you solve exercises, you develop the ability to divide the task in  smaller, more manageable parts. This skill is not only important in programming but also in various other aspects of life. Another benefit of solving Python exercises is that it helps you become more familiar with the language syntax and its various features. You will have to explore different aspects of Python and gain a deeper understanding of its capabilities. This familiarity with the language will make you more efficient and effective in writing code. Moreover, Python practice gives you the opportunity to practice and reinforce what you have learned. It is one thing to read about programming concepts, but it is another thing entirely to actually implement them in code. Exercises provide a hands-on experience that allows you to solidify your understanding of the material.

When students encounter difficult problems during their learning process, it can be discouraging. However, there are several tips that can help them confront these challenges and stay motivated. First, it is important to break down the problem into smaller parts and tackle them one at a time. By approaching the problem step by step, it becomes more manageable and less overwhelming.

Additionally, it is helpful to seek out resources such as online forums or tutorials that can provide guidance and support. Often, other programmers have faced similar challenges and can offer insights or solutions that can help overcome the difficulty. Collaboration and seeking help from others is a valuable skill in programming.

Lastly, it is crucial to stay motivated and not get discouraged by setbacks or failures. Programming is a process of trial and error, and it is normal to encounter obstacles along the way. Embrace these challenges as opportunities for growth and learning. Celebrate your successes, no matter how small they may be, and keep pushing forward. Here you will find a compilation of different sites with exercises and problems so you can practice Python at your own pace.

Python Exercises for Beginners

  • 100 Python problems: Find the last item in an array, even/odd number, word count, reverse string order, alphabet soup, repeating letters, factorial, sort numbers, phone number formatting, etc.
  • 400 Exercises: strings, lists, functions, loops, conditionals, date time, data structure, recursion, math,regex, numpy, pandas.
  • 12 Python exercises (PDF, to see all exercises change number in the browser bar): dictionaries exercises. Functions with loops on dictionaries, function to invert a dictionary.
  • 8 exercises of strings: sum of lengths of names, find the shortest name in text, convert a number to its string, sort names in text alphabetically, etc.
  • 15 Exercises: fill in the blanks (conditionals), find bugs in code, create and merge dictionaries, custom exceptions, count average length of words in a sentence, lists,  function to turn vowels in uppercase and consonants in lower case, create test case for a function and so on.
  • 36 exercises about list comprehensions, list remove duplicates, element search, write to a file, draw a game board, max of three, hangman, birthday plots, odd or even, functions, modules.
  • 75 Exercises of data science: Assignments of Pandas, NumPy, data structure, Matplotlib, Database.
  • 50 Interview questions: theory questions and exercises.
  • 50 Exercises: Find square root, generate random numbers, display multiplication table, find sum of natural numbers,  display calendar, add two matrices, find size of an image, etc.

Python Exercises for Intermediates

  • Real-world Python Projects: Data cleaning, OOP, Python libraries, applications with GUI, automation exercises, data analysis , games, etc.
  • 150 Exercises of Python core topics: strings, sets, maths, loops, collections, dates, exceptions, classes, regex, XML.
  • 40 Python practice questions focused on lists, functions, loops, modules, conditionals, linear algebra, statistics.
  • 200 Python Challenges & problems.
  • 15 Fun programming problems: program of treasure hunt, chess queen attack, program for secret messages, turn roman numbers into arabic, phone words program, calculation of bowling match scores, etc.
  • 50 Problems: rounding, sum of digits, average in array, modular calculator, double dice roll, mortgage calculator, star medals, lucky tickets, etc.
  • 40 Assignments + 2 projects + exam: Practice the Math module, quadratic formula, random function,  nims/stones games, lists, report card function, list comprehensions, structures, OOP, inheritance.
  • 150 exercises: databases, expressions and variables, loops, functions, graphics, list comprehension, OOP, Scientific Python.
  • 200 Exercises: letter capitalize, time convert, vowel square, longest word, coin determiner, stock picker, matrix chains, character removal, etc.
  • 10 Scientific Python exercises: maths, loops, functions, combine text and numbers, plot a function, numpy.
  • 30 Interview questions.
  • 20 Code challenges: Email validator program, password reset program, quiz application, count words/vowels in a string, etc.
  • 22 Problems to perform calculations with Python: Compound interest code, time to fill swimming pool, calculator, area and circunference calculation, distance conversion, load data into dictionaries, triangle recognition, etc.
  • Data Science interview questions: Technical (SQL, Python) and theory (statistics, Machine Learning).

Advanced Python Exercises

  • 5 Assignments, 10 labs: Data cleaning, web scrapping, Pandas, Matplotlib libraries, linear regression (SciKit learn), cross validation, map reduce, etc.
  • 50 Examples of multiple topics: Web scrapping (Selenium), webapp with Flask, RESTful microservice, reddit bot, sentiment analysis, recommendation systems, linear regression, etc.
  • 50 statistics exercises (scipy): Probability, linear models, bayesian models, hypothesis testing, cross validation.
  • Programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like. People use them as a speed contest, interview prep, company training, university coursework, practice problems.
  • 800 coding math problems.
  • 200 exercises & interview questions: Maths, searching, classic algorithms, astronomy, prime numbers, fundamentals of computing, arithmetic, computational geometry, cryptography, data processing, games, graphs.
  • 8 Problems about decorators to cache function invocation results, generator functions, file browsing, plugin registration system and so on.
  • Python interview questions: 64 interview questions from multiple companies.
  • Python challenges of  former editions.
  • 90 exercises focused on the Numpy library.

QUICK SURVEY

What is your current programming level.

  • Absolute beginner
  • I have taken courses but need practice
  • Intermediate

What exercises are you looking for?

  • Data Structures (lists. dictionaries, tuples...)
  • Conditional Statements
  • OOP-Classes,Objects,methods
  • A bit of everything
  • Data Science
  • File IO, Environment variables

What type of projects are you interested in?

  • Software development - scripting
  • Web Applications
  • 3D CAD Apps
  • Cibersecurity
  • Python for Raspberry pi,IOT,Embedded
  • learn to write clean code
  • Cybersecurity

What is your current employment status?

  • High School Student
  • University Student
  • Non University Student
  • Employed for wages/Self employed
  • Looking for a job

How did you learn to code?

  • Self taught / Internet
  • University class
  • High school

Python Exercises

Elementor #3086

Object oriented programming for beginners.

el master

I want to learn Python

Leave a reply

By using this form you agree with the storage and handling of your data by this website. *

facebook_logo

Terms of Use

Python and Excel Projects for practice

Shopping cart

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.

python assignments for practice

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

python assignments for practice

  • Comprehensive Learning Paths
  • 150+ Hours of Videos
  • Complete Access to Jupyter notebooks, Datasets, References.

Rating

101 Pandas Exercises for Data Analysis

  • April 27, 2018
  • Selva Prabhakaran

101 python pandas exercises are designed to challenge your logical muscle and to help internalize data manipulation with python’s favorite package for data analysis. The questions are of 3 levels of difficulties with L1 being the easiest to L3 being the hardest.

python assignments for practice

You might also like to practice the 101 NumPy exercises , they are often used together.

1. How to import pandas and check the version?

2. how to create a series from a list, numpy array and dict.

Create a pandas series from each of the items below: a list, numpy and a dictionary

3. How to convert the index of a series into a column of a dataframe?

Difficulty Level: L1

Convert the series ser into a dataframe with its index as another column on the dataframe.

4. How to combine many series to form a dataframe?

Combine ser1 and ser2 to form a dataframe.

python assignments for practice

5. How to assign name to the series’ index?

Give a name to the series ser calling it ‘alphabets’.

6. How to get the items of series A not present in series B?

Difficulty Level: L2

From ser1 remove items present in ser2 .

7. How to get the items not common to both series A and series B?

Get all items of ser1 and ser2 not common to both.

8. How to get the minimum, 25th percentile, median, 75th, and max of a numeric series?

Difficuty Level: L2

Compute the minimum, 25th percentile, median, 75th, and maximum of ser .

9. How to get frequency counts of unique items of a series?

Calculte the frequency counts of each unique value ser .

10. How to keep only top 2 most frequent values as it is and replace everything else as ‘Other’?

From ser , keep the top 2 most frequent items as it is and replace everything else as ‘Other’.

11. How to bin a numeric series to 10 groups of equal size?

Bin the series ser into 10 equal deciles and replace the values with the bin name.

Desired Output

12. How to convert a numpy array to a dataframe of given shape? (L1)

Reshape the series ser into a dataframe with 7 rows and 5 columns

13. How to find the positions of numbers that are multiples of 3 from a series?

Find the positions of numbers that are multiples of 3 from ser .

14. How to extract items at given positions from a series

From ser , extract the items at positions in list pos .

15. How to stack two series vertically and horizontally ?

Stack ser1 and ser2 vertically and horizontally (to form a dataframe).

16. How to get the positions of items of series A in another series B?

Get the positions of items of ser2 in ser1 as a list.

17. How to compute the mean squared error on a truth and predicted series?

Compute the mean squared error of truth and pred series.

18. How to convert the first character of each element in a series to uppercase?

Change the first character of each word to upper case in each word of ser .

19. How to calculate the number of characters in each word in a series?

20. how to compute difference of differences between consequtive numbers of a series.

Difference of differences between the consequtive numbers of ser .

21. How to convert a series of date-strings to a timeseries?

Difficiulty Level: L2

22. How to get the day of month, week number, day of year and day of week from a series of date strings?

Get the day of month, week number, day of year and day of week from ser .

Desired output

23. How to convert year-month string to dates corresponding to the 4th day of the month?

Change ser to dates that start with 4th of the respective months.

24. How to filter words that contain atleast 2 vowels from a series?

Difficiulty Level: L3

From ser , extract words that contain atleast 2 vowels.

25. How to filter valid emails from a series?

Extract the valid emails from the series emails . The regex pattern for valid emails is provided as reference.

26. How to get the mean of a series grouped by another series?

Compute the mean of weights of each fruit .

27. How to compute the euclidean distance between two series?

Compute the euclidean distance between series (points) p and q, without using a packaged formula.

28. How to find all the local maxima (or peaks) in a numeric series?

Get the positions of peaks (values surrounded by smaller values on both sides) in ser .

29. How to replace missing spaces in a string with the least frequent character?

Replace the spaces in my_str with the least frequent character.

30. How to create a TimeSeries starting ‘2000-01-01’ and 10 weekends (saturdays) after that having random numbers as values?

31. how to fill an intermittent time series so all missing dates show up with values of previous non-missing date.

ser has missing dates and values. Make all missing dates appear and fill up with value from previous date.

32. How to compute the autocorrelations of a numeric series?

Compute autocorrelations for the first 10 lags of ser . Find out which lag has the largest correlation.

33. How to import only every nth row from a csv file to create a dataframe?

Import every 50th row of BostonHousing dataset as a dataframe.

34. How to change column values when importing csv to a dataframe?

Import the boston housing dataset , but while importing change the 'medv' (median house value) column so that values < 25 becomes ‘Low’ and > 25 becomes ‘High’.

35. How to create a dataframe with rows as strides from a given series?

36. how to import only specified columns from a csv file.

Import ‘crim’ and ‘medv’ columns of the BostonHousing dataset as a dataframe.

37. How to get the n rows, n columns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.

Get the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent of the dataframe.

38. How to extract the row and column number of a particular cell with given criterion?

Which manufacturer, model and type has the highest Price ? What is the row and column number of the cell with the highest Price value?

39. How to rename a specific columns in a dataframe?

Rename the column Type as CarType in df and replace the ‘.’ in column names with ‘_’.

Desired Solution

40. How to check if a dataframe has any missing values?

Check if df has any missing values.

41. How to count the number of missing values in each column?

Count the number of missing values in each column of df . Which column has the maximum number of missing values?

42. How to replace missing values of multiple numeric columns with the mean?

Replace missing values in Min.Price and Max.Price columns with their respective mean.

43. How to use apply function on existing columns with global variables as additional arguments?

Difficulty Level: L3

In df , use apply method to replace the missing values in Min.Price with the column’s mean and those in Max.Price with the column’s median.

Use Hint from StackOverflow

44. How to select a specific column from a dataframe as a dataframe instead of a series?

Get the first column ( a ) in df as a dataframe (rather than as a Series).

45. How to change the order of columns of a dataframe?

Actually 3 questions.

Create a generic function to interchange two columns, without hardcoding column names.

Sort the columns in reverse alphabetical order, that is colume 'e' first through column 'a' last.

46. How to set the number of rows and columns displayed in the output?

Change the pamdas display settings on printing the dataframe df it shows a maximum of 10 rows and 10 columns.

47. How to format or suppress scientific notations in a pandas dataframe?

Suppress scientific notations like ‘e-03’ in df and print upto 4 numbers after decimal.

48. How to format all the values in a dataframe as percentages?

Format the values in column 'random' of df as percentages.

49. How to filter every nth row in a dataframe?

From df , filter the 'Manufacturer' , 'Model' and 'Type' for every 20th row starting from 1st (row 0).

50. How to create a primary key index by combining relevant columns?

In df , Replace NaN s with ‘missing’ in columns 'Manufacturer' , 'Model' and 'Type' and create a index as a combination of these three columns and check if the index is a primary key.

51. How to get the row number of the nth largest value in a column?

Find the row position of the 5th largest value of column 'a' in df .

52. How to find the position of the nth largest value greater than a given value?

In ser , find the position of the 2nd largest value greater than the mean.

53. How to get the last n rows of a dataframe with row sum > 100?

Get the last two rows of df whose row sum is greater than 100.

54. How to find and cap outliers from a series or dataframe column?

Replace all values of ser in the lower 5%ile and greater than 95%ile with respective 5th and 95th %ile value.

55. How to reshape a dataframe to the largest possible square after removing the negative values?

Reshape df to the largest possible square with negative values removed. Drop the smallest values if need be. The order of the positive numbers in the result should remain the same as the original.

56. How to swap two rows of a dataframe?

Swap rows 1 and 2 in df .

57. How to reverse the rows of a dataframe?

Reverse all the rows of dataframe df .

58. How to create one-hot encodings of a categorical variable (dummy variables)?

Get one-hot encodings for column 'a' in the dataframe df and append it as columns.

59. Which column contains the highest number of row-wise maximum values?

Obtain the column name with the highest number of row-wise maximum’s in df .

60. How to create a new column that contains the row number of nearest column by euclidean distance?

Create a new column such that, each row contains the row number of nearest row-record by euclidean distance.

61. How to know the maximum possible correlation value of each column against other columns?

Compute maximum possible absolute correlation value of each column against other columns in df .

62. How to create a column containing the minimum by maximum of each row?

Compute the minimum-by-maximum for every row of df .

63. How to create a column that contains the penultimate value in each row?

Create a new column 'penultimate' which has the second largest value of each row of df .

64. How to normalize all columns in a dataframe?

  • Normalize all columns of df by subtracting the column mean and divide by standard deviation.
  • Range all columns of df such that the minimum value in each column is 0 and max is 1.

Don’t use external packages like sklearn.

65. How to compute the correlation of each row with the suceeding row?

Compute the correlation of each row of df with its succeeding row.

66. How to replace both the diagonals of dataframe with 0?

Replace both values in both diagonals of df with 0.

67. How to get the particular group of a groupby dataframe by key?

This is a question related to understanding of grouped dataframe. From df_grouped , get the group belonging to 'apple' as a dataframe.

68. How to get the n’th largest value of a column when grouped by another column?

In df , find the second largest value of 'taste' for 'banana'

69. How to compute grouped mean on pandas dataframe and keep the grouped column as another column (not index)?

In df , Compute the mean price of every fruit , while keeping the fruit as another column instead of an index.

70. How to join two dataframes by 2 columns so they have only the common rows?

Join dataframes df1 and df2 by ‘fruit-pazham’ and ‘weight-kilo’.

71. How to remove rows from a dataframe that are present in another dataframe?

From df1 , remove the rows that are present in df2 . All three columns must be the same.

72. How to get the positions where values of two columns match?

73. how to create lags and leads of a column in a dataframe.

Create two new columns in df , one of which is a lag1 (shift column a down by 1 row) of column ‘a’ and the other is a lead1 (shift column b up by 1 row).

74. How to get the frequency of unique values in the entire dataframe?

Get the frequency of unique values in the entire dataframe df .

75. How to split a text column into two separate columns?

Split the string column in df to form a dataframe with 3 columns as shown.

To be continued . .

More Articles

How to convert python code to cython (and speed up 100x), how to convert python to cython inside jupyter notebooks, install opencv python – a comprehensive guide to installing “opencv-python”, install pip mac – how to install pip in macos: a comprehensive guide, scrapy vs. beautiful soup: which is better for web scraping, add python to path – how to add python to the path environment variable in windows, similar articles, complete introduction to linear regression in r, how to implement common statistical significance tests and find the p value, logistic regression – a complete tutorial with examples in r.

Subscribe to Machine Learning Plus for high value data science content

© Machinelearningplus. All rights reserved.

python assignments for practice

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free sample videos:.

python assignments for practice

Interested in a verified certificate or a professional certificate ?

An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and “debug” it. Designed for students with or without prior programming experience who’d like to learn Python specifically. Learn about functions, arguments, and return values (oh my!); variables and types; conditionals and Boolean expressions; and loops. Learn how to handle exceptions, find and fix bugs, and write unit tests; use third-party libraries; validate and extract data with regular expressions; model real-world entities with classes, objects, methods, and properties; and read and write files. Hands-on opportunities for lots of practice. Exercises inspired by real-world programming problems. No software required except for a web browser, or you can write code on your own PC or Mac.

Whereas CS50x itself focuses on computer science more generally as well as programming with C, Python, SQL, and JavaScript, this course, aka CS50P, is entirely focused on programming with Python. You can take CS50P before CS50x, during CS50x, or after CS50x. But for an introduction to computer science itself, you should still take CS50x!

How to Take this Course

Even if you are not a student at Harvard, you are welcome to “take” this course for free via this OpenCourseWare by working your way through the course’s ten weeks of material. If you’d like to submit the course’s problem sets and final project for feedback, be sure to create an edX account , if you haven’t already. Ask questions along the way via any of the course’s communities !

  • If interested in a verified certificate from edX , enroll at cs50.edx.org/python instead.
  • If interested in a professional certificate from edX , enroll at cs50.edx.org/programs/python (for Python) or cs50.edx.org/programs/data (for Data Science) instead.

How to Teach this Course

If you are a teacher, you are welcome to adopt or adapt these materials for your own course, per the license .

IMAGES

  1. Python Assignments & Variables ||| Python Tutorial ||| Python

    python assignments for practice

  2. 21 Python Short hand or Assignments Operator

    python assignments for practice

  3. Python Syntax Essentials and Best Practices

    python assignments for practice

  4. 16 Python_ Assignments

    python assignments for practice

  5. # 11 Variable Assignments in Python

    python assignments for practice

  6. Simple Python Exercises For Beginners

    python assignments for practice

VIDEO

  1. Assignment

  2. Assignment

  3. Multiple assignments in Python #coding #codingtips #python

  4. Coding assignments, #python, #beginner

  5. Assignment

  6. Assignment

COMMENTS

  1. Python Exercises, Practice, Challenges

    Practice Python basics, data structure, data analytics, and more with 18 free coding exercises for Python developers. Each exercise has 10-20 questions with solutions and explanations. Test your skills online and learn from the tips and hints.

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

  3. Python Exercises

    Test your Python skills with interactive exercises for each chapter. Fill in the missing code, get instant feedback and track your score.

  4. Exercises and Solutions

    Learn Python programming with interactive exercises and solutions. Choose from 40 topics, such as character input, odd or even, list comprehensions, and more.

  5. Python Online Practice: 79 Unique Coding Exercises (2023)

    Learn Python online by writing actual code with interactive exercises, courses, projects, and tutorials. Practice the basics, data analysis, data cleaning, machine learning, and more. Sign up for a free account and get access to 79 ways to practice Python online.

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

    Edabit offers over 2,500 Python challenges for different levels and topics, from language fundamentals to algorithms. You can type your code, check your answer, and see the solutions in the Resources and Solutions tabs.

  7. 10 Python Practice Exercises for Beginners with Solutions

    Learn Python programming skills with 10 exercises designed to challenge you and expose you to new concepts. Each exercise has a solution with explanations and tips to help you improve your coding. Topics include user input, looping, functions, strings, and more.

  8. Python exercises on Exercism

    Code practice and mentorship for everyone. Develop fluency in 69 programming languages with our unique blend of learning, practice and mentoring. Exercism is fun, effective and 100% free, forever. Explore the 140 Python exercises on Exercism.

  9. Python Projects

    1. 2. ». Explore project-based Python tutorials and gain practical coding skills. Work on Python projects that help you gain real-world programming experience. These projects include full source code and step-by-step instructions, and will make you more confident in tackling real-world coding challenges.

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

    Python Practice Problem 1: Sum of a Range of Integers. Let's start with a warm-up question. In the first practice problem, you'll write code to sum a list of integers. Each practice problem includes a problem description. This description is pulled directly from the skeleton files in the repo to make it easier to remember while you're ...

  11. Python Basic Exercise for Beginners with Solutions

    This Python essential exercise is to help Python beginners to learn necessary Python skills quickly.. Immerse yourself in the practice of Python's foundational concepts, such as loops, control flow, data types, operators, list, strings, input-output, and built-in functions.

  12. py.CheckiO

    py.CheckiO - Python practice online. Improve your coding skills by solving coding challenges and exercises online with your friends in a fun way. ... Exchanges experience with other users online through fun coding activities. Python Practice Online. More than 500 missions cover multiple topics with different levels of complexity. And translated ...

  13. Python Exercise with Practice Questions and Solutions

    Learn Python using sets of detailed programming questions from basic to advanced. This web page covers various topics and applications of Python with chapter-wise exercises and solutions.

  14. Solve Python

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

  15. 25 Python Projects for Beginners

    Python Projects You Can Build. Mad Libs. Guess the Number Game (computer) Guess the Number Game (user) Rock, paper, scissors. Hangman. Countdown Timer. Password Generator. QR code encoder / decoder.

  16. Python Exercises. Free Resources. Practity

    Moreover, Python practice gives you the opportunity to practice and reinforce what you have learned. It is one thing to read about programming concepts, but it is another thing entirely to actually implement them in code. ... 40 Assignments + 2 projects + exam: Practice the Math module, quadratic formula, random function, nims/stones games ...

  17. 35 Python Programming Exercises and Solutions

    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.

  18. 59 Fun Python Project Ideas for Beginners in 2024

    Guessing Game — This is another beginner-level project that'll help you learn and practice the basics. Mad Libs — Use Python code to make interactive Python Mad Libs! Hangman — Another childhood classic that you can make to stretch your Python skills. Snake — This is a bit more complex, but it's a classic (and surprisingly fun) game ...

  19. Python Functions Exercise with Solution [10 Programs]

    This Python functions exercise aims to help Python developers to learn and practice how to define functions. Also, you will practice how to create and use the nested functions and the function arguments effectively. ... It contains Python function assignments, programs, questions, and challenges. Total 10 questions. The solution is provided for ...

  20. Python Exercises, Practice, Solution

    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.

  21. 101 Pandas Exercises for Data Analysis

    101 python pandas exercises are designed to challenge your logical muscle and to help internalize data manipulation with python's favorite package for data analysis. The questions are of 3 levels of difficulties with L1 being the easiest to L3 being the hardest. 101 Pandas Exercises. Photo by Chester Ho. You might also like to practice … 101 Pandas Exercises for Data Analysis Read More »

  22. CS50's Introduction to Programming with Python

    An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and "debug" it. Designed for students with or without prior programming experience who'd like to learn Python specifically. Learn about functions, arguments, and return values (oh my!); variables and types; conditionals ...