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 πŸ’ͺ



Bite Description & Tags
1. Sum n numbers Write a function that can sum up numbers:It should receive …
default args None range sum
5. Parse a list of names In this bite you will work with a list of …
lambda list comprehensions min sorting
8. Rotate string characters Write a function that rotates characters in a string, in …
deque slicing
15. Enumerate 2 sequences Iterate over the given names and countries lists, printing them …
enumerate string formatting
16. PyBites date generator Write a generator that returns special dates for PyBites: Every …
datetime generators
19. Write a simple property Write a simple Promo class. Its constructor receives a name …
datetime properties
21. Query a nested data structure Given the provided cars dictionary:Get all JeepsGet the first car …
data structures dictionary comprehensions list comprehensions sorting
26. Dictionary comprehensions are awesome A dictionary comprehension is like a list comprehension, but it …
dictionary comprehensions
29. Martin's IQ test Martin is preparing to pass an IQ test.The most frequent …
enumerate string module
32. Don't let mutability fool you In this Bite you are presented with a function that …
deepcopy mutability
37. Rewrite a for loop using recursion Although you have to be careful using recursion it is …
recursion reverse
38. Using ElementTree to parse XML In this Bite you will use ElementTree to parse some …
movie data xml
43. Force keyword arguments Write a function called get_profile that can only allows 2 …
function arguments kwargs
44. License key generator Write a function called gen_key that creates a license key …
list comprehensions secrets string module
45. Keep a queue of last n items How about writing a queue that holds the last 5 …
deque
46. You are a programmer! Code Fizz Buzz Here is a beginner Bite to write Fizz Buzz: Fizz …
fizzbuzz
54. Nicer formatting of a poem or text In this Bite you complete print_hanging_indents to print a poem …
string manipulation textwrap
55. Get the latest game releases from Steam's RSS feed The Steam gaming platform has an RSS feed of their …
feedparser namedtuple
56. Add a command line interface to our BMI calculator Complete create_parser below so that our BMI program can be …
argparse
64. Fix a truncating zip function Bert is in charge of organizing an event and got …
itertools zip
66. Calculate the running average of a sequence Write a function that takes a sequence of items and …
enumerate mean
67. Working with datetimes This Bite involves solving two problems using datetime:We kicked off …
datetime timedelta
68. Remove punctuation characters from a string Complete remove_punctuation which receives an input string and strips out …
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 …
calendar
77. New places to travel to You want to find people who have as much exposure …
set set operations
80. Check equality of two lists In this Bite we compare two list objects for equality, …
enum equality list
83. At what time does PyBites live? Get to know pytz! pytz brings the Olson tz database …
pytz timezones
91. Matching multiple strings Catching up after #PyCon2018 ... in this Bite you do …
all any re string matching
96. Build Unix' wc program in Python In this Bite you will convert Unix' wc command into …
file processing tempfile Unix
100. Display the last part of a file (Unix tail) Complete the function below simulating Unix' tail, for example: $ …
file processing slicing strip Unix
115. Count leading spaces A small but interesting Bite: given a string with leading …
counting string matching
117. Round a number even (a.k.a. banker's rounding) Bankers Rounding is an algorithm for rounding quantities to integers, …
Decimal rounding
128. Work with datetime's strptime and strftime In this Bite you get some more practice with datetime's …
datetime strftime strptime
130. Analyze some basic Car Data In this exercise you will analyze some basic car data. …
Counter data analysis list comprehensions set
133. Convert an Amazon URL into an affiliation link Can you help PyBites automate their Amazon affiliation link creation?Complete …
regular expressions string manipulation
136. Bloodtypes Check red blood cell compatibility between donor and recipient. For …
enum exception handling multi type input
143. Look up a value in 3 dictionaries In this Bite you are presented with 3 dictionaries. Complete …
collections dict
149. Sorting words with constraint Here is a list of words Jacob is trying to …
lambda sorting string manipulation
153. Round a sequence of numbers It's time to get mathematical! In this Bite we ask …
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 …
counting directories files os module
165. Parse an /etc/passwd file output The /etc/passwd file is a text-based database of information about …
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 …
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 …
exception handling numbers rounding
172. Having fun with Python Partials Meet another gem in the standard library: functools, which contains …
functools partial rounding
176. Create a variable length chessboard In this Bite you are going to print a chessboard …
modulo range stdout
180. Group names by country In this Bite you are presented with a list of …
collections defaultdict groupby
181. Keep a list sorted upon insert Complete the add method of the OrderedList class which takes …
bisect classes data structures __str__
188. Get statistics from PyBites test code Did you know Python has a statistics module?For this Bite …
data analysis file processing statistics
189. Filter a list of names Here is a Bite to practice the continue and break …
break continue generators looping
192. Some logging practice This is a simple logging exercise. The logging module is …
logging
201. Call a Cisco Nexus 9k device In this Bite you are going to make an API …
networking requests
208. Find the number pairs summing up N In this Bite you complete find_number_pairs which receives a list …
itertools looping numbers
209. Write a Sphinx docstring Your team uses Sphinx and wants you to comply with …
data types docstring sphinx
210. Add Type Annotations Continuing from where we left off in Bite 209, use …
annotations typing
214. A countdown generator Write a simple generator that counts from 100 to 1. …
generators
215. Validate a license key Complete the validate_license function writing a regular expression that matches …
bool regular expressions
218. Create a sandwich decorator After creating our Decorators and Context Managers learning path we …
decorators

Bite Description & Tags
3. Word Values Calculate the dictionary word that would have the most value …
max Scrabble sum
30. Movie data analysis In this Bite we are going to parse a csv …
data analysis defaultdict mean movie data namedtuple sorting
4. Top 10 PyBites tags Get the top 10 blog tags of PyBites (e.g. python, …
Counter findall regular expressions
6. PyBites Die Hard Given a listing of files of our community branch determine …
Counter file processing generators namedtuple
7. Parsing dates from logs In this bite we will look at this small server …
datetime file processing
9. Palindromes Write a function to determine if a word (or phrase) …
list comprehensions max reverse
10. Practice exceptions In this bite you learn to catch/raise exceptions.Write a simple …
exception handling raise
12. Write a user validation function Create a function that takes a username and checks for …
classes exception handling namedtuple
13. Convert dict to namedtuple/json Write a function to convert the given blog dict to …
dict json namedtuple
14. Generate a table of n sequences Write a function that receives one or more sequences. The …
generators zip
17. Form teams from a group of friends Write a function called friends_teams that takes a list of …
itertools
18. Find the most common word Write a function that returns the most common (non stop)word …
Counter data analysis list comprehensions
22. Write a decorator with argument Write a decorator called make_html that wraps text inside one …
decorators
25. No promo twice, keep state in a class In this bite a real world scenario: PyBites has a …
classes exception handling properties
27. Parse omdb movie json data Working with APIs is very common these days and lucky …
APIs glob json movie data
28. Converting date strings to datetimes In this Bite you are provided with a list of …
Counter datetime findall
33. Transpose a data structure Sometimes you need to restructure a nested data structure. For …
dict zip
35. Having fun with heapq In this Bite you are provided with 3 data structures: …
datetime heapq
36. Having fun with *args and **kwargs Write a function called get_profile that takes:a required name,a required …
args function arguments kwargs
39. Calculate the total duration of a course In this Bite you read in a text file with …
datetime findall numbers timedelta
41. Write a login_required decorator If you worked with Flask or Django you must have …
decorators
47. Write a new password field validator You know these Create a new password forms? They do …
re string module
48. Make a bar chart of new Safari books Some time ago we made a little Slack bot to …
bar chart data analysis
49. Scrape Packt's html with BeautifulSoup In this Bite you will parse Packt's free learning ebook …
beautifulsoup namedtuple requests
51. When does Python 2 die on Planet Miller? Imagine you landed on Planet Miller (from the movie Interstellar) …
datetime
57. Create a simple calculator that receives command line arguments In this Bite you write a simple calculator that can …
argparse functools reduce
59. Create a multiplication table class of variable length Danny does not like rote learning (nor do we!). He …
classes dunder methods exception handling numbers
60. Create a deck of Uno cards In this Bite you will create a deck of Uno …
list list comprehensions namedtuple
62. Data structures matter - speed up your Python code In this Bite we provide you with 5 functions which …
data structures performance
65. Get all valid dictionary words for a draw of letters This Bite focusses on the use of itertools. To that …
itertools Scrabble
70. Create your own iterator In this Bite you make an iterator called EggCreator by …
iterators random
71. Keep state in a class + make its instance callable In this Bite you write a small class to keep …
classes dunder methods
72. Retrieve the right Ninja Belt based on score As you have probably seen on the new dashboard you …
itertools OrderedDict
73. Organize a meeting between timezones (pytz) Help PyBites community friends find a reasonable common time to …
pytz timezones
78. Find programmers with common languages Similar as last Bite we do another comparison of sequences …
set set operations
79. Parse a csv file and create a bar chart We played a bit with the Slack API today and …
bar chart community csv requests
81. Filter and order tweets by polarity values In this Bite we collected some random tweets and populated …
namedtuple TextBlob Twitter
82. Define a Score Enum and customize it adding methods Starting Python 3.4 there is support for enumerations (not to …
classmethod enum __str__
84. Flatten lists recursively (Droste Bite) Complete flatten that takes a list of lists (which can …
list recursion
86. Create a RGB-to-Hex converter Designer Mary wants to convert her CSS from statements like …
string formatting
87. Convert Decimal to Roman Numerals Complete romanize that takes a decimal number and converts it …
numbers OrderedDict
89. Playing with lists and dicts In this Bite you are presented with a us_state_abbrev dict …
data structures dict list
90. What South Park characters talk most? Did we already tell you we love the collections module? …
Counter csv data analysis defaultdict requests
92. Humanize a datetime In this Bite you will convert a timedelta object into …
datetime namedtuple
95. Subclass the dict built-in In this Bite you will subclass the dict built-in to …
classes inheritance
97. BeautifulSoup II - scrape US bank holidays In this Bite we use BeautifulSoup to scrape US bank …
beautifulsoup defaultdict dict
99. Write an infinite sequence generator Write a generator that produces the sequence [1, 'A', 2, …
generators itertools string module zip
111. Use the ipinfo API to lookup IP country In this Bite you will use the requests library to …
APIs json mock.patch requests
113. Filter words with non-ascii characters In this Bite you extract words from a text that …
all ascii ord unicode
114. Implement a Color class with classmethods As the new junior developer, you have been charged with …
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 …
generators glob os module
118. List exercise: return first occurrence indices of duplicated words In this Bite you are presented with a list of …
counting list comprehensions set
119. Xmas tree generator In this Bite you complete generate_xmas_tree that takes a rows …
default args join range string formatting
120. Write a numbers validation decorator Let's get some more practice with decorators ... in this …
decorators
122. Check if two words are anagrams An anagram is a word or phrase formed by rearranging …
anagram string matching
123. Find the user with most friends In this Bite you are presented with a users dict …
defaultdict looping sorting tuples
125. Get the most recommended books The Tim Ferriss Show is full of wisdom and inspiration. …
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 …
dict modulo numbers string manipulation
129. Analyze Stock Data In this Bite we will answer some questions about stocks, …
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 …
counting lambda list comprehensions string matching
135. Sort a list of book objects In this Bite you are going to look at a …
attrgetter datetime lambda list namedtuple operator sorting
137. Gourmets' Nightmare Many gourmets struggle to find the perfect pairing of wines …
Counter intersection operator sorting
138. OOP fun at the Zoo Finish the Animal class below adding one or more class …
classes classmethod itertools __str__
140. PyBites First Pandas Bite This is a Pandas proof-of-concept Bite. We just added the …
csv data analysis pandas
141. Primitive date format inferrer Complete the get_dates method given the following:a listing of date …
classmethod datetime enum exception handling
142. Exception Handling: Calculate the Winning Player Complete the two functions below: calculate_score takes a list of …
exception handling namedtuple numbers
144. Calculate the Number of Months Passed Some more fun working with dates! In this Bite you …
datetime dateutil exception handling
146. Rhombus generator In this Bite you make a generator of rhombus shapes. …
format f-strings string formatting
147. 100 WEEKDays of Code Date Range Doing a #100DaysOfCode can be challenging, and some of it …
datetime dateutil
148. Print Car Data Grouped by Manufacturer In this Bite you are presented with a list of …
data structures itertools operator sorting
150. Turn messy CSV into JSON At the 1 year mark of our platform here is …
csv json re string manipulation
151. Contemporary Composers You are given a list of operas and a list …
datetime dict exception handling generators namedtuple
154. Write your own Data Class As you might have noticed we are now on Python …
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 …
split string manipulation
156. Make an index of story characters You know the index at the end of a book …
collections defaultdict enumerate sorting string matching
157. Filter out accented characters Another unicode Bite. Given some non-English text with accents (Γ‘, …
string matching unicode
159. Create a simple calculator In this Bite you will create a simple calculator. It …
exception handling numbers operator
162. Vertically align output of counters In this Bite you are tasked with "physically" aligning the …
string formatting
163. Which packages were upgraded? In this Bite you compare a list of packages (aka …
comparison dict numbers string manipulation
166. Complete a tox ini file parser class The INI file format is an informal standard for configuration …
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 …
datetime findall f-strings timedelta
175. Find missing dates Complete get_misssing_dates that takes an (unordered) sequence of datetime.date objects. …
datetime dateutil pandas
178. Parse PyBites blog git commit log In this Bite we want to figure out how active …
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 …
dict regular expressions string manipulation string parsing
184. Analyze some Bite stats data In this Bite we will look at some Bite stats …
Counter csv data analysis set
185. Create a simple spelling suggester In this Bite you will write a simple spelling corrector. …
difflib SequenceMatcher string matching
186. Calculate number of books to have read at date ... For this Bite you are asked to start working on …
datetime dateutil exception handling
187. Actor/actress age at movie release Ever wondered how old an actor/actress was in a particular …
data classes dateutil f-strings
190. Parse income distribution from Latin America XML In this Bite you are going to parse some Latin …
data analysis defaultdict xml
191. Starwars character with highest BMI In this Bite you will parse a multiline string of …
max operator string manipulation tuple unpacking
193. Most upvoted StackOverflow Python questions In this Bite you parse a copy of StackOverflow Python …
beautifulsoup requests sorting string matching web scraping
194. Add caching to a Fibonacci function In this Bite you will learn about memoization: In computing, …
fibonacci functools lru_cache performance
195. Analyze NBA Data with sqlite3 In this Bite you are going to use sqlite3! We …
data analysis SQL sqlite3
197. What date is Mother's Day celebrated? It's the 12th of May 2019 when we write this …
datetime dateutil
199. Multiple inheritance (__mro__) Implement the following class structure: print(Child.__mro__): (<class '__main__.Child'>, <class '__main__.Father'>, …
classes inheritance __mro__ multiple inheritance
202. Analyze some Bite stats data - part II In this Bite you will analyze complexity levels of our …
csv data analysis sorting
203. Type hinting practice It's time for some type hinting! For this bite, you …
classes type hinting
205. Female speakers @ Pycon US After our Code Challenge 62 / Alicante PyDay last week, …
beautifulsoup counting data wrangling gender_guesser
206. Calculate and evenly split the bill Three old friends Bob, Mary, and Alice meet at PyCon …
Decimal numbers rounding
212. Suppressing exceptions Ever wanted to suppress an exception? Check out Python's contextlib …
context managers exception handling
217. Capture stdout Sometimes you need to capture stdout in your script. Python …
context managers StringIO
219. Bite notification planner Another real world use case. When we added notifications to …
datetime generators
221. Parse best selling lists using the NY Times API In this Bite you are going to parse NY Times …
APIs json requests
222. Split an iterable in groups of size n In this Bite you will complete the group function that …
generators iterators itertools looping

Bite Description & Tags
2. Regex Fun Learn Python regular expressions by writing the following 3 functions. …
findall re regular expressions
11. Enrich a class with dunder methods Let's enrich an Account class by adding dunder (aka special) …
dunder methods properties
20. Write a context manager Write a context manager to roll back a transaction on …
context managers dunder methods with statement
23. Find words that are > 95% similar Given a list of tags of our blog find the …
difflib file processing findall itertools SequenceMatcher
24. ABC's and class inheritance ABC's or Abstract Base Classes are great to enforce a …
ABCs abstractmethod classes inheritance
31. Matrix multiplication / @ operator Since 3.5 Python has a binary operator to be used …
dunder methods __matmul__
34. Building a Karma app - implement the User class This Bite is about implementing a User class that keeps …
classes dunder methods namedtuple properties
40. Write a binary search algorithm There are many ways to search for an item in …
algorithms binary search
42. Number Guessing Game Class In this Bite you implement a Game class to perform …
classes games random
50. Make a little PyBites search engine (feedparser) Complete the program below to create a little search command …
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 …
APIs Flask movie data
53. Convert text into multiple columns You run a news site and you got feedback that …
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 …
argparse
61. Create a variable size Paw Patrol card deck with random actions The Paw Patrol card deck consists of 32 cards ranging …
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 …
iterators itertools namedtuple
69. Regex Fun - part II It's time for another Regex one! (here is part I)In …
re regular expressions
75. Parse Unix cal to a weekday mapping In the last bite we return the weekday from a …
re Unix zip
76. The singledispatch countdown challenge We are stoked and grateful to have Martin have you …
decorators functools singledispatch
85. Write an advanced property After Bite 19. Write a simple property let's write a …
classes properties
88. Write a performance monitoring context manager It's time for Context Managers part II. In Bite 20 …
context managers Counter
93. Rock-paper-scissors and generator's send Generators are cool right?! Did you know you can send …
coroutines games random
94. Parse PyCon talk data from YouTube PyCon2018 was awesome! But you clearly had to choose the …
list comprehensions max namedtuple
98. Code your way out of a grid Given a 2D grid of equal length x and y, …
looping namedtuple numbers tuple unpacking
112. Social Media Username Validator In this Bite you parse social_platforms below into a dict …
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. …
re string matching
124. Marvel data analysis This is a simplified version of our Marvel Data Analysis …
Counter csv data analysis list comprehensions rounding sum
126. The Emoji (Unicode) Bite Python 3 supports Unicode so we can do cool stuff …
emojis sys unicode
131. Screen scraper This is the output from using screenFetch on my junky …
dict index regular expressions slicing string manipulation
134. Two Sums Given a random list of numbers, your task is to …
index looping sorting sum
139. Calculate a coding streak in days In this Bite you are going to calculate the amount …
datetime string manipulation timedelta
145. Record Breakers The data for this challenge comes from a subset of …
csv data analysis pandas
152. Manipulate string decorator Write a decorator called strip_range that replaces characters with dots. …
decorators kwargs list string manipulation
158. Subclass the list built-in In this Bite you will complete IntList, a subclass of …
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 …
csv dict exception handling games
164. CLI tool: HTML link converter (stdin to stdout) In this Bite you are going to help your team …
data wrangling exception handling html stdin string formatting string manipulation sys
168. Ninja Rankings PyBites is starting a campaign to try and pair up …
bisect classes data classes dunder methods heapq tuples
174. String manipulation and metrics This bite will get you to play around with creating …
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 …
data analysis pandas
171. Make a terminal spinner animation In this Bite you will spice up your command line …
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 …
data cleaning excel groupby movie data pandas
179. Strip comments from Python code In this Bite you will strip off all comments from …
comments regular expressions string parsing
183. Analyze sales data with pandas For this Bite we got some fake Excel sales data …
data analysis groupby pandas
196. Create a JS-like dict object In this Bite we challenge you to make a dict-like …
classes dict inheritance javascript
198. Calculate my Mac's longest uptime Given the following output, calculate the longest uptime / time …
data wrangling datetime dateutil string parsing
200. πŸ₯³ Minecraft Enchantable Items My kids love Minecraft and they always want me to …
beautifulsoup web scraping
204. Pomodoro with asyncio I got an asyncio and type hinting Bite for you. …
asyncio pomodoro
207. Cached property decorator Given the sample class Planet, computing the mass attribute of …
caching classes decorators properties
211. Write a retry decorator Write a retry decorator that retries to execute the function …
decorators exception handling
213. Code a translation fixer Imagine you built PyBites' new translation feature. You managed to …
regular expressions translate
216. Parse an email header Write a regular expression to extract 4 pieces of information …
regular expressions
220. Analysing @pythonbytes RSS feed Another feedparser exercise! In this Bite we're going to analyze …
classes Counter feedparser max min namedtuple regular expressions string matching type hinting
We use Python 3.7