Bites of Py Exercises

Hone your Python skills by coding and verifying exercises in the comfort of your browser.

 ... or click on one below to get started πŸ’ͺ ... or code a Random Bite

Bite Tags User difficulty More info / forum

101. f-strings and a simple if/else

The latest way to print to the screen in Python (>= 3.6) is with f-strings.In this Bite we'll get you …

f-strings if/else ⚬⚬⚬⚬

102. Infinite loop, input, continue and break

In this Bite we'll get you to take user input using the input builtin and see if it matches items …

break continue input

mock.patch while

103. Loop through a dictionary and pluralise a word

You're given a dictionary of people and the number of games they've won.Use a for loop to iterate over the …

dict looping ⚬⚬⚬

104. Split and join

Split up the message on newline (\n) using the split builtin, then use the join builtin to stitch it together …

join split ⚬⚬⚬

105. Slice and dice

Take the block of text provided and strip off the whitespace at both ends. Split the text by newline (\n).Loop …

replace slicing split

string module strip

106. Strip out vowels and count the number of replacements

In this Bite we'd like you to loop over the characters in the large block of text (the most important …

counting regular expressions replace

string manipulation Zen of Python

107. Filter numbers with a list comprehension

Complete the function below that receives a list of numbers and returns only the even numbers that are > 0 …

list comprehensions modulo ⚬⚬

108. Loop over a dict of namedtuples calculating a total score

In this Bite you calculate the total amount of points earned with Ninja Belts by accessing the given ninja_belts dict.You …

counting dict namedtuple


109. Workout dict lookups and raising an exception

In this Bite you learn how to lookup values from a dictionary or in Python: dict.You are presented with workout_schedule …

dict exception handling format

string manipulation ternary

110. Type conversion and exception handling

