Python Workbook
Python Workbook
John Elder
Codemy.com
Las Vegas
Intro To Python Programming
Beginners Guide Series Workbook
Published By Codemy.com
Las Vegas, NV USA
ISBN
979-8-9859654-3-8
First Edition
http://www.Codemy.com
FOR APRIL
TABLE OF CONTENTS
10
Codemy.com
11
John Elder
12
Codemy.com
• Why it matters
APPENDIX ONE
• Special Half Off Python Projects Course Offer
13
INTRO TO
PYTHON
PROGRAMMING
These days John writes about Coding and wealth creation; produces a
popular coding Youtube Channel, and runs Codemy.com the online
learning platform where he’s taught Coding to over 20 million students.
INTRODUCTION
(https://www.amazon.com/Intro-Python-Programming-Beginners-
Guide/dp/B09VDRSKB7/)
...or you've just stumbled in here looking for Python practice that
doesn’t make you fall asleep at your keyboard, you’re in the right place.
And while that book lays down the knowledge, this workbook is where
you get your reps in.
Think of the original book like the driving manual, and this workbook
like your time behind the wheel. You need both to become a confident,
skilled Python programmer.
17
John Elder
This isn’t a quiz book. There are no multiple choice questions here. I’m
not here to test you. I’m here to help you practice, play, build muscle
memory, and gain real fluency with Python.
Each chapter of the workbook lines up directly with a chapter from the
original book. That means you should absolutely read the chapter first,
get the lay of the land, and then come here to apply what you just
learned.
18
Codemy.com
Chapter 5: Lists
Organize everything from snacks to birthday gifts. Practice modifying,
removing, and repeating list items like a pro.
Chapter 6: Loops
You’ll count things, break things, skip things, and build things—all
while looping until Python tells you to stop. You might even meet a zoo
animal or two.
Chapter 7: Functions
Say goodbye to copy-paste and hello to code reusability. Build your own
code tools like insult generators, emoji printers, and dramatic battle
announcers.
Chapter 8: Dictionaries
Learn to map data like a proper Pythonista. Use key-value pairs to build
inventories, translate emoji, simulate vote counts, and even manage a
fictional zoo.
Conclusion
A friendly nudge to keep going, build your own stuff, and maybe even
take over the world (with Python, obviously).
19
John Elder
Not here.
Some are practical. Some are absurd. Some are mini-challenges. All of
them are original. None of them reuse the examples from the book—so
you’re always applying the concepts in fresh ways.
You don’t have to get everything perfect the first time. The point is to
learn by doing.
1. Read the chapter in the original book first. Don’t skip this. The
exercises assume you understand the basics presented in the
chapter.
20
Codemy.com
3. Run the code. Break it. Fix it. You’ll learn 100x more by seeing
what happens than just reading a correct answer.
If you use them together, you're not just going to understand Python—
you’re going to be able to use it, comfortably and confidently.
So fire up your text editor, warm up your brain, and get ready to code
your way through the rest of the book. I’m glad you’re here.
- John Elder
Codemy.com
21
John Elder
If you make it through this workbook, you’ll have already done more
than most people who say they want to learn Python. But here’s the
truth: knowing about Python isn’t the same as being able to use it. If you
really want to get good, you need to build stuff.
22
Codemy.com
10. To-Do List App – Create your own productivity app using basic
GUI structure.
11. Word Count Tool – Work with text files and count words with
file I/O.
12. Tic Tac Toe Game – Master game flow, input handling, and win
detection.
13. Draw with Turtle – Use the Turtle graphics module to code
creative designs.
14. Image Resizer – Resize and process images for personal or web
use.
15. Anagram Solver – Solve and detect anagrams using clever logic
and lists.
23
John Elder
16. Typing Speed Test – Create a timed typing tool to test speed and
accuracy.
The full course normally sells for $129, but as a thank-you for working
through this workbook, you can grab it now for just $64 here:
https://order.codemy.com/python-projects-64
If you liked this workbook, you’ll love the course. Hope to see you
inside.
24
Codemy.com
CHAPTER TWO
25
John Elder
Alright! This is where the rubber meets the road. In Chapter Two of the
book, we learned how to write and run our very first Python program.
We talked about how to open a text editor (like Sublime Text), create a
new .py file, and run it from the terminal. You typed out the classic
“Hello World!” — a rite of passage for every new programmer.
We also took a peek at the print() function, how it works, and how
Python doesn’t need all the weird semicolons and parentheses that other
languages demand.
You got a crash course in syntax errors (yay typos!), saw what happens
when things go wrong, and learned how to fix them. And let’s not forget
comments — those handy little notes that explain your code so future-
you doesn’t scream into the void.
So now that you know how to write, run, and debug a Python program,
let’s solidify those skills with some fun hands-on practice!
Yes, these are gonna be a little lame because – let’s face it – we haven’t
learned all that much yet. But give them a try anyway!
26
Codemy.com
Exercise 2.1
Hello World – First Impressions Count!
Write a Python program that outputs "Hello, Python World!". Then,
personalize it by adding your name or a funny nickname.
Exercise 2.2
Print-It Party – Making Python Talk
Create a Python program that prints a short story about your favorite
animal, complete with fun details and excitement.
Exercise 2.3
Whoops-a-Daisy – Learning Through Errors
Write Python code with intentional errors (like missing parentheses,
typos, etc.). Try running it and then correct the errors one by one, noting
what you fixed and why.
Exercise 2.4
Comment Craze – What's the Big Idea?
Write a small Python program, then add comments explaining each line.
Make your comments playful and humorous.
27
John Elder
Exercise 2.5
Coding Chaos – Debugging Fun
Take a given Python snippet full of mistakes (create your own or use the
one in the solution) and debug it. List each error and explain how you
fixed it.
Exercise 2.6
Print the Unexpected – Creative Strings
Use Python's print function to create a program that outputs a
humorous dialogue between two fictional characters of your choice.
Exercise 2.7
Hidden Messages – Comment Coding
Write a Python program with hidden secret messages in comments. This
would be really cool if we were all twelve years old! :-p
Exercise 2.8
Guess My Error – Spot and Correct
Partner with a fictional friend to write Python programs with intentional
errors. Then fix the errors.
28
Codemy.com
Exercise 2.9
Terminal Treasure Hunt
Create a list of instructions using Python's print statements. When
executed, these instructions should guide the user through a terminal
"treasure hunt."
Exercise 2.10
ASCII Art Adventure
Use Python's print statements to create your own ASCII art masterpiece.
It could be your favorite animal, object, or even a funny self-portrait!
29
John Elder
Answer 2.2
Answer 2.3
Fix:
Answer 2.4
30
Codemy.com
print("Hello World!"
pritn("Oops")
After:
Answer 2.6
Answer 2.7
31
John Elder
Answer 2.8
Answer 2.9
Answer 2.10
print("""
/\_/\
( o.o )
>^<
""")
32
Codemy.com
CHAPTER THREE
33
John Elder
In Chapter Three of the main book, we got our first real taste of Python's
power. You learned how to make your programs do math, store data in
variables, and interact with users through input.
You saw how Python handles integers and floats (yes, decimal points
matter!), and how you can use variables to keep track of data as your
program runs.
This is the chapter where Python starts feeling more like a tool and less
like a toy.
So let’s play around with what we’ve learned and solidify those skills
with some exercises!
34
Codemy.com
Exercise 3.1
Calculator Fun – Math Time!
Write a program that adds, subtracts, multiplies, and divides two
numbers. Display the results using print statements.
Exercise 3.2
Floaty Numbers – Decimals Matter
Create a program that divides 7 by 3 and prints the result. Then, try a
few other combinations (like 10 divided by 4 or 5 divided by 2) to see
how Python handles decimal values.
Exercise 3.3
Variable Swap – Switcheroo!
Assign values to two variables, then swap them and print the results. Do
this without hardcoding new values.
Exercise 3.4
Favorite Animal – Input Practice
Ask the user what their favorite animal is, then print a sentence that
includes their answer in a funny or creative way.
35
John Elder
Exercise 3.5
Birth Year Guess – The Age Calculator
Ask the user what year they were born in. Subtract it from the current
year and print their age.
Exercise 3.6
Favorite Number – String + Variable
Ask the user for their favorite number. Then print a fun sentence that
includes it.
Exercise 3.7
Story Time – Input & Concatenation
Ask the user for a noun, a verb, and an adjective. Then build a silly one-
line story using their inputs.
Exercise 3.8
Python Mad Libs
Create a simple Mad Lib using at least three input() prompts and some
variables. Then print the full story.
Exercise 3.9
Grocery Total – Math with Input
Ask the user the cost of two grocery items. Add them together and print
the total.
36
Codemy.com
Exercise 3.10
Math Story Problem
Write a program that tells a little story involving math (e.g., “If John has
3 apples and buys 5 more…”). Calculate the result and print it.
37
John Elder
a = 10
b=5
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
Answer 3.2
print(7 / 3)
print(10 / 4)
print(5 / 2)
Answer 3.3
a=1
b=2
a, b = b, a
print("a:", a)
print("b:", b)
38
Codemy.com
Answer 3.4
Answer 3.5
Answer 3.6
Answer 3.7
39
John Elder
Answer 3.8
Answer 3.9
Answer 3.10
apples = 3
bought = 5
total = apples + bought
print("John had", apples, "apples and bought", bought, "more. Now he
has", total, "apples.")
40
Codemy.com
CHAPTER FOUR
IF/ELSE STATEMENTS
41
John Elder
In Chapter Four of the main book, you learned how to make decisions in
your code using if, elif, and else.
You also saw how indentation matters — Python won’t tolerate sloppy
code formatting!
Now let’s reinforce those ideas with some fun and practical exercises.
The exercises will start to get a little harder and a little more interesting
from here on out!
42
Codemy.com
Exercise 4.1
Roller Coaster Ride – Height Check
Write a program that asks for a user’s height in inches. If they are 48
inches or taller, print that they can ride the roller coaster. Otherwise,
print a message that says they need to grow a bit more.
Exercise 4.2
Even or Odd?
Ask the user for a number. Use an if/else statement to print whether the
number is even or odd.
Exercise 4.3
Password Checker
Ask the user to enter a password. If the password is "swordfish", print
"Access granted". Otherwise, print "Access denied".
Exercise 4.4
Grading Machine
Ask the user to enter a number between 0 and 100. Print the letter grade
using if/elif/else:
- 90 or higher: A
- 80–89: B
- 70–79: C
- 60–69: D
- Below 60: F
43
John Elder
Exercise 4.5
Double Trouble
Ask the user for two numbers. Use if/else to print which one is larger, or
print a message if they are the same.
Exercise 4.6
Animal Match Game
Ask the user to input their favorite animal. If it’s "dog", "cat", or "rabbit",
print "Great choice!". Otherwise, print "That’s an interesting pick!"
Exercise 4.7
Dinner Plans – Logical Operators
Ask the user if they are hungry (yes or no) and if they have food at home
(yes or no).
- If hungry and no food at home, print "Time to order takeout!"
- If hungry and food at home, print "Time to cook!"
- If not hungry, print "Maybe later."
Exercise 4.8
Number Range Checker
Ask the user for a number. Use if and and to check if the number is
between 10 and 20, inclusive.
44
Codemy.com
Exercise 4.9
Weather Wizard
Ask the user if it’s raining and if it’s cold. Print different suggestions
depending on the answers (e.g., "Bring an umbrella", "Wear a coat", etc.)
Exercise 4.10
Choose Your Path – Text Adventure
Write a simple text-based game where the user chooses between two
paths. Use if/else to give different story outcomes.
45
John Elder
Answer 4.2
Answer 4.3
46
Codemy.com
Answer 4.4
Answer 4.5
47
John Elder
Answer 4.6
Answer 4.7
Answer 4.8
48
Codemy.com
Answer 4.9
Answer 4.10
path = input("Do you choose the left path or the right path? ")
if path == "left":
print("You find a treasure chest!")
else:
print("You fall into a pit of snakes!")
49
John Elder
CHAPTER FIVE
LISTS
50
Codemy.com
In Chapter Five of the main book, we learned how to create lists, access
items using indexes, change individual elements, and use methods like
.append(), .insert(), .remove(), and .pop().
We also experimented with lists that contain other lists — also known as
multidimensional lists.
Let’s reinforce those concepts with exercises that match what you’ve
seen in the book so far.
51
John Elder
Exercise 5.1
Favorite Foods
Create a list of your three favorite foods and print the whole list.
Exercise 5.2
Add to the List
Start with a list of two school supplies. Add two more using .append()
and print the final list.
Exercise 5.3
Replacing the Middle
Create a list with three silly objects. Change the second one to something
even sillier, then print the result.
Exercise 5.4
Pop Goes the List
Make a list of three sounds. Use .pop() to remove the last one and print
what was removed and the updated list.
Exercise 5.5
Insert It In
Create a list with three movies. Use .insert() to add a new movie at the
beginning. Then print the updated list.
52
Codemy.com
Exercise 5.6
Remove That!
Create a list with five chores. Use .remove() to delete your least favorite
chore. Print the final list.
Exercise 5.7
First and Last
Make a list of four emojis. Print the first and last using indexing.
Exercise 5.8
Double Trouble
Create a list of your three favorite animals. Then make a second list of
your three favorite colors. Combine them into one list that contains both
lists. Print the result.
Exercise 5.9
Multidimensional Peek
Make a list called outer that contains two lists: one of fruits and one of
vegetables. Print one item from each inner list using double indexing.
53
John Elder
Exercise 5.10
Build a Nested List from Scratch
Ask the user to enter two colors and two shapes. Store colors in one list
and shapes in another. Combine both lists into one nested list and print
it.
54
Codemy.com
Answer 5.2
Answer 5.3
55
John Elder
Answer 5.4
Answer 5.5
Answer 5.6
56
Codemy.com
Answer 5.7
Answer 5.8
Answer 5.9
57
John Elder
Answer 5.10
colors = []
shapes = []
colors.append(input("Enter a color: "))
colors.append(input("Enter another color: "))
shapes.append(input("Enter a shape: "))
shapes.append(input("Enter another shape: "))
nested = [colors, shapes]
print(nested)
58
Codemy.com
CHAPTER SIX
LOOPS
59
John Elder
In Chapter Six of the main book, we learned about two powerful tools
for repeating actions in code: the while loop and the for loop.
A while loop keeps running as long as a condition is true, and a for loop
lets us step through each item in a list.
We also explored break, continue, and pass, as well as the use of else
blocks with loops.
These exercises will help you practice what you learned in this chapter
— and only what you learned so far.
60
Codemy.com
Exercise 6.1
Even Countdown
Use a while loop to count down from 10 to 2 by twos. Print each
number.
Exercise 6.2
Zoo Animals
Create a list of four zoo animals. Use a for loop to print each one
followed by the phrase " is cool!"
Exercise 6.3
Count and Compliment
Use a while loop to count from 1 to 5. When the number is 3, print
"Three is the best number!" instead of the number.
Exercise 6.4
Build a Word
Make a list of letters that spell out a short word (like ['c', 'a', 't']). Use a
for loop to print the word one letter at a time.
Exercise 6.5
No Fours Allowed
Write a for loop that prints numbers 1 through 5 but skips 4 using
continue.
61
John Elder
Exercise 6.6
Stop at Banana
Make a list of fruit: ['apple', 'orange', 'banana', 'grape']. Use a for loop to
print each fruit. Use break to stop the loop when you reach "banana".
Exercise 6.7
Empty Loop Else
Create a for loop that runs through an empty list. Add an else block that
prints "Nothing to see here!"
Exercise 6.8
Just Passing Through
Loop through the word "class". If the letter is "s", use pass. Print the rest
of the letters.
Exercise 6.9
Password Practice
Use a while loop to keep asking the user to enter the word "code". Only
stop once they type it exactly.
Exercise 6.10
Buzz Until Stop
Use a while loop that runs forever. Ask the user to type a word. If the
word is "stop", break the loop. Otherwise, print "buzz!"
62
Codemy.com
i = 10
while i >= 2:
print(i)
i -= 2
Answer 6.2
Answer 6.3
i=1
while i <= 5:
if i == 3:
print("Three is the best number!")
else:
print(i)
i += 1
63
John Elder
Answer 6.4
Answer 6.5
Answer 6.6
Answer 6.7
items = []
64
Codemy.com
Answer 6.8
Answer 6.9
entry = ""
while entry != "code":
entry = input("Enter the password: ")
65
John Elder
Answer 6.10
while True:
word = input("Type a word: ")
if word == "stop":
break
print("buzz!")
66
Codemy.com
CHAPTER SEVEN
FUNCTIONS
67
John Elder
In this chapter we rolled up our sleeves and built our own little Python
machines—functions!
You learned how to define a function using the def keyword, how to call
it by name to make it run, and how to pass in information using
parameters and arguments.
You also saw how to give your function parameters default values,
which is super handy when you want your function to work even if no
info is passed in.
Instead of repeating code over and over, you can name it, pack it into a
function, and reuse it any time you like.
Let’s keep the momentum going with some offbeat, hands-on exercises
to drive this home.
68
Codemy.com
Exercise 7.1
The Spam Factory
Write a function called spam_repeater that takes two parameters: a word
and a number. It should print the word that number of times, once per
line. Call it with "SPAM" and 7.
Exercise 7.2
Mad Libs: Python Edition
Write a function called mad_lib that takes three arguments: name, color,
and animal. It should print a silly sentence using all three, like “Once
upon a time, <name> met a <color> <animal>.” Call it at least three times
with different inputs.
Exercise 7.3
Default Insult Generator
Create a function called insult that takes two parameters: name and
adjective. Both should have default values: "you" and "smelly". The
function should print “Hey <name>, you’re so <adjective>!” Call it with
no arguments, then with one, then with two.
Exercise 7.4
Fighter Intro Announcer
Write a function called intro that takes three arguments: name, power,
and weapon. It should print “Prepare yourselves! <name> arrives,
wielding <weapon>, powered by <power>!” Call it three times with
different combinations.
69
John Elder
Exercise 7.5
Emoji Printer
Write a function called print_emojis that takes two parameters: an emoji
and a number. It should print that emoji that number of times, all on one
line. Use it to print 20 fire emojis, 10 thumbs-up emojis, and 3 alien
emojis.
Exercise 7.6
Custom Liner
Write a function called draw_line that takes two arguments: a character
(default is "*") and a length (default is 10). It should print a line using the
character repeated the given number of times. Call it with no arguments,
then with "-", 20.
Exercise 7.7
Build-A-Band
Create a function called band_setup that takes three arguments: singer,
guitarist, and drummer. Make drummer a default parameter set to
"Drum Machine". It should print “Now performing: <singer> on vocals,
<guitarist> on guitar, and <drummer> on drums!” Try calling it with and
without the drummer.
70
Codemy.com
Exercise 7.8
Code Red Alert
Define a function called alert that takes two parameters: level and
message. It should print “[<level>] ALERT: <message>!” Call it three
times using levels like “INFO”, “WARNING”, and “PANIC”.
Exercise 7.9
Commentator Combo
Write a function called battle_log that takes three parameters: hero,
villain, and location. Give location a default value like “on a volcano”. It
should print “Today, <hero> will face off against <villain> <location>.”
Call it once with and once without a location.
Exercise 7.10
Function Multipack
Create three functions:
- open_box prints “You opened the box!”
- surprise prints “A snake jumps out!”
- open_surprise_box calls the first two in order
71
John Elder
spam_repeater("SPAM", 7)
Answer 7.2
Answer 7.3
insult()
insult("Bob")
insult("Karen", "loud")
72
Codemy.com
Answer 7.4
Answer 7.5
print_emojis("🔥🔥", 20)
print_emojis("👍👍", 10)
print_emojis("👽👽", 3)
Answer 7.6
draw_line()
draw_line("-", 20)
73
John Elder
Answer 7.7
Answer 7.8
Answer 7.9
74
Codemy.com
Answer 7.10
def open_box():
print("You opened the box!")
def surprise():
print("A snake jumps out!")
def open_surprise_box():
open_box()
surprise()
open_surprise_box()
75
John Elder
CHAPTER EIGHT
DICTIONARIES
76
Codemy.com
You’ve got keys, and each key is connected to a value. It’s like a super-
powered list where you don’t have to remember what position
something is in—you just use its label instead.
In this chapter, you learned how to make dictionaries with curly braces,
how to add key-value pairs, how to change existing values, how to loop
through all the items, and how to get the value associated with a key.
Let’s reinforce what you’ve learned with some practical and (slightly
ridiculous) exercises.
77
John Elder
Exercise 8.1
Escape Room Profile Loader
Create a dictionary called player that stores a game player’s name,
inventory count, access level, and location. After defining it, simulate the
player picking up an item by increasing the inventory count by 1, then
changing their location to “Vault”. Finally, print a sentence that uses
both updated values.
Exercise 8.2
Build-a-Planet
Create a dictionary called planet that includes keys like name,
number_of_moons, and breathable (True or False). Then add a new key
called danger_level with a value of your choice. Print a full sentence for
each key-value pair that describes the planet (example: This planet has 2
moons).
Exercise 8.3
Quiz Score Evaluator
Create a dictionary called quiz_scores with at least four students and
their numeric scores. Then loop through the dictionary and print a
custom message for each student: if their score is 70 or higher, say they
passed; otherwise, say they need to study more.
78
Codemy.com
Exercise 8.4
Monster Weakness Map
Create a dictionary that maps three fictional monster names to their
weaknesses. Then write a loop that prints out a warning for each one,
like: Warning: To defeat Slarg, use fire.
Exercise 8.5
Shopping Cart Updater
Start with an empty dictionary called shopping_cart. Then add at least
three items to it where the keys are product names and the values are
prices. Then increase the price of one item by 10 and print the full cart.
Exercise 8.6
Menu Calorie Counter
Create a dictionary called menu with three dishes and their calorie
counts. Write a loop that calculates and prints the total number of
calories for all dishes combined.
Exercise 8.7
Currency Converter
Write a dictionary that maps three countries to their currency (like USA
to dollar). Then simulate changing the currency of one of them (for
example, Italy from lira to euro) and print before and after.
79
John Elder
Exercise 8.8
Vote Tally Simulator
Create a dictionary called votes with at least five candidate names as
keys and zero as the starting vote count. Then simulate 10 random votes
by manually incrementing different candidates' counts. Print the final
tally.
Exercise 8.9
Winter Wardrobe Filter
Make a dictionary called wardrobe that has clothing items as keys and
seasons as values. Write a loop that filters and prints only the clothing
items appropriate for winter.
Exercise 8.10
Zoo Inventory Tracker
Build a nested dictionary called zoo where each key is an animal species
and the value is another dictionary with keys like count and habitat.
Add three animals. Then loop through and print out a summary line for
each one.
80
Codemy.com
player = {
"name": "Eli",
"inventory_count": 3,
"access_level": "basic",
"location": "Lobby"
}
player["inventory_count"] += 1
player["location"] = "Vault"
print("Player now has", player["inventory_count"], "items and is in",
player["location"])
Answer 8.2
planet = {
"name": "Xenor",
"number_of_moons": 2,
"breathable": False
}
planet["danger_level"] = "high"
81
John Elder
Answer 8.3
quiz_scores = {
"Alice": 85,
"Bob": 67,
"Charlie": 73,
"Daisy": 59
}
for student in quiz_scores:
score = quiz_scores[student]
if score >= 70:
print(student + " passed!")
else:
print(student + " needs to study more.")
Answer 8.4
monsters = {
"Slarg": "fire",
"Grumble": "ice",
"Flarp": "sunlight"
}
for name in monsters:
print("Warning: To defeat " + name + ", use " + monsters[name] + ".")
82
Codemy.com
Answer 8.5
shopping_cart = {}
shopping_cart["tofu"] = 3.50
shopping_cart["bread"] = 2.00
shopping_cart["salsa"] = 4.25
shopping_cart["salsa"] = shopping_cart["salsa"] + 1.00
print(shopping_cart)
Answer 8.6
menu = {
"burrito": 550,
"salad": 320,
"smoothie": 410
}
total = 0
for dish in menu:
total += menu[dish]
print("Total calories:", total)
83
John Elder
Answer 8.7
currencies = {
"USA": "dollar",
"Japan": "yen",
"Italy": "lira"
}
print("Before:", currencies)
currencies["Italy"] = "euro"
print("After:", currencies)
Answer 8.8
votes = {
"Ava": 0,
"Ben": 0,
"Cara": 0,
"Dan": 0,
"Elle": 0
}
votes["Ava"] += 3
votes["Ben"] += 1
votes["Cara"] += 2
votes["Dan"] += 2
votes["Elle"] += 2
print(votes)
84
Codemy.com
Answer 8.9
wardrobe = {
"scarf": "winter",
"tank top": "summer",
"boots": "winter",
"shorts": "summer",
"jacket": "winter"
}
for item in wardrobe:
if wardrobe[item] == "winter":
print(item)
85
John Elder
Answer 8.10
zoo = {
"giraffe": {
"count": 5,
"habitat": "savannah"
},
"penguin": {
"count": 12,
"habitat": "ice cave"
},
"koala": {
"count": 3,
"habitat": "eucalyptus grove"
}
}
for animal in zoo:
info = zoo[animal]
print(animal + ": " + str(info["count"]) + " in " + info["habitat"])
86
Codemy.com
CHAPTER NINE
IS THIS THING ON?!
87
John Elder
This is where Python starts to feel powerful. You’re not just printing
stuff anymore—you’re interacting.
In this workbook chapter, you’ll rework and remix those same ideas:
using dictionaries to store prompts, looping through them, calling
functions to organize behavior, and adding your own twists to the
format.
These problems are designed to help you take full ownership of this
pattern.
88
Codemy.com
Exercise 9.1
Riddle Dictionary
Create a dictionary called riddles with at least three riddles as keys and
their answers as values. Loop through the dictionary and print each
riddle followed by the correct answer (you’re not asking the user—just
displaying the Q&A).
Exercise 9.2
run_quiz Function
Write a function called run_quiz that takes a dictionary of questions and
correct answers. Inside the function, loop through the questions, ask the
user for input, and compare it to the correct answer. At the end, print
how many they got right.
Exercise 9.3
Math Fact Checker
Make a dictionary called math_facts where the keys are simple math
problems as strings (like 5 + 3) and the values are correct answers as
integers. Write a loop that asks the user each question and compares the
user’s input (converted to int) to the answer.
Exercise 9.4
trivia_round Function
Create a function called trivia_round that accepts a player name and
then runs a quiz round using a fixed dictionary of three trivia questions.
Print the player’s name and final score at the end.
89
John Elder
Exercise 9.5
Simulated Speed Quiz
Write a function called speed_quiz that loops through a question
dictionary but only gives the user 5 seconds to answer each question.
(Note: Just simulate the time limit with a message, no timing code
required.)
Exercise 9.6
Vocabulary Reflection Quiz
Create a dictionary of vocabulary words where the key is a fancy word
and the value is a plain definition. Write a loop that prints each word
and asks the user to guess what it means. Don’t score it—just for
reflection.
Exercise 9.7
Case-Insensitive Quiz
Write a function called all_caps_quiz that takes a question-answer
dictionary and accepts user input normally, but converts both the input
and correct answer to uppercase before comparing. This makes it case-
insensitive.
90
Codemy.com
Exercise 9.8
Error Type Quiz
Create a dictionary of common Python errors (like NameError,
TypeError, etc.) and their descriptions. Loop through and ask the user to
type in the correct error type based on the description. Score 1 point for
each correct match.
Exercise 9.9
Emoji Meaning Quiz
Write a quiz game where the dictionary stores emoji as keys and words
like smile or alien as the correct answers. Ask the user what each emoji
means. At the end, print how many they got right.
Exercise 9.10
Custom Flashcard Builder
Create a function called custom_flashcards that asks the user to enter
three new question-answer pairs (via input) and adds them to a
dictionary. Then loop through that dictionary and quiz the user using
what they just created.
91
John Elder
riddles = {
"What has hands but can’t clap?": "A clock",
"What has a head and a tail but no body?": "A coin",
"What gets wetter as it dries?": "A towel"
}
Answer 9.2
def run_quiz(questions):
score = 0
for q in questions:
answer = input(q + " ")
if answer == questions[q]:
score += 1
print("You got", score, "out of", len(questions), "correct.")
quiz = {
"What’s the capital of France?": "Paris",
"2 + 2?": "4",
"What color is the sky?": "blue"
}
run_quiz(quiz)
92
Codemy.com
Answer 9.3
math_facts = {
"5 + 3": 8,
"10 - 6": 4,
"7 * 2": 14
}
Answer 9.4
def trivia_round(name):
score = 0
trivia = {
"What planet is known as the Red Planet?": "Mars",
"Who wrote Hamlet?": "Shakespeare",
"What’s the largest ocean?": "Pacific"
}
for q in trivia:
answer = input(q + " ")
if answer == trivia[q]:
score += 1
print(name + ", your score is", score)
trivia_round("Ava")
93
John Elder
Answer 9.5
def speed_quiz():
questions = {
"What’s 9 + 10?": "19",
"What comes after Tuesday?": "Wednesday"
}
for q in questions:
print(q + " (You have 5 seconds to answer!)")
answer = input("> ")
if answer == questions[q]:
print("Correct!")
else:
print("Wrong!")
speed_quiz()
Answer 9.6
vocab = {
"gregarious": "sociable",
"obfuscate": "to confuse",
"benevolent": "kind"
}
94
Codemy.com
Answer 9.7
def all_caps_quiz(qset):
score = 0
for q in qset:
answer = input(q + " ")
if answer.upper() == qset[q].upper():
score += 1
print("Score:", score)
questions = {
"What’s the opposite of hot?": "cold",
"What color are bananas?": "yellow"
}
all_caps_quiz(questions)
95
John Elder
Answer 9.8
errors = {
"Raised when a variable doesn’t exist": "NameError",
"Raised when you add a number to a string": "TypeError",
"Raised when you divide by zero": "ZeroDivisionError"
}
score = 0
for desc in errors:
guess = input(desc + ": ")
if guess == errors[desc]:
score += 1
Answer 9.9
emoji_quiz = {
"😊😊": "smile",
"🔥🔥": "fire",
"👽👽": "alien"
}
score = 0
for e in emoji_quiz:
answer = input("What does " + e + " mean? ")
if answer == emoji_quiz[e]:
score += 1
96
Codemy.com
Answer 9.10
def custom_flashcards():
custom = {}
for i in range(3):
question = input("Enter a question: ")
answer = input("Enter the answer: ")
custom[question] = answer
for q in custom:
user = input(q + " ")
if user == custom[q]:
print("Correct!")
else:
print("Incorrect.")
custom_flashcards()
97
John Elder
CONCLUSION
You Did It—Seriously
If you’ve made it this far, congratulations! You now know more about
Python than most people who say they want to learn to code.
You learned how to store things, retrieve them, manipulate them, and
loop over them.
Then you leveled up and learned how to write your own functions—
mini-programs that let you reuse logic, clean up your code, and organize
your thinking.
98
Codemy.com
That wasn’t just a theoretical exercise. That was real software, made by
you.
The important thing now isn’t just that you finished the book—it’s what
that means.
You’ve seen the core building blocks of Python, and more importantly,
you’ve used them. You’ve written real code and made it do what you
want.
So don’t stop here. Keep building. Make small projects. Break things. Fix
them.
This is where programming gets fun, and you’ve already done the hard
part.
You’re not just someone who wants to learn Python. You’re someone
who knows how to write Python.
99
John Elder
APPENDIX ONE
But here’s the truth: knowing about Python isn’t the same as being able
to use it. If you really want to get good, you need to build stuff.
No fluff, no filler, just actual applications that teach you how to think like
a programmer and use Python to solve real problems.
100
Codemy.com
10. To-Do List App – Create your own productivity app using basic
GUI structure.
11. Word Count Tool – Work with text files and count words with
file I/O.
12. Tic Tac Toe Game – Master game flow, input handling, and win
detection.
13. Draw with Turtle – Use the Turtle graphics module to code
creative designs.
14. Image Resizer – Resize and process images for personal or web
use.
101
John Elder
15. Anagram Solver – Solve and detect anagrams using clever logic
and lists.
16. Typing Speed Test – Create a timed typing tool to test speed and
accuracy.
The full course normally sells for $129, but as a thank-you for working
through this workbook, you can grab it now for just $64 here:
https://order.codemy.com/python-projects-64
102
Codemy.com
If you liked this workbook, you’ll love the course. Hope to see you
inside.
—John Elder
Founder, Codemy.com
103
John Elder
104
Codemy.com
105
John Elder
THE END
106
Codemy.com
NOTES
107
John Elder
NOTES
108
Codemy.com
NOTES
109
John Elder
NOTES
110
Codemy.com
NOTES
111
John Elder
NOTES
112
Codemy.com
NOTES
113
John Elder
NOTES
114
Codemy.com
115