In this Bite you complete the divide_numbers function that takes a numerator and a denominator (the number above and below …

exception handling raise type casting


Bite Tags User difficulty More info / forum

1. Sum n numbers

Write a function that can sum up numbers:It should receive a list of n numbers. If no argument is provided, …

default args None range


5. Parse a list of names

In this bite you will work with a list of names.First you will write a function to take out duplicates …

lambda list comprehensions min


8. Rotate string characters

Write a function that rotates characters in a string, in both directions:if n is positive move characters from beginning to …

deque slicing ⚬⚬⚬⚬

15. Enumerate 2 sequences

Iterate over the given names and countries lists, printing them prepending the number of the loop (starting at 1). Here …

enumerate string formatting ⚬⚬⚬⚬⚬

16. PyBites date generator

Write a generator that returns special dates for PyBites: Every year mark counting from PYBITES_BORN date (so 19th of Dec …

datetime generators ⚬⚬⚬⚬⚬⚬

19. Write a simple property

Write a simple Promo class. Its constructor receives a name str and expires datetime.Add a property called expired which returns …

datetime properties ⚬⚬⚬⚬⚬

21. Query a nested data structure

Given the provided cars dictionary:Get all JeepsGet the first car of every manufacturer.Get all vehicles containing the string Trail in …

data structures dictionary comprehensions list comprehensions


26. Dictionary comprehensions are awesome

A dictionary comprehension is like a list comprehension, but it constructs a dict instead of a list. They are convenient …

dictionary comprehensions ⚬⚬⚬

29. Martin's IQ test

Martin is preparing to pass an IQ test.The most frequent task in this test is to find out which one …

enumerate string module ⚬⚬⚬⚬

32. Don't let mutability fool you

In this Bite you are presented with a function that copies the given items data structure.There is a problem though, …

deepcopy mutability ⚬⚬

37. Rewrite a for loop using recursion

Although you have to be careful using recursion it is one of those concepts you want to at least understand. …

recursion reverse ⚬⚬⚬

38. Using ElementTree to parse XML

In this Bite you will use ElementTree to parse some Nolan movies we extracted from OMDb.Luckily most APIs switched to …

movie data xml ⚬⚬⚬⚬⚬

43. Force keyword arguments

Write a function called get_profile that can only allows 2 keyword arguments: name and profession which default to julian and …

function arguments kwargs ⚬⚬⚬⚬

44. License key generator

Write a function called gen_key that creates a license key with this format: KI80OMZ7-5OGYC1AC-735LDPT1-4L11XU1UThe key consists of a combination of …

list comprehensions secrets string module


45. Keep a queue of last n items

How about writing a queue that holds the last 5 items? Queue follows First-In-First-Out methodology, i.e., the data item stored …

deque ⚬⚬⚬⚬

46. You are a programmer! Code Fizz Buzz

Here is a beginner Bite to write Fizz Buzz: Fizz buzz is a group word game for children to teach …

fizzbuzz ⚬

54. Nicer formatting of a poem or text

In this Bite you complete print_hanging_indents to print a poem (or text) in a nicer way. For example calling it …

string manipulation textwrap ⚬⚬⚬⚬⚬

55. Get the latest game releases from Steam's RSS feed

The Steam gaming platform has an RSS feed of their latest game releases. In this Bite, you'll pull down and …

feedparser namedtuple ⚬⚬

56. Add a command line interface to our BMI calculator

Complete create_parser below so that our BMI program can be called like this: $ python -h usage: [-h] …

argparse ⚬⚬⚬⚬

64. Fix a truncating zip function

Bert is in charge of organizing an event and got the attendees names, locations and confirmations in 3 lists. Assuming …

itertools zip ⚬⚬⚬

66. Calculate the running average of a sequence

Write a function that takes a sequence of items and returns the running average, so for example this: running_mean([1, 2, …

enumerate mean ⚬⚬⚬

67. Working with datetimes

This Bite involves solving two problems using datetime:We kicked off our 100 Days of Code project on March 30th, 2017. …

datetime timedelta ⚬⚬⚬

68. Remove punctuation characters from a string

Complete remove_punctuation which receives an input string and strips out all punctuation characters (!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~).Return the resulting string. You can go …

string manipulation string module ⚬

74. What day of the week were you born on?

Complete weekday_of_birth_date which takes a date object of a birthday and returns the corresponding weekday string.For example Bob and Julian's …

calendar ⚬⚬

77. New places to travel to

You want to find people who have as much exposure to different cultures as yourself.Complete the uncommon_cities helper that takes …

set set operations ⚬⚬

80. Check equality of two lists

In this Bite we compare two list objects for equality, a fundamental thing to understand in Python.Complete the check_equality function …

enum equality list


83. At what time does PyBites live?

Get to know pytz! pytz brings the Olson tz database into Python (docs). Let's see how many hours Bob and …

pytz timezones ⚬⚬⚬

91. Matching multiple strings

Catching up after #PyCon2018 ... in this Bite you do multiple string matching. Complete contains_only_vowels, contains_any_py_chars, and contains_digits below. See …

all any re

string matching

96. Build Unix' wc program in Python

In this Bite you will convert Unix' wc command into Python. Your function takes a file (absolute path), reads it …

file processing tempfile Unix


100. Display the last part of a file (Unix tail)

Complete the function below simulating Unix' tail, for example: $ tail -3 # byte to str conversion and strip …

file processing slicing strip


115. Count leading spaces

A small but interesting Bite: given a string with leading indent spacing, calculate the amount of space (literal space, not …

counting string matching ⚬

117. Round a number even (a.k.a. banker's rounding)

Bankers Rounding is an algorithm for rounding quantities to integers, in which numbers which are equidistant from the two nearest …

Decimal rounding ⚬⚬

128. Work with datetime's strptime and strftime

In this Bite you get some more practice with datetime's useful strptime and stftime.Complete the two functions: years_ago and convert_eu_to_us_date …

datetime strftime strptime


130. Analyze some basic Car Data

In this exercise you will analyze some basic car data. Here is the (fake) JSON data we created with Mockeroo …

Counter data analysis list comprehensions


133. Convert an Amazon URL into an affiliation link

Can you help PyBites automate their Amazon affiliation link creation?Complete the generate_affiliation_link(url) function below which should convert the following links: …

regular expressions string manipulation ⚬

136. Bloodtypes

Check red blood cell compatibility between donor and recipient. For simplicity, only eight basic types of blood are considered. The …

enum exception handling multi type input


143. Look up a value in 3 dictionaries

In this Bite you are presented with 3 dictionaries. Complete get_person_age that takes a name as argument and returns the …

collections dict ⚬⚬

149. Sorting words with constraint

Here is a list of words Jacob is trying to sort: >>> words = "It's almost Holidays and PyBites wishes …

lambda sorting string manipulation


153. Round a sequence of numbers

It's time to get mathematical! In this Bite we ask that you complete the round_up_or_down function that receives a transactions …

list comprehensions math rounding


161. Count the number of files and directories

Complete count_dirs_and_files traversing the passed in directory path.Return a tuple of (number_of_directories, number_of_files)Let's use the tree command to show an …

counting directories files

os module

165. Parse an /etc/passwd file output

The /etc/passwd file is a text-based database of information about users that may log into the system or other operating …

split string manipulation tuple unpacking


167. Complete a User class: properties and representation dunder methods

In this Bite you are presented with another class, User this time. Like last Bite you are asked to complete …

classes dunder methods f-strings

properties __repr__ __str__ string manipulation

169. Simple length converter

Your task is to complete the convert() function. It's purpose is to convert centimeters to inches and vice versa. As …

exception handling numbers rounding


172. Having fun with Python Partials

Meet another gem in the standard library: functools, which contains tools for functional-style programming.In this Bite you will play with …

functools partial rounding


176. Create a variable length chessboard

In this Bite you are going to print a chessboard to stdout (use print).Complete create_chessboard that takes an optional argument …

modulo range stdout


180. Group names by country

In this Bite you are presented with a list of surnames, names, and countries. These 3 fields are in a …

collections defaultdict groupby


181. Keep a list sorted upon insert

Complete the add method of the OrderedList class which takes a num argument and adds that to the self._numbers list …

bisect classes data structures


188. Get statistics from PyBites test code

Did you know Python has a statistics module?For this Bite we did a line count on our test code for …

data analysis file processing statistics


189. Filter a list of names

Here is a Bite to practice the continue and break statements in Python.Complete filter_names that takes a list of names …

break continue generators


192. Some logging practice

This is a simple logging exercise. The logging module is very useful and is part of the standard library; unfortunately …

callable logging ⚬⚬⚬⚬

201. Call a Cisco Nexus 9k device

Cisco Nexus 9k devices is one of the first network equipment with comprehensive API programmatic access from Cisco. API capabilities …

networking requests ⚬⚬⚬⚬⚬⚬⚬⚬

208. Find the number pairs summing up N

In this Bite you complete find_number_pairs which receives a list of numbers and returns all the pairs that sum up …

itertools looping numbers


209. Write a Sphinx docstring

Your team uses Sphinx and wants you to comply with its standards for docstrings. As per the Sphinx-RTD-Tutorial a typical …

data types docstring sphinx


210. Add Type Annotations

Continuing from where we left off in Bite 209, use the docstring you wrote in last Bite to add type …

annotations typing

214. A countdown generator

Write a simple generator that counts from 100 to 1. It can just return the ints one by one, no …

generators ⚬⚬

215. Validate a license key

Complete the validate_license function writing a regular expression that matches a PyBites license key which: Starts with PB, following 4 …

bool regular expressions ⚬⚬⚬⚬

218. Create a sandwich decorator

After creating our Decorators and Context Managers learning path we realized we did not have a beginner decorator Bite, so …

decorators ⚬⚬⚬⚬⚬

225. Swap case PyBites characters

In this Bite you will swap case all pybites characters (both lower- and upper case) for a given text.Not much …

looping string manipulation string parsing


Bite Tags User difficulty More info / forum

3. Word Values

Calculate the dictionary word that would have the most value in Scrabble.There are 3 tasks to complete for this Bite:First …

max Scrabble sum


30. Movie data analysis

In this Bite we are going to parse a csv movie dataset to identify the directors with the highest rated …

data analysis defaultdict mean

movie data namedtuple sorting

4. Top 10 PyBites tags

Get the top 10 blog tags of PyBites (e.g. python, flask, django, learning). Our tests suppose you will use a …

Counter findall regular expressions


6. PyBites Die Hard

Given a listing of files of our community branch determine who PR'd (= submitted pull request) the most (excluding PyBites) …

Counter file processing generators


7. Parsing dates from logs

In this bite we will look at this small server log finding the first and last system shutdown events: INFO …

datetime file processing ⚬⚬⚬⚬⚬⚬

9. Palindromes

Write a function to determine if a word (or phrase) is a palindrome.Then write a second function to receive a …

list comprehensions max reverse


10. Practice exceptions

In this bite you learn to catch/raise exceptions.Write a simple division function meeting the following requirements:when denominator is 0 catch …

exception handling raise ⚬⚬⚬⚬

12. Write a user validation function

Create a function that takes a username and checks for a valid user:The username is in USERS,the user is not …

classes exception handling namedtuple


13. Convert dict to namedtuple/json

Write a function to convert the given blog dict to a namedtuple.Write a second function to convert the resulting namedtuple …

dict json namedtuple


14. Generate a table of n sequences

Write a function that receives one or more sequences. The sequences are already defined for you.The function should return a …

generators zip ⚬⚬⚬⚬⚬

17. Form teams from a group of friends

Write a function called friends_teams that takes a list of friends, a team_size (type int, default=2) and order_does_matter (type bool, …

itertools ⚬⚬⚬⚬

18. Find the most common word

Write a function that returns the most common (non stop)word in this Harry Potter text.Make sure you strip out non-alphanumeric …

Counter data analysis list comprehensions


22. Write a decorator with argument

Write a decorator called make_html that wraps text inside one or more html tags. As shown in the tests decorating …

decorators ⚬⚬⚬⚬⚬⚬

25. No promo twice, keep state in a class

In this bite a real world scenario: PyBites has a growing set of Bites and gives away promos. They choose …

classes exception handling properties


27. Parse omdb movie json data

Working with APIs is very common these days and lucky for us they increasingly return JSON (over XML). We saved …

APIs glob json

movie data

28. Converting date strings to datetimes

In this Bite you are provided with a list of publish dates of all our PyBites blog posts. They are …

Counter datetime findall


33. Transpose a data structure

Sometimes you need to restructure a nested data structure. For example you can convert a dict in a list of …

dict zip ⚬⚬⚬⚬⚬

35. Having fun with heapq

In this Bite you are provided with 3 data structures: a list of ints, a list of datetimes, and a …

datetime heapq ⚬⚬⚬

36. Having fun with *args and **kwargs

Write a function called get_profile that takes:a required name,a required age,one or more optional sports (args),one or more optional awards …

args function arguments kwargs


39. Calculate the total duration of a course

In this Bite you read in a text file with course times (MM:SS) per video.You extract these and calculate the …

datetime findall numbers


41. Write a login_required decorator

If you worked with Flask or Django you must have seen routes being decorated to enforce authentication.In this Bite you …

decorators ⚬⚬⚬⚬

47. Write a new password field validator

You know these Create a new password forms? They do a lot of checks to make sure you make a …

re string module ⚬⚬⚬

48. Make a bar chart of new Safari books

Some time ago we made a little Slack bot to post new titles added to Safari to Slack. And luckily …

bar chart data analysis ⚬⚬⚬⚬

49. Scrape Packt's html with BeautifulSoup

In this Bite you will parse Packt's free learning ebook site extracting the html for the daily free ebook: As …

beautifulsoup namedtuple requests


51. When does Python 2 die on Planet Miller?

Imagine you landed on Planet Miller (from the movie Interstellar) where 1 hour takes 7 Earth years (known as the …

datetime ⚬⚬⚬⚬

57. Create a simple calculator that receives command line arguments

In this Bite you write a simple calculator that can perform additions (add), subtractions (sub), multiplications (mul) and divisions (div).You …

argparse functools reduce


59. Create a multiplication table class of variable length

Danny does not like rote learning (nor do we!). He is asked to remember multiplication tables of considerable size 😭Can …

classes dunder methods exception handling


60. Create a deck of Uno cards

In this Bite you will create a deck of Uno cards. Here is the equipment requirement as described here - …

list list comprehensions namedtuple


62. Data structures matter - speed up your Python code

In this Bite we provide you with 5 functions which you have to try to make faster. Some require different …

data structures performance ⚬⚬⚬

65. Get all valid dictionary words for a draw of letters

This Bite focusses on the use of itertools. To that extend you complete get_possible_dict_words and _get_permutations_draw to get all valid …

itertools Scrabble ⚬⚬⚬⚬⚬⚬

70. Create your own iterator

In this Bite you make an iterator called EggCreator by implementing the __iter__ and __next__ dunder methods (as dictated by …

iterators random ⚬⚬⚬

71. Keep state in a class + make its instance callable

In this Bite you write a small class to keep track of the max score in a game. When called …

classes dunder methods ⚬⚬⚬⚬

72. Retrieve the right Ninja Belt based on score

As you have probably seen on the new dashboard you can now gain Ninja Belts based on the amount of …

itertools OrderedDict ⚬⚬⚬⚬

73. Organize a meeting between timezones (pytz)

Help PyBites community friends find a reasonable common time to meet!Complete the function below receiving a UTC datetime and one …

pytz timezones ⚬⚬⚬⚬⚬

78. Find programmers with common languages

Similar as last Bite we do another comparison of sequences exercise.Here is the deal: you are in charge of huge …

set set operations ⚬⚬⚬

79. Parse a csv file and create a bar chart

We played a bit with the Slack API today and wow: our PyBites community is super international! We really enjoy …

bar chart community csv


81. Filter and order tweets by polarity values

In this Bite we collected some random tweets and populated a list of namedtuples of text and a polarity rating …

namedtuple TextBlob Twitter


82. Define a Score Enum and customize it adding methods

Starting Python 3.4 there is support for enumerations (not to confuse with the enumerate builtin). You can define a class …

classmethod enum __str__


84. Flatten lists recursively (Droste Bite)

Complete flatten that takes a list of lists (which can have lists ad infinitum) and flatten them into a one …

list recursion ⚬⚬⚬⚬

86. Create a RGB-to-Hex converter

Designer Mary wants to convert her CSS from statements like background-color: rgb(128, 128, 0); to: background-color: #808000;.Don't worry, you don't …

string formatting ⚬⚬⚬

87. Convert Decimal to Roman Numerals

Complete romanize that takes a decimal number and converts it to its Roman Numeral equivalent.If a non int or invalid …

numbers OrderedDict ⚬⚬⚬⚬

89. Playing with lists and dicts

In this Bite you are presented with a us_state_abbrev dict and a states list.Complete the four methods in the template …

data structures dict list


90. What South Park characters talk most?

Did we already tell you we love the collections module? In this Bite we combine its defaultdict and Counter data …

Counter csv data analysis

defaultdict requests

92. Humanize a datetime

In this Bite you will convert a timedelta object into something readable. We know: there are modules to do it, …

datetime namedtuple ⚬⚬⚬⚬⚬⚬

95. Subclass the dict built-in

In this Bite you will subclass the dict built-in to support a birthday dictionary.This dictionary takes names as keys and …

classes inheritance ⚬⚬⚬⚬⚬

97. BeautifulSoup II - scrape US holidays

In this Bite we use BeautifulSoup to scrape US holidays from OfficeHolidays to make a lookup of holidays per month.Check …

beautifulsoup defaultdict dict


99. Write an infinite sequence generator

Write a generator that produces the sequence [1, 'A', 2, 'B', 3, 'C', ... 'X', 25, 'Y', 26, 'Z'] infinitely. …

generators itertools string module


111. Use the ipinfo API to lookup IP country

In this Bite you will use the requests library to make a GET request to the ipinfo service.Use IPINFO_URL and …

APIs json mock.patch


113. Filter words with non-ascii characters

In this Bite you extract words from a text that contain non-ascii characters. So Fichier non trouvΓ© would return a …

all ascii ord


114. Implement a Color class with classmethods

As the new junior developer, you have been charged with enhancing the Color class. Your task will be to implement …

classmethod hex __repr__

__str__ string module

116. List and filter files in a directory

In this Bite you complete get_files that receives a dirname and size_in_kb (note kb, not bytes).There are two things you …

generators glob os module


118. List exercise: return first occurrence indices of duplicated words

In this Bite you are presented with a list of words. Loop through them and find all the words that …

counting list comprehensions set


119. Xmas tree generator

In this Bite you complete generate_xmas_tree that takes a rows arg (= height of the tree). For each row you …

default args join range

string formatting

120. Write a numbers validation decorator

Let's get some more practice with decorators ... in this Bite you will write a decorator that checks if input …

decorators ⚬⚬⚬

122. Check if two words are anagrams

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using …

anagram string matching ⚬⚬⚬⚬

123. Find the user with most friends

In this Bite you are presented with a users dict of keys=id's and values=usernames and a friendships list of user …

defaultdict looping sorting


125. Get the most recommended books

The Tim Ferriss Show is full of wisdom and inspiration. It can also fill up your book shelves because a …

beautifulsoup Counter default args

list comprehensions requests

127. Return the right ordinal suffix for a number

In this Bite you complete a function that takes an int and returns it appended with the right suffix: 1 …

dict modulo numbers

string manipulation

129. Analyze Stock Data

In this Bite we will answer some questions about stocks, using some JSON data obtained from the awesome Mockeroo fake …

counting data analysis json

requests sorting string manipulation

132. Find the word with the most vowels

Finish the get_word_max_vowels function below that takes a text string as its input argument and returns a tuple of the …

counting lambda list comprehensions

string matching

135. Sort a list of book objects

In this Bite you are going to look at a list of Book namedtuples and sort them by various criteria. …

attrgetter datetime lambda

list namedtuple operator sorting

137. Gourmets' Nightmare

Many gourmets struggle to find the perfect pairing of wines and cheeses. A number of considerations are relevant, each of …

Counter intersection operator


138. OOP fun at the Zoo

Finish the Animal class below adding one or more class variables and a classmethod so that the following code: dog …

classes classmethod itertools


140. PyBites First Pandas Bite

This is a Pandas proof-of-concept Bite. We just added the library to our platform! For this Bite you find out …

csv data analysis pandas


141. Primitive date format inferrer

Complete the get_dates method given the following:a listing of date strings in unknown date format andan enum class which contains …

classmethod datetime enum

exception handling

142. Exception Handling: Calculate the Winning Player

Complete the two functions below: calculate_score takes a list of dice roll scores and returns the total score only taking …

exception handling namedtuple numbers


144. Calculate the Number of Months Passed

Some more fun working with dates! In this Bite you will calculate the number of months between the fixed START_DATE …

datetime dateutil exception handling


146. Rhombus generator

In this Bite you make a generator of rhombus shapes. You will complete gen_rhombus that when called like this: gen …

format f-strings string formatting


147. 100 WEEKDays of Code Date Range

Doing a #100DaysOfCode can be challenging, and some of it is because you dedicate to do it on workdays AND …

datetime dateutil ⚬⚬⚬⚬

148. Print Car Data Grouped by Manufacturer

In this Bite you are presented with a list of car (manufacturer, model) tuples. Group the data by manufacturer printing …

data structures itertools operator


150. Turn messy CSV into JSON

At the 1 year mark of our platform here is Bite 150! In this Bite you are presented with some …

csv json re

string manipulation

151. Contemporary Composers

You are given a list of operas and a list of composers. For two given composers find operas (where one …

datetime dict exception handling

generators namedtuple

154. Write your own Data Class

As you might have noticed we are now on Python 3.7 so time for a Bite on data classes which …

data classes data structures hashable

sorting type hinting

155. Split a string by spaces or quoted text

Another text manipulation Bite. Code split_words_and_quoted_text that takes a text string and splits it by space, except words that are …

split string manipulation ⚬⚬⚬

156. Make an index of story characters

You know the index at the end of a book where you look up which pages people and terms occur? …

collections defaultdict enumerate

sorting string matching

157. Filter out accented characters

Another unicode Bite. Given some non-English text with accents (Γ‘, Γ©, Γ­, used in Spanish for example), extract the accented …

string matching unicode ⚬⚬⚬⚬

159. Create a simple calculator

In this Bite you will create a simple calculator. It takes a string of num1 operator num2 which you convert …

exception handling numbers operator


162. Vertically align output of counters

In this Bite you are tasked with "physically" aligning the number of comments on a webpage.For some reason you are …

string formatting ⚬⚬

163. Which packages were upgraded?

In this Bite you compare a list of packages (aka requirement.txt) from before vs. after (pip) upgrade. Check the TESTS …

comparison dict numbers

string manipulation

166. Complete a tox ini file parser class

The INI file format is an informal standard for configuration files for some platforms or software. (Wikipedia).In this Bite you …

classes configparser properties

string matching string parsing tox

173. Set up future notifications

Let's do another datetime processing Bite. Complete add_todo below that converts time units to future timestamps.Here is how it works …

datetime findall f-strings


175. Find missing dates

Complete get_misssing_dates that takes an (unordered) sequence of objects. It should determine what the start and end date of …

datetime dateutil pandas


178. Parse PyBites blog git commit log

In this Bite we want to figure out how active we've been on our blog.To start our data analysis we …

Counter data analysis datetime

dateutil string parsing

182. Parse a bunch of quotes from HTML

Let's get some inspiration. Below you find the simplified HTML of Richard Branson's My top 10 quotes on living life …

dict regular expressions string manipulation

string parsing

184. Analyze some Bite stats data

In this Bite we will look at some Bite stats logs (usernames have been anonymized!): $ head -5 bite_output_log.txt bite,user,completed …

Counter csv data analysis


185. Create a simple spelling suggester

In this Bite you will write a simple spelling corrector. Complete suggest_word that receives a misspelled word argument and returns …

difflib SequenceMatcher string matching


186. Calculate number of books to have read at date ...

For this Bite you are asked to start working on a reading goal feature for PyBites My Reading List.Code up …

datetime dateutil exception handling


187. Actor/actress age at movie release

Ever wondered how old an actor/actress was in a particular movie? In this Bite you will write some code to …

data classes dateutil f-strings


190. Parse income distribution from Latin America XML

In this Bite you are going to parse some Latin American countries in xml, specifically the output of which …

data analysis defaultdict xml


191. Starwars character with highest BMI

In this Bite you will parse a multiline string of SWAPI Starwars characters.Calculate the BMI of each character returning a …

max operator string manipulation

tuple unpacking

193. Most upvoted StackOverflow Python questions

In this Bite you parse a copy of StackOverflow Python questions which we cached here Retrieve + parse this URL …

beautifulsoup requests sorting

string matching web scraping

194. Add caching to a Fibonacci function

In this Bite you will learn about memoization: In computing, memoization or memoisation is an optimization technique used primarily to …

fibonacci functools lru_cache


195. Analyze NBA Data with sqlite3

In this Bite you are going to use sqlite3! We loaded some NBA data into a players DB table: Complete …

data analysis SQL sqlite3


197. What date is Mother's Day celebrated?

It's the 12th of May 2019 when we write this so happy Mother's Day! In many countries this special day …

datetime dateutil ⚬⚬⚬

199. Multiple inheritance (__mro__)

Implement the following class structure: print(Child.__mro__): (<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class '__main__.Person'>, <class 'object'>) Each class has the …

classes inheritance __mro__

multiple inheritance

202. Analyze some Bite stats data - part II

In this Bite you will analyze complexity levels of our first 200 Bites of Py exercises. We loaded this CSV …

csv data analysis sorting


203. Type hinting practice

It's time for some type hinting! For this bite, you have been provided a very simple Employee class object. I …

classes data classes type hinting

205. Female speakers @ Pycon US

After our Code Challenge 62 / Alicante PyDay last week, we thought it would be nice to branch off a …

beautifulsoup counting data wrangling


206. Calculate and evenly split the bill

Three old friends Bob, Mary, and Alice meet at PyCon and decide to go out to dinner together. They have …

Decimal numbers rounding


212. Suppressing exceptions

Ever wanted to suppress an exception? Check out Python's contextlib module. In this Bite you refactor sum_numbers which has some …

context managers exception handling ⚬⚬⚬

217. Capture stdout

Sometimes you need to capture stdout in your script. Python makes it easy with contextlib's redirect_stdout. In this Bite you …

context managers StringIO ⚬⚬⚬⚬

219. Bite notification planner

Another real world use case. When we added notifications to our learning paths, we gave the user the option to …

datetime generators ⚬⚬⚬⚬

221. Parse best selling lists using the NY Times API

In this Bite you are going to parse NY Times Best Seller Lists using The New York Times Developer Network.This …

APIs json requests


222. Split an iterable in groups of size n

In this Bite you will complete the group function that receives an iterable and splits it up in n groups. …

generators iterators itertools


223. Unix file permissions

Each file and directory in Unix has its permissions broken down into owner, group and other (world) attributes, see here.Each …

dict list comprehensions string manipulation


226. Get top titles from

There is a new Python news aggregator in town! Check it out here. In this Bite you will parse it!Imagine …

beautifulsoup namedtuple news

requests sorting string parsing web scraping

227. Convert Warcraft json data to csv

In this Bite we are going to convert some Warcraft Mount JSON data to csv.Here are the steps to take:Complete …

csv exception handling json


228. Create a Gravatar URL

In this Bite you will generate a Gravatar URL, e.g.;=g&d;=robohash.In this URL 5b13356d467af88631503c27a3d0e0cf is a hash of a lowercase …

gravatar hashlib string formatting


Bite Tags User difficulty More info / forum

2. Regex Fun

Learn Python regular expressions by writing the following 3 functions. In each function's docstring we show the expected result. The …

findall re regular expressions


11. Enrich a class with dunder methods

Let's enrich an Account class by adding dunder (aka special) methods to support the following:length of the object: len(acc) returns …

dunder methods properties ⚬⚬⚬⚬

20. Write a context manager

Write a context manager to roll back a transaction on the given Account class.There are two special (aka dunder) methods …

context managers dunder methods with statement


23. Find words that are > 95% similar

Given a list of tags of our blog find the ones that have a similarity score of over 95%Don't worry, …

difflib file processing findall

itertools SequenceMatcher

24. ABC's and class inheritance

ABC's or Abstract Base Classes are great to enforce a common API for your subclasses.You define one or more methods …

ABCs abstractmethod classes


31. Matrix multiplication / @ operator

Since 3.5 Python has a binary operator to be used for matrix multiplication: @, see PEP 465 -- A dedicated …

dunder methods __matmul__ ⚬⚬⚬⚬⚬⚬⚬⚬⚬

34. Building a Karma app - implement the User class

This Bite is about implementing a User class that keeps track of karma points received (Bite idea came from our …

classes dunder methods namedtuple


40. Write a binary search algorithm

There are many ways to search for an item in an ordered collection. One of the slowest methods is to …

algorithms binary search ⚬⚬⚬⚬⚬⚬

42. Number Guessing Game Class

In this Bite you implement a Game class to perform a number guessing game. It lets a user do a …

classes games random


50. Make a little PyBites search engine (feedparser)

Complete the program below to create a little search command line app to search the PyBites blog on tags. It …

any feedparser list comprehensions

namedtuple search

52. Create a movie quote API with Flask

In this Advanced Bite you will implement a full-blown CRUD app to manage movie quotes using Flask. Implement the following …

APIs Flask movie data


53. Convert text into multiple columns

You run a news site and you got feedback that people read more if articles are printed in 2 or …

string manipulation ⚬⚬⚬⚬⚬⚬

58. Using argparse to interface with a grocery cart

Below is a Groceries class with add/delete/show/search methods.You as a Python Developer are asked to give your users a command …

argparse ⚬⚬⚬⚬⚬

61. Create a variable size Paw Patrol card deck with random actions

The Paw Patrol card deck consists of 32 cards ranging A1-A2..B1-B2..C..G..H3-H4. 8 of these cards have an action associated: 2x …

itertools namedtuple random

string module

63. Use an infinite iterator to simulate a traffic light

Complete traffic_light using itertools.cycle to return an infinite iterator to similate a traffic light.When called it should return a State …

iterators itertools namedtuple


69. Regex Fun - part II

It's time for another Regex one! (here is part I)In this Bite you will complete 8 functions to hone your …

re regular expressions ⚬⚬⚬⚬⚬⚬

75. Parse Unix cal to a weekday mapping

In the last bite we return the weekday from a date object. And you probably used the calendar module.Unix has …

re Unix zip


76. The singledispatch countdown challenge

We are stoked and grateful to have Martin have you practice functools.singledispatch (new in Python 3.4).PEP 443 defines generic programming …

decorators functools singledispatch


85. Write an advanced property

After Bite 19. Write a simple property let's write a more advanced one.In this Bite you are presented with a …

classes properties ⚬⚬⚬⚬⚬

88. Write a performance monitoring context manager

It's time for Context Managers part II. In Bite 20 you used it to roll back a transaction implementing the …

context managers Counter ⚬⚬⚬⚬⚬⚬⚬

93. Rock-paper-scissors and generator's send

Generators are cool right?! Did you know you can send values into a generator by calling its send(value) method? Crazy …

coroutines games random


94. Parse PyCon talk data from YouTube

PyCon2018 was awesome! But you clearly had to choose the whole time, so much was going on!In this Bite we …

list comprehensions max namedtuple


98. Code your way out of a grid

Given a 2D grid of equal length x and y, can you print the route to go from 1 to …

looping namedtuple numbers

tuple unpacking

112. Social Media Username Validator

In this Bite you parse social_platforms below into a dict of Validator namedtuples. For each social network you should extract …

namedtuple range re

regular expressions string manipulation string matching typing

121. Determine the strength of a password

In this Bite you evaluate the strength of a password. Complete the function below and return a score from 0 …

re string matching ⚬⚬⚬⚬⚬⚬

124. Marvel data analysis

This is a simplified version of our Marvel Data Analysis we held at the Alicante PyChallengeDay.Complete most_popular_characters, max_and_min_years_new_characters and percentage_female …

Counter csv data analysis

list comprehensions rounding sum

126. The Emoji (Unicode) Bite

Python 3 supports Unicode so we can do cool stuff like ... emojis πŸ˜…Let's play a bit with emoji-to-text and …

emojis sys unicode


131. Screen scraper

This is the output from using screenFetch on my junky computer. [email protected] MMMMMMMMMMMMMMMMMMMMMMMMMmds+. OS: Mint 19 tara MMm----::-://////////////oymNMd+' Kernel: x86_64 …

dict index regular expressions

slicing string manipulation

134. Two Sums

Given a random list of numbers, your task is to find the two indices that added together equal the target …

index looping sorting


139. Calculate a coding streak in days

In this Bite you are going to calculate the amount of days you are on a coding streak (consecutive days …

datetime string manipulation timedelta


145. Record Breakers

The data for this challenge comes from a subset of The National Centers for Environmental Information (NCEI) Daily Global Historical …

csv data analysis pandas


152. Manipulate string decorator

Write a decorator called strip_range that replaces characters with dots. It takes a start and an end int argument that …

decorators kwargs list

string manipulation

158. Subclass the list built-in

In this Bite you will complete IntList, a subclass of list, which should be able to do the following: >>> …

dunder methods exception handling inheritance

list mean median properties statistics

160. 15-way Rock Paper Scissors

In this Bite you are going to write a 15-way Rock Paper Scissors game (this challenge first appeared as part …

csv dict exception handling


164. CLI tool: HTML link converter (stdin to stdout)

In this Bite you are going to help your team out automating a boring task. They reached out to you …

data wrangling exception handling html

stdin string formatting string manipulation sys

168. Ninja Rankings

PyBites is starting a campaign to try and pair up the highest ranking Ninjas with some of the lower ranking …

bisect classes data classes

dunder methods heapq tuples

174. String manipulation and metrics

This bite will get you to play around with creating a dataclass and some text manipulation, formatting, and metrics gathering. …

Counter data classes list comprehensions

properties string formatting string manipulation translate

170. Analyze McDonald's food data

In this Bite you are going to analyze some nutrition facts for McDonald's food, specially calories and proteinic rich options.The …

data analysis pandas ⚬⚬⚬

171. Make a terminal spinner animation

In this Bite you will spice up your command line apps with a loader animation.You will use itertools.cycle and sys.stdout …

command line itertools stdout

sys time

177. Use Pandas to find most common genres in a movie excel sheet

Another pandas Bite: we took some fake movie data from Mockaroo, an awesome fake data service, and dumped it in …

data cleaning excel groupby

movie data pandas

179. Strip comments from Python code

In this Bite you will strip off all comments from some Python source code. Complete strip_comments that takes some multiline …

comments regular expressions string parsing


183. Analyze sales data with pandas

For this Bite we got some fake Excel sales data which we are going to analyze with pandas.First complete load_excel_into_dataframe …

data analysis groupby pandas


196. Create a JS-like dict object

In this Bite we challenge you to make a dict-like object that supports attribute lookups, just like JS objects! Check …

classes dict inheritance


198. Calculate my Mac's longest uptime

Given the following output, calculate the longest uptime / time between reboots: [[email protected] log]$ last reboot reboot ~ Wed Apr …

data wrangling datetime dateutil

string parsing

200. πŸ₯³ Minecraft Enchantable Items

My kids love Minecraft and they always want me to play with them. At times gathering resources can get boring …

beautifulsoup web scraping ⚬⚬⚬⚬⚬⚬⚬⚬⚬

204. Pomodoro with asyncio

I got an asyncio and type hinting Bite for you. For this bite, you will be taking a simple Pomodoro …

asyncio pomodoro ⚬⚬⚬⚬⚬⚬

207. Cached property decorator

Given the sample class Planet, computing the mass attribute of an instance is a computationally expensive and time consuming operation. …

caching classes decorators


211. Write a retry decorator

Write a retry decorator that retries to execute the function it decorates. If the function raises an exception (any kind) …

decorators exception handling ⚬⚬⚬⚬⚬

213. Code a translation fixer

Imagine you built PyBites' new translation feature. You managed to successfully get translated text for a Bite, but there's a …

regular expressions ⚬⚬⚬⚬

216. Parse an email header

Write a regular expression to extract 4 pieces of information from an email header: From email To email Subject Date …

regular expressions ⚬⚬⚬⚬⚬⚬

220. Analysing @pythonbytes RSS feed

Another feedparser exercise! In this Bite we're going to analyze the Python Bytes Podcast feed a bit completing the PythonBytes …

classes Counter feedparser

max min namedtuple regular expressions string matching type hinting

224. Get sentences from a text

Here is another fun regex exercise for you: it's easy to split text by newline using splitlines. Now try to …

data wrangling regular expressions string manipulation


We use Python 3.7