Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

OOP I(Python+java) (1)

we
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

OOP I(Python+java) (1)

we
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 264

PYTHON II

DRONA FOUNDATION
BVOC - IT
Sr No INDEX
1 Article

1 Modules in Python
1.1 Modules Python Introduction
1.2 Modules Python Random
Modules Python Namespaces
1.3
1.4 Modules Python Decimals
1.5 Modules Python Files and Scope
1.6 Modules Python Review
1 Concept Review

2 CREATING DICTIONARIES
2.1 Introduction to Python Dictionaries
2.2 Make a Dictionary
2.3 Invalid Keys
2.4 Empty Dictionary
Add A Key
2.5
2.6 Add Multiple Keys
2.7 Overwrite Values
2.8 Dict Comprehensions
2.9 Review
2 Concept Review
2 Quiz

3 USING DICTIONARIES
3.1 Using Dictionaries
3.2 Get A Key
3.3 Get an Invalid Key
3.4 Safely Get a Key
3.5 Delete a Key
3.6 Get All Keys
3.7 Get All Values
3.8 Get All Items
1
3.9 Review
3 Concept Review
1 Project : Scrabble
3 Quiz
2 Article

4 LEARN PYTHON: FILES


4.1 Reading a File
4.2 Iterating Through Lines
4.3 Reading a Line
4.4 Writing a File
4.5 Appending to a File
4.6 What's With "with"?
4.7 What Is a CSV File?
4.8 Reading a CSV File
4.9 Reading Different Types of CSV Files
4.1 Writing a CSV File
4.11 Reading a JSON File
4.12 Writing a JSON File
4.4 Review
4 Concept Review
4 Quiz
2 Project : Hacking The Fender

5 INTRODUCTION TO CLASSES
5.1 Types
5.2 Class
5.3 Instantiation
5.4 Object-Oriented Programming
5.5 Class Variables
5.6 Methods
5.7 Methods with Arguments
5.8 Constructors
5.9 Instance Variables
5.10 Attribute Functions
5.11 Self

2
5.12 Everything is an Object
5.13 String Representation
5.14 Review
5 Concept Review
5 Quiz
3 Project : Basta Fazoolin’
3 Article
4 Article
5 Article
6 Article
7 Article
8 Article

JAVA
1 HELLO WORLD
1.1 Introduction to Java
1.2 Hello Java File!
1.3 Print Statements
1.4 Commenting Code
1.5 Semicolons and Whitespace
1.6 Compilation: Catching Errors
1.7 Compilation: Creating Executables
1.8 Java Review: Putting It All Together
1 Quiz
1 Project : Planting a Tree
Concept Review

2 VARIABLES
2.1 Introduction
2.2 Ints
2.3 Doubles
2.4 Booleans
2.5 Char
2.6 String
2.7 Static Checking
2.8 Naming

3
2.9 Review
2 Quiz
2 Project : Java Variables : Mad Libs
Concept Review

3 Manipulating Variables
3.1 Introduction
3.2 Addition and Subtraction
3.3 Multiplication and Division
3.4 Modulo
3.5 Compound Assignment Operators
3.6 Order of Operations
3.7 Greater Than and Less Than
3.8 Equals and Not Equals
3.9 Greater/Less Than or Equal To
3.10 .equals()
3.11 String Concatenation
3.12 final Keyword
3.13 Review
3 Quiz
3 Project : Math Magic

4
1.Article

Off-Platform Project: Coded Correspondence

In this off-platform project, you will be exchanging coded communications with


your pen pal, Vishal. The two of you challenge each other by sending coded
messages that you will have to use your Python skills to decipher! Put your
programming skills to the test with these fun cryptography puzzles.
Follow the steps below to get started with your project!
Working on Your Computer
1. If you’ve never used the command line, we recommend taking the Learn
the Command Line course.
2. Install Python by following the directions in this article on Installing Python.
3. Learn about Jupyter Notebooks, a cool way of combining Python code with
explanations or instruction in a web terminal.
4. Download the project: Coded Correspondence
5. Unzip it by double-clicking on it.
6. In the terminal, navigate to the directory containing the project, and type:
jupyter notebook
This should open a browser tab.
7. Click on coded_correspondence.ipynb in the browser tab. This will open up
your Jupyter Notebook.
8. Follow the steps in the Jupyter Notebook. If you get stuck, you can look
at coded_correspondence_solutions.ipynb for the answer.
This is a challenging project! Be prepared to come up with your own creative
methods of solving the problems!

5
1. Modules in Python
1.1 Modules Python Introduction

In the world of programming, we care a lot about making code reusable. In most
cases, we write code so that it can be reusable for ourselves. But sometimes we
share code that’s helpful across a broad range of situations.
In this lesson, we’ll explore how to use tools other people have built in Python
that are not included automatically for you when you install Python. Python
allows us to package code into files or sets of files called modules.
A module is a collection of Python declarations intended broadly to be used as a
tool. Modules are also often referred to as “libraries” or “packages” — a package
is really a directory that holds a collection of modules.
Usually, to use a module in a file, the basic syntax you need at the top of that file
is:
from module_name import object_name
Often, a library will include a lot of code that you don’t need that may slow down
your program or conflict with existing code. Because of this, it makes sense to
only import what you need.
One common library that comes as part of the Python Standard Library
is datetime. datetime helps you work with dates and times in Python.
Let’s get started by importing and using the datetime module. In this case, you’ll
notice that datetime is both the name of the library and the name of the object
that you are importing.

1.1 Modules Python Introduction Instructions


6
1.
In script.py import the datetime type from the datetime library.
2.
Create a variable current_time and set it equal to datetime.now().
3.
Print out current_time.

OUTPUT
2023-04-12 05:39:51.465704

1.2 Modules Python Random

datetime is just the beginning. There are hundreds of Python modules that you
can use. Another one of the most commonly used is random which allows you to
generate numbers or select items at random.
With random, we’ll be using more than one piece of the module’s functionality,
so the import syntax will look like:
import random
We’ll work with two common random functions:
• random.choice() which takes a list as an argument and returns a number
from the list
• random.randint() which takes two numbers as arguments and generates a
random number between the two numbers you passed in
Let’s take randomness to a whole new level by picking a random number from a
list of randomly generated numbers between 1 and 10.

7
1.2 Modules Python Random Instructions
1.
In script.py import the random library.

2.
Create a variable random_list and set it equal to an empty list
3.
Turn the empty list into a list comprehension that uses random.randint() to
generate a random integer between 1 and 10 (inclusive) for each number
in range(11).

4.
Create a new variable randomer_number and set it equal
to random.choice() with random_list as an argument.
5.
Print randomer_number out to see what number was picked!

# Import random below:

# Create random_list below:


# Create randomer_number below:
# Print randomer_number below:

8
OUTPUT
12

1.3 Modules Python Namespaces

Notice that when we want to invoke the randint() function we


call random.randint(). This is default behavior where Python offers
a namespace for the module. A namespace isolates the functions, classes, and
variables defined in the module from the code in the file doing the importing.
Your local namespace, meanwhile, is where your code is run.
Python defaults to naming the namespace after the module being imported, but
sometimes this name could be ambiguous or lengthy. Sometimes, the module’s
name could also conflict with an object you have defined within your local
namespace.
Fortunately, this name can be altered by aliasing using the as keyword:
import module_name as name_you_pick_for_the_module
Aliasing is most often done if the name of the library is long and typing the full
name every time you want to use one of its functions is laborious.
You might also occasionally encounter import *. The * is known as a “wildcard”
and matches anything and everything. This syntax is considered dangerous
because it could pollute our local namespace. Pollution occurs when the same
name could apply to two possible things. For example, if you happen to have a
function floor() focused on floor tiles, using from math import * would also
import a function floor() that rounds down floats.
Let’s combine your knowledge of the random library with another fun library
called matplotlib, which allows you to plot your Python code in 2D.
You’ll use a new random function random.sample() that takes a range and a
number as its arguments. It will return the specified number of random numbers
from that range.
9
#random.sample takes a list and randomly selects k items from it
new_list = random.sample(list, k)
#for example:
nums = [1, 2, 3, 4, 5]
sample_nums = random.sample(nums, 3)
print(sample_nums) # 2, 5, 1

1.3 Modules Python Namespaces Instructions


1.
Below import codecademylib3_seaborn, import pyplot from the
module matplotlib with the alias plt.

2.
Import random below the other import statements. It’s best to keep all imports at
the top of your file.
3.
Create a variable numbers_a and set it equal to the range of numbers 1 through
12 (inclusive).
4.
Create a variable numbers_b and set it equal to a random sample of twelve
numbers within range(100).
Feel free to print numbers_b to see your random sample of numbers.
5.
Now let’s plot these number sets against each other using plt. Call plt.plot() with
your two variables as its arguments.
6.
Now call plt.show() and run your code!

10
You should see a graph of random numbers displayed. You’ve used two Python
modules to accomplish this (random and matplotlib).

import codecademylib3_seaborn

# Add your code below:

OUTPUT

1.4 Modules Python Decimals

Let’s say you are writing software that handles monetary transactions. If you used
Python’s built-in floating-point arithmetic to calculate a sum, it would result in a
weirdly formatted number.
cost_of_gum = 0.1
cost_of_gumdrop = 0.35

11
cost_of_transaction = cost_of_gum + cost_of_gumdrop
# Returns 0.44999999999999996
Being familiar with rounding errors in floating-point arithmetic you want to use a
data type that performs decimal arithmetic more accurately. You could do the
following:
from decimal import Decimal

cost_of_gum = Decimal('0.1')
cost_of_gumdrop = Decimal('0.35')

cost_of_transaction = cost_of_gum + cost_of_gumdrop


# Returns 0.45 instead of 0.44999999999999996
Above, we use the decimal module’s Decimal data type to add 0.1 with 0.35.
Since we used the Decimal type the arithmetic acts much more as expected.
Usually, modules will provide functions or data types that we can then use to
solve a general problem, allowing us more time to focus on the software that we
are building to solve a more specific problem.
Ready, set, fix some floating point math by using decimals!

1.4 Modules Python Decimals Instructions


1.
Run your code to see the weird floating point math that occurs.
2.
In script.py import Decimal from the decimal module.
3.
Use Decimal to make two_decimal_points only have two decimals points
and four_decimal_points to only have four decimal points.

12
# Import Decimal below:

# Fix the floating point math below:


two_decimal_points = 0.2 + 0.69
print(two_decimal_points)

four_decimal_points = 0.53 * 0.65


print(four_decimal_points)

OUTPUT
0.89
0.3445

1.5 Modules Python Files and Scope

You may remember the concept of scope from when you were learning about
functions in Python. If a variable is defined inside of a function, it will not be
accessible outside of the function.
Scope also applies to classes and to the files you are working within.
Files have scope? You may be wondering.
Yes. Even files inside the same directory do not have access to each other’s
variables, functions, classes, or any other code. So if I have a
file sandwiches.py and another file hungry_people.py, how do I give my hungry
people access to all the sandwiches I defined?

13
Well, files are actually modules, so you can give a file access to another file’s
content using that glorious import statement.
With a single line of from sandwiches import sandwiches at the top
of hungry_people.py, the hungry people will have all the sandwiches they could
ever want.

1.5 Modules Python Files and Scope Instructions


1.
Tab over to library.py and define a function always_three() with no parameters
that returns 3.

2.
Call your always_three() function in script.py. Check out that error message you
get in the output terminal and the consequences of file scope.
3.
Resolve the error with an import statement at the top of script.py that imports
your function from library. Run your code and watch import do its magic!

1.6 Modules Python Review

You’ve learned:
• what modules are and how they can be useful
• how to use a few of the most commonly used Python libraries
• what namespaces are and how to avoid polluting your local namespace
• how scope works for files in Python

14
Programmers can do great things if they are not forced to constantly reinvent
tools that have already been built. With the power of modules, we can import any
code that someone else has shared publicly.
In this lesson, we covered some of the Python Standard Library, but you can
explore all the modules that come packaged with every installation of Python at
the Python Standard Library documentation.
This is just the beginning. Using a package manager (like conda or pip3), you can
install any modules available on the Python Package Index.
The sky’s the limit!

__________________________________________
Concept Review

Date and Time in Python

Python provides a module named datetime to deal with dates and times.
It allows you to set date ,time or both date and time using
the date(),time()and datetime() functions respectively, after importing
the datetime module .
import datetime
feb_16_2019 = datetime.date(year=2019, month=2, day=16)
feb_16_2019 = datetime.date(2019, 2, 16)
print(feb_16_2019) #2019-02-16

time_13_48min_5sec = datetime.time(hour=13, minute=48, second=5)


time_13_48min_5sec = datetime.time(13, 48, 5)
15
print(time_13_48min_5sec) #13:48:05

timestamp= datetime.datetime(year=2019, month=2, day=16, hour=13,


minute=48, second=5)
timestamp = datetime.datetime(2019, 2, 16, 13, 48, 5)
print (timestamp) #2019-01-02 13:48:05

Aliasing with ‘as’ keyword

In Python, the as keyword can be used to give an alternative name as an alias for
a Python module or function.
# Aliasing matplotlib.pyplot as plt
from matplotlib import pyplot as plt
plt.plot(x, y)

# Aliasing calendar as c
import calendar as c
print(c.month_name[1])

Import Python Modules

The Python import statement can be used to import Python modules from other
files.
Modules can be imported in three different ways: import module, from module
import functions, or from module import *. from module import * is discouraged,
16
as it can lead to a cluttered local namespace and can make the namespace
unclear.
# Three different ways to import modules:
# First way
import module
module.function()

# Second way
from module import function
function()

# Third way
from module import *
function()

random.randint() and random.choice()

In Python, the random module offers methods to simulate non-deterministic


behavior in selecting a random number from a range and choosing a random item
from a list.
The randint() method provides a uniform random selection from a range of
integers. The choice() method provides a uniform selection of a random element
from a sequence.
# Returns a random integer N in a given range, such that start <= N <= end
# random.randint(start, end)

17
r1 = random.randint(0, 1)
print(r1) # Random integer where 0 <= r1 <= 1

# Prints a random element from a sequence


seq = ["a", "b", "c", "d", "e"]
r2 = random.choice(seq)
print(r2) # Random element in the sequence

Module importing

In Python, you can import and use the content of another file using import
filename, provided that it is in the same folder as the current file you are writing.
# file1 content
# def f1_function():
# return "Hello World"

# file2
import file1

# Now we can use f1_function, because we imported file1


f1_function()

__________________________________________

18
Learn Python: Datetimes
VIDEO:
https://youtu.be/smDBZDvsm0I

__________________________________________
Learn Python: pipenv

In this article, you’ll learn how to install pipenv on Windows, MacOS, and
Chromebook computers.
Installing pipenv on MacOS and Windows

VIDEO:
https://youtu.be/BVr-6Ki96XM

19
2.CREATING DICTIONARIES
2.1 Introduction to Python Dictionaries

A dictionary is an unordered set of key: value pairs.


It provides us with a way to map pieces of data to each other so that we can
quickly find values that are associated with one another.
Suppose we want to store the prices of various items sold at a cafe:
• Avocado Toast is 6 dollars
• Carrot Juice is 5 dollars
• Blueberry Muffin is 2 dollars
In Python, we can create a dictionary called menu to store this data:
menu = {"avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
Notice that:
1. A dictionary begins and ends with curly braces { and }.
2. Each item consists of a key ("avocado toast") and a value (6).
3. Each key: value pair is separated by a comma.
It’s considered good practice to insert a space () after each comma, but our code
will still run without the space.

2.1 Introduction to Python Dictionaries Instructions


1.

20
Suppose we have a dictionary of temperature sensors in the house and what
temperatures they read. We’ve just added a sensor to the "pantry", and it reads
22 degrees.
Add this pair to the dictionary on line 1.

2.
Remove the # in front of the definition of the dictionary num_cameras, which
represents the number of cameras in each area around the house.
If you run this code, you’ll get an error:
SyntaxError: invalid syntax
Try to find and fix the syntax error to make this code run.

sensors = {"living room": 21, "kitchen": 23, "bedroom": 20}


#num_cameras = {"backyard": 6 "garage": 2 "driveway": 1}

print(sensors)

OUTPUT
{'living room': 21, 'kitchen': 23, 'bedroom': 20}

2.2 Make a Dictionary

In the previous exercise, we saw a dictionary that maps strings to numbers


(i.e., "avocado toast": 6). However, the keys can be numbers as well.

21
For example, if we were mapping restaurant bill subtotals to the bill total after
tip, a dictionary could look like:
subtotal_to_total = {20: 24, 1: 12, 5: 6, 15: 18}
Values can be of any type. We can use a string, a number, a list, or even another
dictionary as the value associated with a key!
For example:
students_in_classes = {"software design": ["Aaron", "Delila", "Samson"],
"cartography": ["Christopher", "Juan", "Marco"], "philosophy": ["Frederica",
"Manuel"]}
The list ["Aaron", "Delila", "Samson"], which is the value for the key "software
design", represents the students in that class.
We can also mix and match key and value types. For example:
person = {"name": "Shuri", "age": 18, "family": ["T'Chaka", "Ramonda"]}

2.2 Make a Dictionary Instructions


1.
Create a dictionary called translations that maps the following words in English to
their definitions in Sindarin (the language of the elves):
English Sindarin
mountain orod
bread bass
friend mellon
horse roch

22
2.3 Invalid Keys

We can have a list or a dictionary as a value of an item in a dictionary, but we


cannot use these data types as keys of the dictionary. If we try to, we will get
a TypeError.
For example:
powers = {[1, 2, 4, 8, 16]: 2, [1, 3, 9, 27, 81]: 3}
This code will yield:
TypeError: unhashable type: 'list'
The word “unhashable” in this context means that this ‘list’ is an object that can
be changed.
Dictionaries in Python rely on each key having a hash value, a specific identifier
for the key. If the key can change, that hash value would not be reliable. So the
keys must always be unchangeable, hashable data types, like numbers or strings.

2.3 Invalid Keys Instructions


1.
Run the code inside script.py. You should get an error:
TypeError: unhashable type
Make the code run without errors by flipping the items in the dictionary so that
the strings are the keys and the lists are the values

children = {["Johannes", "Rosmarie", "Eleonore"]: "von Trapp", ["Sonny", "Fredo",


"Michael"]: "Corleone"}

2.4 Empty Dictionary


23
A dictionary doesn’t have to contain anything. Sometimes we need to create an
empty dictionary when we plan to fill it later based on some other input.
We can create an empty dictionary like this:
empty_dict = {}
We will explore ways to fill a dictionary in the next exercise.

2.4 Empty Dictionary Instructions


1.
Create an empty dictionary called my_empty_dictionary.

2.5 Add A Key


To add a single key: value pair to a dictionary, we can use the syntax:
dictionary[key] = value
For example, if we had our menu dictionary from the first exercise:
menu = {"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
And we wanted to add a new item, "cheesecake" for 8 dollars, we could use:
menu["cheesecake"] = 8
Now, menu looks like:
{"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2,
"cheesecake": 8}

2.5 Add A Key Instructions


1.
Create an empty dictionary called animals_in_zoo.
2.
24
Walking around the zoo, you see 8 zebras. Add "zebras" to animals_in_zoo as a
key with a value of 8.
3.
The primate house was bananas! Add "monkeys" to animals_in_zoo as a key with
a value of 12.
4.
As you leave the zoo, you are saddened that you did not see any dinosaurs.
Add "dinosaurs" to animals_in_zoo as a key with a value of 0.
5.
Print animals_in_zoo.

OUTPUT
{'zebras': 8, 'monkeys': 12, 'dinosaurs': 0}

2.6 Add Multiple Keys

If we wanted to add multiple key : value pairs to a dictionary at once, we can use
the .update() method.
Looking at our sensors object from a previous exercise:
sensors = {"living room": 21, "kitchen": 23, "bedroom": 20}
If we wanted to add 3 new rooms, we could use:
sensors.update({"pantry": 22, "guest room": 25, "patio": 34})
This would add all three items to the sensors dictionary.
Now, sensors looks like:

25
{"living room": 21, "kitchen": 23, "bedroom": 20, "pantry": 22, "guest room": 25,
"patio": 34}

2.6 Add Multiple Keys Instructions


1.
In one line of code, add two new users to the user_ids dictionary:
• theLooper, with an id of 138475
• stringQueen, with an id of 85739

2.
Print user_ids.

OUTPUT
{'teraCoder': 9018293, 'proProgrammer': 119238, 'theLooper': 138475,
'stringQueen': 85739}

2.7 Overwrite Values

We know that we can add a key by using the following syntax:


menu["banana"] = 3
This will create a key "banana" and set its value to 3. But what if we used a key
that already has an entry in the menu dictionary?
In that case, our value assignment would overwrite the existing value attached to
that key. We can overwrite the value of "oatmeal" like this:

26
menu = {"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
menu["oatmeal"] = 5
print(menu)
This would yield:
{"oatmeal": 5, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
Notice the value of "oatmeal" has now changed to 5.

2.7 Overwrite Values Instructions


1.
Add the key "Supporting Actress" and set the value to "Viola Davis".
2.
Without changing the definition of the dictionary oscar_winners, change the
value associated with the key "Best Picture" to "Moonlight".

oscar_winners = {"Best Picture": "La La Land", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}

2.8 Dict Comprehensions

Let’s say we have two lists that we want to combine into a dictionary, like a list of
students and a list of their heights, in inches:
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
heights = [61, 70, 67, 64]
Python allows you to create a dictionary using a dict comprehension, with this
syntax:

27
students = {key:value for key, value in zip(names, heights)}
#students is now {'Jenny': 61, 'Alexus': 70, 'Sam': 67, 'Grace': 64}
Remember that zip() combines two lists into an iterator of tuples with the list
elements paired together. This dict comprehension:
1. Takes a pair from the iterator of tuples
2. Names the elements in the pair key (the one originally from the names list)
and value (the one originally from the heights list)
3. Creates a key : value item in the students dictionary
4. Repeats steps 1-3 for the entire iterator of pairs

2.8 Dict Comprehensions Instructions


1.
You have two lists, representing some drinks sold at a coffee shop and the
milligrams of caffeine in each. First, create a variable called zipped_drinks that is
an iterator of pairs between the drinks list and the caffeine list.

2.
Create a dictionary called drinks_to_caffeine by using a dict comprehension that
goes through the zipped_drinks iterator and turns each tuple pair into a key:value
item.

drinks = ["espresso", "chai", "decaf", "drip"]


caffeine = [64, 40, 0, 120]

2.9 Review
So far we have learned:

28
• How to create a dictionary
• How to add elements to a dictionary
• How to update elements in a dictionary
• How to use a dict comprehension to create a dictionary from two lists
Let’s practice these skills!

2.9 Review Instructions


1.
We are building a music streaming service. We have provided two lists,
representing songs in a user’s library and the amount of times each song has been
played.
Using a dict comprehension, create a dictionary called plays that goes
through zip(songs, playcounts) and creates a song:playcount pair for
each song in songs and each playcount in playcounts.

2.
Print plays.
3.
After printing plays, add a new entry to it. The entry should be for the
song "Purple Haze" and the playcount is 1.
4.
This user has caught Aretha Franklin fever and listened to “Respect” 5 more
times. Update the value for "Respect" to be 94 in the plays dictionary.
5.
Create a dictionary called library that has two key: value pairs:
• key "The Best Songs" with a value of plays, the dictionary you created

29
• key "Sunday Feelings" with a value of an empty dictionary
6.
Print library.

songs = ["Like a Rolling Stone", "Satisfaction", "Imagine", "What's Going On",


"Respect", "Good Vibrations"]
playcounts = [78, 29, 44, 21, 89, 5]

OUTPUT
{'The Best Songs': {'Like a Rolling Stone': 78, 'Satisfaction': 29, 'Imagine': 44,
"What's Going On": 21, 'Respect': 94, 'Good Vibrations': 5, 'Purple Haze': 1},
'Sunday Feelings': {}}

__________________________________________
Concept Review

Accessing and writing data in a Python dictionary

Values in a Python dictionary can be accessed by placing the key within square
brackets next to the dictionary. Values can be written by placing key within
square brackets next to the dictionary and using the assignment operator (=). If
the key already exists, the old value will be overwritten. Attempting to access a
value with a key that does not exist will cause a KeyError.
To illustrate this review card, the second line of the example code block shows
the way to access the value using the key "song". The third line of the code block
overwrites the value that corresponds to the key "song".

30
my_dictionary = {"song": "Estranged", "artist": "Guns N' Roses"}
print(my_dictionary["song"])
my_dictionary["song"] = "Paradise City"

Syntax of the Python dictionary

The syntax for a Python dictionary begins with the left curly brace ({), ends with
the right curly brace (}), and contains zero or more key : value items separated by
commas (,). The key is separated from the value by a colon (:).
roaster = {"q1": "Ashley", "q2": "Dolly"}

Merging dictionaries with the .update() method in Python

Given two dictionaries that need to be combined, Python makes this easy with
the .update() function.
For dict1.update(dict2), the key-value pairs of dict2 will be written into
the dict1 dictionary.
For keys in both dict1 and dict2, the value in dict1 will be overwritten by the
corresponding value in dict2.
dict1 = {'color': 'blue', 'shape': 'circle'}
dict2 = {'color': 'red', 'number': 42}

dict1.update(dict2)

# dict1 is now {'color': 'red', 'shape': 'circle', 'number': 42}

31
Dictionary value types

Python allows the values in a dictionary to be any type – string, integer, a list,
another dictionary, boolean, etc. However, keys must always be an immutable
data type, such as strings, numbers, or tuples.
In the example code block, you can see that the keys are strings or numbers (int
or float). The values, on the other hand, are many varied data types.
dictionary = {
1: 'hello',
'two': True,
'3': [1, 2, 3],
'Four': {'fun': 'addition'},
5.0: 5.5
}

Python dictionaries

A python dictionary is an unordered collection of items. It contains data as a set of


key: value pairs.
my_dictionary = {1: "L.A. Lakers", 2: "Houston Rockets"}

Dictionary Key-Value Methods


When trying to look at the information in a Python dictionary, there are multiple
methods that return objects that contain the dictionary keys and values.

32
• .keys() returns the keys through a dict_keys object.
• .values() returns the values through a dict_values object.
• .items() returns both the keys and values through a dict_items object.
ex_dict = {"a": "anteater", "b": "bumblebee", "c": "cheetah"}

ex_dict.keys()
# dict_keys(["a","b","c"])

ex_dict.values()
# dict_values(["anteater", "bumblebee", "cheetah"])

ex_dict.items()
# dict_items([("a","anteater"),("b","bumblebee"),("c","cheetah")])

get() Method for Dictionary

Python provides a .get() method to access a dictionary value if it exists. This


method takes the key as the first argument and an optional default value as the
second argument, and it returns the value for the specified key if key is in the
dictionary. If the second argument is not specified and key is not found
then None is returned.
# without default
{"name": "Victor"}.get("name")
# returns "Victor"

33
{"name": "Victor"}.get("nickname")
# returns None

# with default
{"name": "Victor"}.get("nickname", "nickname is not a key")
# returns "nickname is not a key"

The .pop() Method for Dictionaries in Python

Python dictionaries can remove key-value pairs with the .pop() method. The
method takes a key as an argument and removes it from the dictionary. At the
same time, it also returns the value that it removes from the dictionary.
famous_museums = {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre',
'Athens': 'The Acropolis Museum'}
famous_museums.pop('Athens')
print(famous_museums) # {'Washington': 'Smithsonian Institution', 'Paris': 'Le
Louvre'}

__________________________________________
2. Quiz

1. What is the value of inventory after this code is run?


inventory = {"iron spear": 12, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20}

34
inventory["invisible knife"] = 40
inventory["mithril shield"] = 25
a) {"iron spear": 12, "invisible knife": 70, "needle of ambition": 1, "stone
glove": 20, "mithril shield": 25}
b) {"iron spear": 12, "invisible knife": 40, "needle of ambition": 1, "stone
glove": 20, "mithril shield": 25}
c) {"iron spear": 12, "invisible knife": 70, "needle of ambition": 1, "stone
glove": 20}
d) {"iron spear": 12, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "invisible knife": 40, "mithril shield": 25}

2. What is the line of code to initialize an empty dictionary called thesaurus?


a) thesaurus = {}
b) thesaurus = new Dictionary()
c) thesaurus = []
d) thesaurus = empty_dict()

3. Which of these dictionaries has integers as the keys and strings as the values?
a) zipcodes = {"Alabama":35801,"Alaska":99501, "Oregon":97201,
"Vermont":05751, "New Jersey":07039}
b) zipcodes = {35801: "Alabama", "No Value": "N/A", "APO": "Overseas"}
c) zipcodes = {35801: "Alabama", 99501: "Alaska", 97201: "Oregon", 05751:
"Vermont", 07039: "New Jersey"}
d) zipcodes = {35801: ["Huntsville", "Montgomery"], 99501: ["Anchorage"],
97201: ["Portland", "Salem"], 05751: ["Burlington", "Montpelier",
"Rutland"], 07039: ["Hoboken"]}

4. What will the following code output?


conference_rooms = ["executive", "hopper", "lovelace", "pod", "snooze booth"]
capacity = [7, 20, 6, 2, 1]

35
room_dict = {key:value for key, value in zip(conference_rooms, capacity)}

print(room_dict)

a) {7: "executive", 20: "hopper", 6: "lovelace", 2: "pod", 1: "snooze booth"}


b) [("executive", 7), ("hopper", 20), ("lovelace", 6), ("pod", 2), ("snooze
booth", 1)}
c) ["executive", 7, "hopper", 20, "lovelace", 6, "pod", 2, "snooze booth", 1]
d) {"executive": 7, "hopper": 20, "lovelace": 6, "pod": 2, "snooze booth": 1}

5. Which of these is an invalid dictionary (will result in a TypeError when trying to


run)?
a) {["apple", "orange"]: "fruit", ["broccoli"]: "vegetable", ["salt", "paprika",
"saffron"]: "spice"}
b) {2: ["apple", "orange"], 1: ["broccoli"], 3: ["salt", "paprika", "saffron"]}
{"fruit": "apple", "vegetable": 10, "spice": ["salt", "paprika", "saffron"]}

36
3.USING DICTIONARIES
3.1 Using Dictionaries

Now that we know how to create a dictionary, we can start using already created
dictionaries to solve problems.
In this lesson, you’ll learn how to:
• Use a key to get a value from a dictionary
• Check for existence of keys
• Iterate through keys and values in dictionaries

3.2 Get A Key

Once you have a dictionary, you can access the values in it by providing the key.
For example, let’s imagine we have a dictionary that maps buildings to their
heights, in meters:
building_heights = {"Burj Khalifa": 828, "Shanghai Tower": 632, "Abraj Al Bait":
601, "Ping An": 599, "Lotte World Tower": 554.5, "One World Trade": 541.3}
Then we can access the data in it like this:
>>> building_heights["Burj Khalifa"]
828
>>> building_heights["Ping An"]
599

37
3.2 Get A Key Instructions
1.
We have provided a dictionary that maps the elements of astrology to the zodiac
signs. Print out the list of zodiac signs associated with the "earth" element.
2.
Print out the list of the "fire" signs.

zodiac_elements = {"water": ["Cancer", "Scorpio", "Pisces"], "fire": ["Aries",


"Leo", "Sagittarius"], "earth": ["Taurus", "Virgo", "Capricorn"], "air":["Gemini",
"Libra", "Aquarius"]}

OUTPUT
['Taurus', 'Virgo', 'Capricorn']
['Aries', 'Leo', 'Sagittarius']

3.3 Get an Invalid Key

Let’s say we have our dictionary of building heights from the last exercise:
building_heights = {"Burj Khalifa": 828, "Shanghai Tower": 632, "Abraj Al Bait":
601, "Ping An": 599, "Lotte World Tower": 554.5, "One World Trade": 541.3}
What if we wanted to know the height of the Landmark 81 in Ho Chi Minh City?
We could try:
print(building_heights["Landmark 81"])
But "Landmark 81" does not exist as a key in the building_heights dictionary! So
this will throw a KeyError:
KeyError: 'Landmark 81'
38
One way to avoid this error is to first check if the key exists in the dictionary:
key_to_check = "Landmark 81"

if key_to_check in building_heights:
print(building_heights["Landmark 81"])
This will not throw an error, because key_to_check in building_heights will
return False, and so we never try to access the key.

3.3 Get an Invalid Key Instructions


1.
Review the code in the editor and predict what the output will be. Run the code
to see if you are correct!
2.
Because "energy" is not a key in zodiac_elements, a KeyError is thrown in the
terminal!
Using an if statement, check if "energy" is a key in zodiac_elements. Nest the
existing print() statement within the if statement so that it will only execute
if "energy" is a key.
Run your code again. This time, there should be no errors in the terminal!
3.
Add the key "energy" to the zodiac_elements. It should map to a value of "Not a
Zodiac element". Run the code. Since "energy" is now a key, its value prints to the
terminal!

zodiac_elements = {"water": ["Cancer", "Scorpio", "Pisces"], "fire": ["Aries", "Leo",


"Sagittarius"], "earth": ["Taurus", "Virgo", "Capricorn"], "air":["Gemini", "Libra",
"Aquarius"]}

39
print(zodiac_elements["energy"])

OUTPUT
Not a Zodiac element

3.4 Safely Get a Key

We saw in the last exercise that we had to add a key:value pair to a dictionary in
order to avoid a KeyError. This solution is not sustainable. We can’t predict every
key a user may call and add all of those placeholder values to our dictionary!
Dictionaries have a .get() method to search for a value instead of
the my_dict[key] notation we have been using. If the key you are trying
to .get() does not exist, it will return None by default:
building_heights = {"Burj Khalifa": 828, "Shanghai Tower": 632, "Abraj Al Bait":
601, "Ping An": 599, "Lotte World Tower": 554.5, "One World Trade": 541.3}

#this line will return 632:


building_heights.get("Shanghai Tower")

#this line will return None:


building_heights.get("My House")
You can also specify a value to return if the key doesn’t exist. For example, we
might want to return a building height of 0 if our desired building is not in the
dictionary:
>>> building_heights.get('Shanghai Tower', 0)
632
>>> building_heights.get('Mt Olympus', 0)
0

40
>>> building_heights.get('Kilimanjaro', 'No Value')
'No Value'

3.4 Safely Get a Key Instructions


1.
Use .get() to get the value of "teraCoder"‘s user ID, with 10000 as a default value
if the user doesn’t exist. Store it in a variable called tc_id. Print tc_id to the
console.
2.
Use .get() to get the value of "superStackSmash"‘s user ID, with 10000 as a default
value if the user doesn’t exist. Store it in a variable called stack_id.
Print stack_id to the console.

user_ids = {"teraCoder": 10019, "pythonGuy": 182921, "samTheJavaMaam":


123112, "lyleLoop": 12931, "keysmithKeith": 129384}

OUTPUT
10019
10000

3.5 Delete a Key

Sometimes we want to get a key and remove it from the dictionary. Imagine we
were running a raffle, and we have this dictionary mapping ticket numbers to
prizes:
raffle = {223842: "Teddy Bear", 872921: "Concert Tickets", 320291: "Gift Basket",
412123: "Necklace", 298787: "Pasta Maker"}
41
When we get a ticket number, we want to return the prize and also remove that
pair from the dictionary, since the prize has been given away. We can
use .pop() to do this. Just like with .get(), we can provide a default value to return
if the key does not exist in the dictionary:
>>> raffle.pop(320291, "No Prize")
"Gift Basket"
>>> raffle
{223842: "Teddy Bear", 872921: "Concert Tickets", 412123: "Necklace", 298787:
"Pasta Maker"}
>>> raffle.pop(10000, "No Prize")
"No Prize"
>>> raffle
{223842: "Teddy Bear", 872921: "Concert Tickets", 412123: "Necklace", 298787:
"Pasta Maker"}
>>> raffle.pop(872921, "No Prize")
"Concert Tickets"
>>> raffle
{223842: "Teddy Bear", 412123: "Necklace", 298787: "Pasta Maker"}
.pop() works to delete items from a dictionary, when you know the key value.

3.5 Delete a Key Instructions


1.
You are designing the video game Big Rock Adventure. We have provided a
dictionary of items that are in the player’s inventory which add points to their
health meter. In one line, add the corresponding value of the key "stamina
grains" to the health_points variable and remove the item "stamina grains" from
the dictionary. If the key does not exist, add 0 to health_points.

2.
In one line, add the value of "power stew" to health_points and remove the item
from the dictionary. If the key does not exist, add 0 to health_points.
42
3.
In one line, add the value of "mystic bread" to health_points and remove the item
from the dictionary. If the key does not exist, add 0 to health_points.
4.
Print available_items and health_points.

available_items = {"health potion": 1, "cake of the cure": 5, "green elixir": 20,


"strength sandwich": 25, "stamina grains": 15, "power stew": 30}
health_points = 20

OUTPUT
{'health potion': 1, 'cake of the cure': 5, 'green elixir': 20, 'strength sandwich': 25}
65

3.6 Get All Keys

Sometimes we want to operate on all of the keys in a dictionary. For example, if


we have a dictionary of students in a math class and their grades:
test_scores = {"Grace":[80, 72, 90], "Jeffrey":[88, 68, 81], "Sylvia":[80, 82, 84],
"Pedro":[98, 96, 95], "Martin":[78, 80, 78], "Dina":[64, 60, 75]}
We want to get a roster of the students in the class, without including their
grades. We can do this with the built-in list() function:
>>> list(test_scores)
["Grace", "Jeffrey", "Sylvia", "Pedro", "Martin", "Dina"]
Dictionaries also have a .keys() method that returns a dict_keys object.
A dict_keys object is a view object, which provides a look at the current state of

43
the dictionary, without the user being able to modify anything.
The dict_keys object returned by .keys() is a set of the keys in the dictionary. You
cannot add or remove elements from a dict_keys object, but it can be used in the
place of a list for iteration:
for student in test_scores.keys():
print(student)
will yield:
Grace
Jeffrey
Sylvia
Pedro
Martin
Dina

3.6 Get All Keys Instructions


1.
Create a variable called users and assign it to be a dict_keys object of all of the
keys of the user_ids dictionary.
2.
Create a variable called lessons and assign it to be a dict_keys object of all of the
keys of the num_exercises dictionary.
3.
Print users to the console.
4.
Print lessons to the console.

user_ids = {"teraCoder": 10019, "pythonGuy": 182921, "samTheJavaMaam":


123112, "lyleLoop": 12931, "keysmithKeith": 129384}

44
num_exercises = {"functions": 1, "syntax": 13, "control flow": 15, "loops": 22,
"lists": 19, "classes": 18, "dictionaries": 18}

OUTPUT
dict_keys(['teraCoder', 'pythonGuy', 'samTheJavaMaam', 'lyleLoop',
'keysmithKeith'])
dict_keys(['functions', 'syntax', 'control flow', 'loops', 'lists', 'classes',
'dictionaries'])

3.7 Get All Values

Dictionaries have a .values() method that returns a dict_values object (just like
a dict_keys object but for values!) with all of the values in the dictionary. It can be
used in the place of a list for iteration:
test_scores = {"Grace":[80, 72, 90], "Jeffrey":[88, 68, 81], "Sylvia":[80, 82, 84],
"Pedro":[98, 96, 95], "Martin":[78, 80, 78], "Dina":[64, 60, 75]}

for score_list in test_scores.values():


print(score_list)
will yield:
[80, 72, 90]
[88, 68, 81]
[80, 82, 84]
[98, 96, 95]
[78, 80, 78]
[64, 60, 75]
There is no built-in function to get all of the values as a list, but if you really want
to, you can use:

45
list(test_scores.values())
However, for most purposes, the dict_values object will act the way you want a
list to act.

3.7 Get All Values Instructions


1.
Create a variable called total_exercises and set it equal to 0.
2.
Iterate through the values in the num_exercises list and add each value to
the total_exercises variable.
3.
Print the total_exercises variable to the console.

num_exercises = {"functions": 1, "syntax": 13, "control flow": 15, "loops": 22,


"lists": 19, "classes": 18, "dictionaries": 18}

OUTPUT
115

3.8 Get All Items

You can get both the keys and the values with the .items() method.
Like .keys() and .values(), it returns a dict_list object. Each element of
the dict_list returned by .items() is a tuple consisting of:
(key, value)

46
so to iterate through, you can use this syntax:
biggest_brands = {"Apple": 184, "Google": 141.7, "Microsoft": 80, "Coca-Cola":
69.7, "Amazon": 64.8}

for company, value in biggest_brands.items():


print(company + " has a value of " + str(value) + " billion dollars. ")
which would yield this output:
Apple has a value of 184 billion dollars.
Google has a value of 141.7 billion dollars.
Microsoft has a value of 80 billion dollars.
Coca-Cola has a value of 69.7 billion dollars.
Amazon has a value of 64.8 billion dollars.

3.8 Get All Items Instructions


1.
Use a for loop to iterate through the items of pct_women_in_occupation. For
each key : value pair, print out a string that looks like:

Women make up [value] percent of [key]s.

pct_women_in_occupation = {"CEO": 28, "Engineering Manager": 9, "Pharmacist":


58, "Physician": 40, "Lawyer": 37, "Aerospace Engineer": 9}

OUTPUT
Women make up 28 percent of CEOs.
Women make up 9 percent of Engineering Managers.
Women make up 58 percent of Pharmacists.
Women make up 40 percent of Physicians.
47
Women make up 37 percent of Lawyers.
Women make up 9 percent of Aerospace Engineers.

3.9 Review
In this lesson, you’ve learned how to go through dictionaries and access keys and
values in different ways. Specifically, you have seen how to:
• Use a key to get a value from a dictionary
• Check for existence of keys
• Remove a key: value pair from a dictionary
• Iterate through keys and values in dictionaries

3.9 Review Instructions


1.
We have provided a pack of tarot cards, tarot. You are going to do a three card
spread of your past, present, and future.
Create an empty dictionary called spread.
2.
The first card you draw is card 13. Pop the value assigned to the key 13 out of
the tarot dictionary and assign it as the value of the "past" key of spread.

3.
The second card you draw is card 22. Pop the value assigned to the key 22 out of
the tarot dictionary and assign it as the value of the "present" key of spread.
4.
The third card you draw is card 1. Pop the value assigned to the key 1 out of
the tarot dictionary and assign it as the value of the "future" key of spread.
48
5.
Iterate through the items in the spread dictionary and for each key: value pair,
print out a string that says:
Your {key} is the {value} card.
6.
Congratulations! You have learned about how to modify and use dictionaries.
Hit the Run button one more time when you are ready to continue.

tarot = { 1: "The Magician", 2: "The High Priestess", 3: "The Empress", 4: "The


Emperor", 5: "The Hierophant", 6: "The Lovers", 7: "The Chariot", 8:
"Strength", 9: "The Hermit", 1: "Wheel of Fortune", 11: "Justice",
12: "The Hanged Man", 13: "Death", 14: "Temperance", 15: "The Devil", 16:
"The Tower", 17: "The Star", 18: "The Moon", 19: "The Sun", 20:
"Judgement", 21: "The World", 22: "The Fool"}

OUTPUT
Your past is the Death card.
Your present is the The Fool card.
Your future is the Wheel of Fortune card.

__________________________________________
Concept Review

Accessing and writing data in a Python dictionary

49
Values in a Python dictionary can be accessed by placing the key within square
brackets next to the dictionary. Values can be written by placing key within
square brackets next to the dictionary and using the assignment operator (=). If
the key already exists, the old value will be overwritten. Attempting to access a
value with a key that does not exist will cause a KeyError.
To illustrate this review card, the second line of the example code block shows
the way to access the value using the key "song". The third line of the code block
overwrites the value that corresponds to the key "song".
my_dictionary = {"song": "Estranged", "artist": "Guns N' Roses"}
print(my_dictionary["song"])
my_dictionary["song"] = "Paradise City"

Syntax of the Python dictionary

The syntax for a Python dictionary begins with the left curly brace ({), ends with
the right curly brace (}), and contains zero or more key : value items separated by
commas (,). The key is separated from the value by a colon (:).
roaster = {"q1": "Ashley", "q2": "Dolly"}

Merging dictionaries with the .update() method in Python

Given two dictionaries that need to be combined, Python makes this easy with
the .update() function.
For dict1.update(dict2), the key-value pairs of dict2 will be written into
the dict1 dictionary.
For keys in both dict1 and dict2, the value in dict1 will be overwritten by the
corresponding value in dict2.

50
dict1 = {'color': 'blue', 'shape': 'circle'}
dict2 = {'color': 'red', 'number': 42}

dict1.update(dict2)

# dict1 is now {'color': 'red', 'shape': 'circle', 'number': 42}

Dictionary value types

Python allows the values in a dictionary to be any type – string, integer, a list,
another dictionary, boolean, etc. However, keys must always be an immutable
data type, such as strings, numbers, or tuples.
In the example code block, you can see that the keys are strings or numbers (int
or float). The values, on the other hand, are many varied data types.
dictionary = {
1: 'hello',
'two': True,
'3': [1, 2, 3],
'Four': {'fun': 'addition'},
5.0: 5.5
}

Python dictionaries

51
A python dictionary is an unordered collection of items. It contains data as a set of
key: value pairs.
my_dictionary = {1: "L.A. Lakers", 2: "Houston Rockets"}

Dictionary Key-Value Methods

When trying to look at the information in a Python dictionary, there are multiple
methods that return objects that contain the dictionary keys and values.
• .keys() returns the keys through a dict_keys object.
• .values() returns the values through a dict_values object.
• .items() returns both the keys and values through a dict_items object.
ex_dict = {"a": "anteater", "b": "bumblebee", "c": "cheetah"}

ex_dict.keys()
# dict_keys(["a","b","c"])

ex_dict.values()
# dict_values(["anteater", "bumblebee", "cheetah"])

ex_dict.items()
# dict_items([("a","anteater"),("b","bumblebee"),("c","cheetah")])

get() Method for Dictionary


Python provides a .get() method to access a dictionary value if it exists. This
method takes the key as the first argument and an optional default value as the
52
second argument, and it returns the value for the specified key if key is in the
dictionary. If the second argument is not specified and key is not found
then None is returned.
# without default
{"name": "Victor"}.get("name")
# returns "Victor"

{"name": "Victor"}.get("nickname")
# returns None

# with default
{"name": "Victor"}.get("nickname", "nickname is not a key")
# returns "nickname is not a key"

The .pop() Method for Dictionaries in Python

Python dictionaries can remove key-value pairs with the .pop() method. The
method takes a key as an argument and removes it from the dictionary. At the
same time, it also returns the value that it removes from the dictionary.
famous_museums = {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre',
'Athens': 'The Acropolis Museum'}
famous_museums.pop('Athens')
print(famous_museums) # {'Washington': 'Smithsonian Institution', 'Paris': 'Le
Louvre'}

__________________________________________
53
Project-1

Scrabble

In this project, you will process some data from a group of friends playing
scrabble. You will use dictionaries to organize players, words, and points.
There are many ways you can extend this project on your own if you finish and
want to get more practice!
If you get stuck during this project or would like to see an experienced developer
work through it, click “Get Unstuck“ to see a project walkthrough video.

TASKS

Build your Point Dictionary


1.
We have provided you with two lists, letters and points. We would like to
combine these two into a dictionary that would map a letter to its point value.
Using a list comprehension and zip, create a dictionary
called letter_to_points that has the elements of letters as the keys and the
elements of points as the values.

2.
Our letters list did not take into account blank tiles. Add an element to
the letter_to_points dictionary that has a key of " " and a point value of 0.

Score a Word

54
3.
We want to create a function that will take in a word and return how many points
that word is worth.
Define a function called score_word that takes in a parameter word.

4.
Inside score_word, create a variable called point_total and set it to 0.
5.
After defining point_total, create a for loop that goes through the letters
in word and adds the point value of each letter to point_total.
You should get the point value from the letter_to_points dictionary. If the letter
you are checking for is not in letter_to_points, add 0 to the point_total.

6.
After the for loop is finished, return point_total.
7.
Let’s test this function! Create a variable called brownie_points and set it equal to
the value returned by the score_word() function with an input of "BROWNIE".
8.
We expect the word BROWNIE to earn 15 points:
(B + R + O + W + N + I + E)

(3 + 1 + 1 + 4 + 4 + 1 + 1) = 15
Let’s print out brownie_points to make sure we got it right.
Score a Game
9.

55
Create a dictionary called player_to_words that maps players to a list of the
words they have played. This table represents the data to transcribe into your
dictionary:
player1 wordNerd Lexi Con Prof Reader
BLUE EARTH ERASER ZAP
TENNIS EYES BELLY COMA
EXIT MACHINE HUSKY PERIOD

1.
Create an empty dictionary called player_to_points.

11.
Iterate through the items in player_to_words. Call each player player and each list
of words words.
Within your loop, create a variable called player_points and set it to 0.

12.
Within the loop, create another loop that goes through each word in words and
adds the value of score_word() with word as an input.

13.
After the inner loop ends, set the current player value to be a key
of player_to_points, with a value of player_points.

14.

56
player_to_points should now contain the mapping of players to how many points
they’ve scored. Print this out to see the current standings for this game!
If you’ve calculated correctly, wordNerd should be winning by 1 point.
Ideas for Further Practice!
15.
If you want extended practice, try to implement some of these ideas with the
Python you’ve learned:
• play_word() — a function that would take in a player and a word, and add
that word to the list of words they’ve played
• update_point_totals() — turn your nested loops into a function that you
can call any time a word is played
• make your letter_to_points dictionary able to handle lowercase inputs as
well

letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 1, 1, 1, 1, 1, 4, 4, 8, 4, 1]
OUTPUT
15
{'player1': 12, 'BLUE': 28, 'TENNIS': 25, 'EXIT': 41}

__________________________________________
3. Quiz

1. What will the following code output?

57
combo_meals = {1: ["hamburger", "fries"], 2: ["hamburger", "fries", "soda"], 4:
["veggie burger", "salad", "soda"], 6: ["hot dog", "apple slices", "orange juice"]}
print(combo_meals[3])
a) "fries"
b) ["hot dog", "apple slices", "orange juice"]
c) KeyError
d) ["veggie burger", "salad", "soda"]

2. What is the output of the following code?


oscars = {"Best Picture": "Moonlight", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}

for element in oscars.values():


print(element)
a) "Best Picture" : "Moonlight"
"Best Actor": "Casey Affleck"
"Best Actress": "Emma Stone"
"Animated Feature": "Zootopia"
b) "Best Picture"
"Best Actor"
"Best Actress"
"Animated Feature"
c) ("Best Picture", "Moonlight")
("Best Actor", "Casey Affleck")
("Best Actress", "Emma Stone")
("Animated Feature", "Zootopia")
d) "Moonlight"
"Casey Affleck"
"Emma Stone"
"Zootopia"

3. What will the following code output?


58
inventory = {"iron spear": 12, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "the peacemaker": 65, "demonslayer": 50}
print(inventory.get("stone glove", 30))
a) 20
b) 30
c) 1
d) ("stone glove", 20)

4. What is the output of the following code?


raffle = {223842: "Teddy Bear", 872921: "Concert Tickets", 320291: "Gift Basket",
412123: "Necklace", 298787: "Pasta Maker"}

raffle.pop(561721, "No Value")


print(raffle)

a) 'No Value'
b) {223842: 'Teddy Bear', 872921: 'Concert Tickets', 320291: 'Gift Basket',
412123: 'Necklace', 298787: 'Pasta Maker', 561721: 'No Value'}
c) KeyError
d) {223842: 'Teddy Bear', 872921: 'Concert Tickets', 320291: 'Gift Basket',
412123: 'Necklace', 298787: 'Pasta Maker'}

5. What will the following code output?


combo_meals = {1: ["hamburger", "fries"], 2: ["hamburger", "fries", "soda"], 4:
["veggie burger", "salad", "soda"], 6: ["hot dog", "apple slices", "orange juice"]}
print(combo_meals[2])
a) "soda"
b) KeyError
c) ["veggie burger", "salad", "soda"]
d) ["hamburger", "fries", "soda"]

59
6. What will the following code output?
inventory = {"iron spear": 12, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "the peacemaker": 65, "demonslayer": 50}

print("the peacemaker" in inventory)


a) KeyError
b) True
c) 65
d) False

7. What does the following code output?


inventory = {"iron spear": 12, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "the peacemaker": 65, "demonslayer": 50}

print(12 in inventory)
a) False
b) True
c) KeyError
d) "iron spear"

8. What is the output of the following code?


oscars = {"Best Picture": "Moonlight", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}

for element in oscars:


print(element)
a) "Moonlight"
"Casey Affleck"

60
"Emma Stone"
"Zootopia"
b) "Best Picture" : "Moonlight"
"Best Actor": "Casey Affleck"
"Best Actress": "Emma Stone"
"Animated Feature": "Zootopia"
c) ("Best Picture", "Moonlight")
("Best Actor", "Casey Affleck")
("Best Actress", "Emma Stone")
("Animated Feature", "Zootopia")
d) "Best Picture"
"Best Actor"
"Best Actress"
"Animated Feature"

9. What will the following code output?


combo_meals = {1: ["hamburger", "fries"], 2: ["hamburger", "fries", "soda"], 4:
["veggie burger", "salad", "soda"], 6: ["hot dog", "apple slices", "orange juice"]}
print(combo_meals.get(3, ["hamburger", "fries"]))
a) ["hot dog", "apple slices", "orange juice"]
b) ["veggie burger", "salad", "soda"]
c) ["hamburger", "fries"]
d) KeyError

__________________________________________
2.Article

Off-Platform Project: Abruptly Goblins

61
In this off-platform project you will be the proprietor of a comic and games store,
the Sorcery Society, and you decide to host a game night to play the hot new
tabletop RPG Abruptly Goblins! You’ll be writing your own Python functions and
using dictionaries to provide a new service to gaming attendees of your shop.
Your beloved clientele want to organize a game night at your comics store! Create
a system for organizing and tracking gamer’s availability. Programmatically figure
out the best day to host a game night and send out emails to your attendees to
let them know when to come. Follow the steps below to get started with your
project!

Working on Your Computer


1. If you’ve never used the command line, we recommend taking the Learn
the Command Line course.
2. Install Python by following the directions in this article on Installing Python.
3. Learn about Jupyter Notebooks, a cool way of combining Python code with
explanations or instruction in a web terminal.
4. Download the Abruptly Goblins project.
5. Unzip it by double-clicking on it.
6. In the terminal, navigate to the directory containing the project, and type:
jupyter notebook
This should open a browser tab.
7. Click on Abruptly Goblins Planner.ipynb in the browser tab. This will open
up your Jupyter Notebook.
8. Follow the steps in the Jupyter Notebook. If you get stuck, you can look
at Abruptly Goblins Planner (Solution).ipynb for the answer.

62
4. LEARN PYTHON: FILES
4.1 Reading a File

Computers use file systems to store and retrieve data. Each file is an individual
container of related information. If you’ve ever saved a document, downloaded a
song, or even sent an email you’ve created a file on some computer somewhere.
Even script.py, the Python program you’re editing in the learning environment, is
a file.
So, how do we interact with files using Python? We’re going to learn how to read
and write different kinds of files using code. Let’s say we had a file
called real_cool_document.txt with these contents:
real_cool_document.txt
Wowsers!
We could read that file like this:
script.py
with open('real_cool_document.txt') as cool_doc:
cool_contents = cool_doc.read()
print(cool_contents)
This opens a file object called cool_doc and creates a new indented block where
you can read the contents of the opened file. We then read the contents of the
file cool_doc using cool_doc.read() and save the resulting string into the
variable cool_contents. Then we print cool_contents, which outputs the
statement Wowsers!.

4.1 Reading a File Instructions

63
1.
Use with to open the file welcome.txt. Save the file object as text_file.

2.
Read the contents of text_file and save the results in text_data.

3.
Print out text_data.

OUTPUT
Congratulations on reading your first file at codecademy.com!

4.2 Iterating Through Lines

When we read a file, we might want to grab the whole document in a single
string, like .read() would return. But what if we wanted to store each line in a
variable? We can use the .readlines() function to read a text file line by line
instead of having the whole thing. Suppose we have a file:
keats_sonnet.txt
To one who has been long in city pent,
’Tis very sweet to look into the fair
And open face of heaven,—to breathe a prayer
Full in the smile of the blue firmament.
script.py

64
with open('keats_sonnet.txt') as keats_sonnet:
for line in keats_sonnet.readlines():
print(line)
The above script creates a temporary file object called keats_sonnet that points
to the file keats_sonnet.txt. It then iterates over each line in the document and
prints the entire file out.

4.2 Iterating Through Lines Instructions


1.
Using a with statement, create a file object pointing to the
file how_many_lines.txt. Store that file object in the variable lines_doc.

2.
Iterate through each of the lines in lines_doc.readlines() using a for loop.
Inside the for loop print out each line of how_many_lines.txt.

OUTPUT
1. How many lines do we write on the daily,

2. Many money, we write many many many

3. How many lines do you write on the daily,

4. Say you say many money, you write many many many

4.3 Reading a Line


65
Sometimes you don’t want to iterate through a whole file. For that, there’s a
different file method, .readline(), which will only read a single line at a time. If the
entire document is read line by line in this way subsequent calls to .readline() will
not throw an error but will start returning an empty string (""). Suppose we had
this file:
millay_sonnet.txt
I shall forget you presently, my dear,
So make the most of this, your little day,
Your little month, your little half a year,
Ere I forget, or die, or move away,
script.py
with open('millay_sonnet.txt') as sonnet_doc:
first_line = sonnet_doc.readline()
second_line = sonnet_doc.readline()
print(second_line)
This script also creates a file object called sonnet_doc that points to the
file millay_sonnet.txt. It then reads in the first line
using sonnet_doc.readline() and saves that to the variable first_line. It then saves
the second line (So make the most of this, your little day,) into the
variable second_line and then prints it out.

4.3 Reading a Line Instructions


1.
Using a with statement, create a file object pointing to the file just_the_first.txt.
Store that file object in the variable first_line_doc.

2.
Save the first line of just_the_first.txt into the variable first_line.

66
3.
Print out the variable first_line.

OUTPUT
You do look, my son, in a moved sort,

4.4 Writing a File

Reading a file is all well and good, but what if we want to create a file of our own?
With Python we can do just that. It turns out that our open() function that we’re
using to open a file to read needs another argument to open a file to write to.
script.py
with open('generated_file.txt', 'w') as gen_file:
gen_file.write("What an incredible file!")
Here we pass the argument 'w' to open() in order to indicate to open the file in
write-mode. The default argument is 'r' and passing 'r' to open() opens the file in
read-mode as we’ve been doing.
This code creates a new file in the same folder as script.py and gives it the
text What an incredible file!. It’s important to note that if there is already a file
called generated_file.txt it will completely overwrite that file, erasing whatever its
contents were before.

4.4 Writing a File Instructions


1.
Create a file object for the file bad_bands.txt using the open() function with
the w argument. Assign this object to the temporary variable bad_bands_doc.

67
2.
Use the bad_bands_doc.write() method to add the name of a musical group you
dislike to the document bad_bands.

4.5 Appending to a File

So maybe completely deleting and overwriting existing files is something that


bothers you. Isn’t there a way to just add a line to a file without completely
deleting it? Of course there is! Instead of opening the file using the
argument 'w' for write-mode, we open it with 'a' for append-mode. If we have a
generated file with the following contents:
generated_file.txt
This was a popular file...
Then we can add another line to that file with the following code:
script.py
with open('generated_file.txt', 'a') as gen_file:
gen_file.write("\n... and it still is")
In the code above we open a file object in the temporary variable gen_file. This
variable points to the file generated_file.txt and, since it’s open in append-mode,
adds the string \n... and it still is to the file. The newline character \n moves to the
next line before adding the rest of the string. If you were to open the file after
running the script it would look like this:
generated_file.txt
This was a popular file...
... and it still is
Notice that opening the file in append-mode, with 'a' as an argument to open(),
means that using the file object’s .write() method appends whatever is passed to

68
the end of the file. If we were to run script.py again, this would be
what generated_file.txt looks like:
generated_file.txt
This was a popular file...
... and it still is
... and it still is
Notice that we’ve appended "\n... and it still is" to the file a second time! This is
because in script.py we opened generated_file.txt in append-mode.

4.5 Appending to a File Instructions


1.
We’ve got a file, cool_dogs.txt, filled with all the cool dogs we know. Somehow
while compiling this list we forgot about one very cool dog. Let’s fix that problem
by adding him to our cool_dogs.txt.
Open up our file cool_dogs.txt in append-mode and assign it to the file
object cool_dogs_file.
2.
Inside your with block, add “Air Buddy\n” to cool_dogs.txt. Air Buddy is a Golden
Retriever that plays basketball, which more than qualifies him for this list.
The \n character moves to the next line after appending the string.

4.6 What's With "with"?

We’ve been opening these files with this with block so far, but it seems a little
weird that we can only use our file variable in the indented block. Why is that?
The with keyword invokes something called a context manager for the file that
we’re calling open() on. This context manager takes care of opening the file when
we call open() and then closing the file after we leave the indented block.
69
Why is closing the file so complicated? Well, most other aspects of our code deal
with things that Python itself controls. All the variables you create: integers, lists,
dictionaries — these are all Python objects, and Python knows how to clean them
up when it’s done with them. Since your files exist outside your Python script, we
need to tell Python when we’re done with them so that it can close the
connection to that file. Leaving a file connection open unnecessarily can affect
performance or impact other programs on your computer that might be trying to
access that file.
The with syntax replaces older ways to access files where you need to
call .close() on the file object manually. We can still open up a file and append to
it with the old syntax, as long as we remember to close the file connection
afterwards.
fun_cities_file = open('fun_cities.txt', 'a')

# We can now append a line to "fun_cities".


fun_cities_file.write("Montréal")

# But we need to remember to close the file


fun_cities_file.close()
In the above script we added “Montréal” as a new line in our file fun_cities.txt.
However, since we used the older-style syntax, we had to remember to close the
file afterwards. Since this is necessarily more verbose (requires at least one more
line of code) without being any more expressive, using with is preferred.

4.6 What's With "with"? Instructions


1.
In script.py there’s a file object that doesn’t get closed correctly. Let’s fix it by
changing the syntax!
Remove this line:
close_this_file = open('fun_file.txt')

70
And change it to use the with syntax from our previous exercises.
Remember to indent the rest of the body so that we don’t get an IndentError.

close_this_file = open('fun_file.txt')

setup = close_this_file.readline()
punchline = close_this_file.readline()

print(setup)

OUTPUT
What did the pirate say when he turned 80?

4.7 What Is a CSV File?

Text files aren’t the only thing that Python can read, but they’re the only thing
that we don’t need any additional parsing library to understand. CSV files are an
example of a text file that impose a structure to their data. CSV stands
for Comma-Separated Values and CSV files are usually the way that data from
spreadsheet software (like Microsoft Excel or Google Sheets) is exported into a
portable format. A spreadsheet that looks like the following
Name Username Email
Roger
rsmith wigginsryan@yahoo.com
Smith

Michelle
mlbeck hcosta@hotmail.com
Beck

71
Name Username Email

Ashley
a_bark_x a_bark_x@turner.com
Barker

Lynn
goodmanjames lynniegonz@hotmail.com
Gonzales

Jennifer
chasej jchase@ramirez.com
Chase

Charles
choover choover89@yahoo.com
Hoover
Adrian
adevans adevans98@yahoo.com
Evans
Susan
susan82 swilliams@yahoo.com
Walter
Stephanie
stephanieking sking@morris-tyler.com
King

Erika
jessica32 ejmiller79@yahoo.com
Miller

In a CSV file that same exact data would be rendered like this:
users.csv
Name,Username,Email
Roger Smith,rsmith,wigginsryan@yahoo.com
Michelle Beck,mlbeck,hcosta@hotmail.com
Ashley Barker,a_bark_x,a_bark_x@turner.com
Lynn Gonzales,goodmanjames,lynniegonz@hotmail.com
Jennifer Chase,chasej,jchase@ramirez.com
Charles Hoover,choover,choover89@yahoo.com
Adrian Evans,adevans,adevans98@yahoo.com
72
Susan Walter,susan82,swilliams@yahoo.com
Stephanie King,stephanieking,sking@morris-tyler.com
Erika Miller,jessica32,ejmiller79@yahoo.com
Notice that the first row of the CSV file doesn’t actually represent any data, just
the labels of the data that’s present in the rest of the file. The rest of the rows of
the file are the same as the rows in the spreadsheet software, just instead of
being separated into different cells they’re separated by… well I suppose it’s fair
to say they’re separated by commas.

4.7 What Is a CSV File? Instructions


1.
CSV files are just plain text files!
Open logger.csv using our standard with syntax, saving the file object in the
temporary variable log_csv_file.
2.
Print out the contents of logger.csv by calling .read() on the file. Notice that it is
parsed as a string.

OUTPUT
Name,Age,ID
Richard Andrews,43,0de2ecf31df2386377b1d2dc4fae8b16fad05ad0
Hailey Sellers,24,3d9b8a95458c1df2687191e8146a97ca4afb28aa
Jessica Pace,39,a5daa63ef893cb86bc8df111cc9a5f8e1d0c563
Jasmine Escobar,42,9844e403841ec84b9a2fb3caf9d2a1c9ee042d31
Karen Kelly,26,8338f76ac0e9a76d73d57790f1d9843b185b5428
Patricia Christensen,70,23099bb630c1c64989458393045f08de3bac0eb9
Jessica Hansen,24,a8c035ccd099ef909a46e0d96b76c0f132c9c562
73
Raymond Adams,53,a051901830ff6c2095524ef92b1541eef9f8c64d
Stephanie Morrow,53,3bad04a5fc0a7ec33735ae45535f354887988f35
Timothy Ramos,34,b4930920b5256c4e592541297e43a556c8fe33a8

4.8 Reading a CSV File

Recall our CSV file from our last exercise:


users.csv
Name,Username,Email
Roger Smith,rsmith,wigginsryan@yahoo.com
Michelle Beck,mlbeck,hcosta@hotmail.com
Ashley Barker,a_bark_x,a_bark_x@turner.com
Lynn Gonzales,goodmanjames,lynniegonz@hotmail.com
Even though we can read these lines as text without a problem, there are ways to
access the data in a format better suited for programming purposes. In Python we
can convert that data into a dictionary using the csv library’s DictReader object.
Here’s how we’d create a list of the email addresses of all of the users in the
above table:
import csv

list_of_email_addresses = []
with open('users.csv', newline='') as users_csv:
user_reader = csv.DictReader(users_csv)
for row in user_reader:
list_of_email_addresses.append(row['Email'])
In the above code we first import our csv library, which gives us the tools to parse
our CSV file. We then create the empty list list_of_email_addresses which we’ll
later populate with the email addresses from our CSV. Then we open
the users.csv file with the temporary variable users_csv.

74
We pass the additional keyword argument newline='' to the file
opening open() function so that we don’t accidentally mistake a line break in one
of our data fields as a new row in our CSV (read more about this in the Python
documentation).
After opening our new CSV file we use csv.DictReader(users_csv) which converts
the lines of our CSV file to Python dictionaries which we can use access methods
for. The keys of the dictionary are, by default, the entries in the first line of our
CSV file. Since our CSV’s first line calls the third field in our CSV “Email“, we can
use that as the key in each row of our DictReader.
When we iterate through the rows of our user_reader object, we access all of the
rows in our CSV as dictionaries (except for the first row, which we used to label
the keys of our dictionary). By accessing the 'Email' key of each of these rows we
can grab the email address in that row and append it to
our list_of_email_addresses.

4.8 Reading a CSV File Instructions


1.
Import the csv module.
2.
Open up the file cool_csv.csv in the temporary variable cool_csv_file.
3.
Using csv.DictReader read the contents of cool_csv_file into a new variable
called cool_csv_dict.

4.
cool_csv.csv includes a cool fact about every person in the CSV.
For each row in cool_csv_dict print out that row’s "Cool Fact".

75
OUTPUT
Has never been out of the country.
Published a small biography on a local legend.
Happened across a major movie star while biking once.
Once ate three packages of cookies in one sitting.
Has been to over fifteen different forests.
Old job was across the street from their new job.
Has a dog named Peanut.
While working a phone bank accidentally called their mother.
Can whistle the national anthem of twelve different nations.
Is triple-jointed.

4.9 Reading Different Types of CSV Files

I need to level with you, I’ve been lying to you for the past two exercises. Well,
kind of. We’ve been acting like CSV files are Comma-Separated Values files. It’s
true that CSV stands for that, but it’s also true that other ways of separating
values are valid CSV files these days.
People used to call Tab-Separated Values files TSV files, but as other separators
grew in popularity everyone realized that creating a new .[a-z]sv file format for
every value-separating character used is not sustainable.
So we call all files with a list of different values a CSV file and then use
different delimiters (like a comma or tab) to indicate where the different values
start and stop.
Let’s say we had an address book. Since addresses usually use commas in them,
we’ll need to use a different delimiter for our information. Since none of our data
has semicolons (;) in them, we can use those.
76
addresses.csv
Name;Address;Telephone
Donna Smith;126 Orr Corner Suite 857\nEast Michael, LA 54411;906-918-6560
Aaron Osborn;6965 Miller Station Suite 485\nNorth Michelle, KS
64364;815.039.3661x42816
Jennifer Barnett;8749 Alicia Vista Apt. 288\nLake Victoriaberg, TN 5194;397-796-
4842x451
Joshua Bryan;20116 Stephanie Stravenue\nWhitneytown, IA 87358;(380)074-
6173
Andrea Jones;558 Melissa Keys Apt. 588\nNorth Teresahaven, WA
63411;+57(8)7795396386
Victor Williams;725 Gloria Views Suite 628\nEast Scott, IN
38095;768.708.3411x954
Notice the \n character, this is the escape sequence for a new line. The possibility
of a new line escaped by a \n character in our data is why we pass
the newline='' keyword argument to the open() function.
Also notice that many of these addresses have commas in them! This is okay,
we’ll still be able to read it. If we wanted to, say, print out all the addresses in this
CSV file we could do the following:
import csv

with open('addresses.csv', newline='') as addresses_csv:


address_reader = csv.DictReader(addresses_csv, delimiter=';')
for row in address_reader:
print(row['Address'])
Notice that when we call csv.DictReader we pass in the delimiter parameter,
which is the string that’s used to delineate separate fields in the CSV. We then
iterate through the CSV and print out each of the addresses.

4.9 Reading Different Types of CSV Files Instructions


1.

77
Import the csv module.
2.
Open up the file books.csv in the variable books_csv.
3.
Create a DictReader instance that uses the @ symbol as a delimiter to
read books_csv. Save the result in a variable called books_reader.
4.
Create a list called isbn_list, iterate through books_reader to get the ISBN number
of every book in the CSV file. Use the ['ISBN'] key for the dictionary objects passed
to it.

4.10 Writing a CSV File

Naturally if we have the ability to read different CSV files we might want to be
able to programmatically create CSV files that save output and data that someone
could load into their spreadsheet software. Let’s say we have a big list of data that
we want to save into a CSV file. We could do the following:
big_list = [{'name': 'Fredrick Stein', 'userid': 6712359021, 'is_admin': False},
{'name': 'Wiltmore Denis', 'userid': 2525942, 'is_admin': False}, {'name': 'Greely
Plonk', 'userid': 15890235, 'is_admin': False}, {'name': 'Dendris Stulo', 'userid':
572189563, 'is_admin': True}]

import csv

with open('output.csv', 'w') as output_csv:


fields = ['name', 'userid', 'is_admin']
output_writer = csv.DictWriter(output_csv, fieldnames=fields)

output_writer.writeheader()

78
for item in big_list:
output_writer.writerow(item)
In our code above we had a set of dictionaries with the same keys for each, a
prime candidate for a CSV. We import the csv library, and then open a new CSV
file in write-mode by passing the 'w' argument to the open() function.
We then define the fields we’re going to be using into a variable called fields. We
then instantiate our CSV writer object and pass two arguments. The first
is output_csv, the file handler object. The second is our list of fields fields which
we pass to the keyword parameter fieldnames.
Now that we’ve instantiated our CSV file writer, we can start adding lines to the
file itself! First we want the headers, so we call .writeheader() on the writer
object. This writes all the fields passed to fieldnames as the first row in our file.
Then we iterate through our big_list of data. Each item in big_list is a dictionary
with each field in fields as the keys. We call output_writer.writerow() with
the item dictionaries which writes each line to the CSV file.

4.10 Writing a CSV File Instructions


1.
We have a list in the workspace access_log which is a list of dictionaries we want
to write out to a CSV file.
Let’s start by importing the csv module.
2.
Open up the file logger.csv in the temporary variable logger_csv. Don’t forget to
open the file in write-mode.
3.
Create a csv.DictWriter instance called log_writer. Pass logger_csv as the first
argument and then fields as a keyword argument to the keyword fieldnames.
4.

79
Write the header to log_writer using the .writeheader() method.
5.
Iterate through the access_log list and add each element to the CSV
using log_writer.writerow().

access_log = [{'time': '08:39:37', 'limit': 844404, 'address': '1.227.124.181'},


{'time': '13:13:35', 'limit': 543871, 'address': '198.51.139.193'}, {'time': '19:40:45',
'limit': 3021, 'address': '172.1.254.208'}, {'time': '18:57:16', 'limit': 67031769,
'address': '172.58.247.219'}, {'time': '21:17:13', 'limit': 9083, 'address':
'124.144.20.113'}, {'time': '23:34:17', 'limit': 65913, 'address': '203.236.149.220'},
{'time': '13:58:05', 'limit': 1541474, 'address': '192.52.206.76'}, {'time': '1:52:00',
'limit': 11465607, 'address': '14.47.149.93'}, {'time': '14:56:12', 'limit': 19,
'address': '192.31.185.7'}, {'time': '18:56:35', 'limit': 6207, 'address':
'2.228.164.197'}]
fields = ['time', 'address', 'limit']

4.11 Reading a JSON File

CSV isn’t the only file format that Python has a built-in library for. We can also use
Python’s file tools to read and write JSON. JSON, an abbreviation of JavaScript
Object Notation, is a file format inspired by the programming language JavaScript.
The name, like CSV is a bit of a misnomer — some JSON is not valid JavaScript
(and plenty of JavaScript is not valid JSON).
JSON’s format is endearingly similar to Python dictionary syntax, and so JSON files
might be easy to read from a Python developer standpoint. Nonetheless, Python
comes with a json package that will help us parse JSON files into actual Python
dictionaries. Suppose we have a JSON file like the following:
purchase_14781239.json

80
{
'user': 'ellen_greg',
'action': 'purchase',
'item_id': '14781239',
}
We would be able to read that in as a Python dictionary with the following code:
json_reader.py
import json

with open('purchase_14781239.json') as purchase_json:


purchase_data = json.load(purchase_json)

print(purchase_data['user'])
# Prints 'ellen_greg'
First we import the json package. We opened the file using our
trusty open() command. Since we’re opening it in read-mode we just need to pass
the file name. We save the file in the temporary variable purchase_json.
We continue by parsing purchase_json using json.load(), creating a Python
dictionary out of the file. Saving the results into purchase_data means we can
interact with it. We print out one of the values of the JSON file by keying into
the purchase_data object.

4.11 Reading a JSON File Instructions


1.
Let’s read a JSON file! Start by importing the json module.

2.
Open up the file message.json, saving the file object to the
variable message_json.

81
Open the file in read-mode, without passing any additional arguments to open().

3.
Pass the JSON file object as an argument to json.load() and save the resulting
Python dictionary as message.
4.
Print out message['text'].

OUTPUT
Now that's JSON!

4.12 Writing a JSON File

Naturally we can use the json library to translate Python objects to JSON as well.
This is especially useful in instances where you’re using a Python library to serve
web pages, you would also be able to serve JSON. Let’s say we had a Python
dictionary we wanted to save as a JSON file:
turn_to_json = {
'eventId': 674189,
'dateTime': '2015-02-12T09:23:17.511Z',
'chocolate': 'Semi-sweet Dark',
'isTomatoAFruit': True
}
We’d be able to create a JSON file with that information by doing the following:
import json

with open('output.json', 'w') as json_file:


json.dump(turn_to_json, json_file)
82
We import the json module, open up a write-mode file under the
variable json_file, and then use the json.dump() method to write to the
file. json.dump() takes two arguments: first the data object, then the file object
you want to save.

4.12 Writing a JSON File Instructions


1.
In your workspace, we’ve put a dictionary called data_payload. We want to save
this to a file called data.json.
Let’s start by importing the json library.
2.
Open a new file object in the variable data_json. The filename should
be 'data.json' and the file should be opened in write-mode.

3.
Call json.dump() with data_payload and data_json to convert our data to JSON
and then save it to the file data.json.

data_payload = [
{'interesting message': 'What is JSON? A web application\'s little pile of secrets.',
'follow up': 'But enough talk!'}
]

4.13 Review

Now you know all about files! You were able to:
83
• Open up file objects using open() and with.
• Read a file’s full contents using Python’s .read() method.
• Read a file line-by-line using .readline() and .readlines()
• Create new files by opening them in write-mode.
• Append to a file non-destructively by opening a file in append-mode.
• Apply all of the above to different types of data-carrying files including CSV
and JSON!
You have all the skills necessary to read, write, and update files programmatically,
a very useful skill in the Python universe!

with open('file.txt') as file_object:


print(file_object.read())

OUTPUT
Thank you for learning about files in Python with us!

__________________________________________
Concept Review

Python File Object


A Python file object is created when a file is opened with the open() function. You
can associate this file object with a variable when you open a file using
the with and as keywords. For example:
with open('somefile.txt') as file_object:
You can then print the content of the file object, file_object with print().

84
print(file_object)
You might see something like this on the output terminal:
<_io.TextIOWrapper name='somefile.txt' mode='r' encoding='UTF-8'>

Python Readline Method


To read only one line instead of multiple lines in a Python file, use the
method .readline() on a file object that is returned from the open() function.
Every subsequent .readline() will extract the next line in the file if it exists.
with open('story.txt') as story_object:
print(story_object.readline())
will print only the first line in story.txt.

Parsing JSON files to dictionary


JSON format is used to store key value pairs. Python’s json module allows reading
such data format and parsing it to a dictionary. The json.load function takes a file
object as an argument and returns the data in a dictionary format.
# Use json.load with an opened file object to read the contents into a Python
dictionary.

# Contents of file.json
# { 'userId': 1 }

import json
with open('file.json') as json_file:

85
python_dict = json.load(json_file)

print(python_dict.get('userId'))
# Prints 1

Python Append To File


Writing to an opened file with the 'w' flag overwrites all previous content in the
file. To avoid this, we can append to a file instead. Use the 'a' flag as the second
argument to open(). If a file doesn’t exist, it will be created for append mode.
with open('shopping.txt', 'a') as shop:
shop.write('Tomatoes, cucumbers, celery\n')

Python Write To File


By default, a file when opened with open() is only for reading. A second
argument 'r' is passed to it by default. To write to a file, first open the file with
write permission via the 'w' argument. Then use the .write() method to write to
the file. If the file already exists, all prior content will be overwritten.
with open('diary.txt','w') as diary:
diary.write('Special events for today')

Python Readlines Method


Instead of reading the entire content of a file, you can read a single line at a time.
Instead of .read() which returns a string, call .readlines() to return a list of strings,
each representing an individual line in the file. Calling this code:
with open('lines.txt') as file_object:
file_data = file_object.readlines()

86
print(file_data)
returns a list of strings in file_data:
['1. Learn Python.\n', '2. Work hard.\n', '3. Graduate.']
Iterating over the list, file_data, and printing it:
for line in file_data:
print(line)
outputs:
1. Learn Python.

2. Work hard.

3. Graduate.

Class csv.DictWriter
In Python, the csv module implements classes to read and write tabular data
in CSV format. It has a class DictWriter which operates like a regular writer but
maps a dictionary onto output rows. The keys of the dictionary are column names
while values are actual data.
The csv.DictWriter constructor takes two arguments. The first is the open file
handler that the CSV is being written to. The second named
parameter, fieldnames, is a list of field names that the CSV is going to handle.
# An example of csv.DictWriter
import csv

with open('companies.csv', 'w') as csvfile:


fieldnames = ['name', 'type']
87
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name': 'Codecademy', 'type': 'Learning'})
writer.writerow({'name': 'Google', 'type': 'Search'})

"""
After running the above code, companies.csv will contain the following
information:

name,type
Codecademy,Learning
Google,Search
"""

Python Read Method


After a file is opened with open() returning a file object, call the .read() method of
the file object to return the entire file content as a Python string. Executing the
following Python code:
with open('mystery.txt') as text_file:
text_data = text_file.read()
print(text_data)
will produce a string containing the entire content of the read file:
Mystery solved.
Congratulations!

88
__________________________________________
4. Quiz

1. What function would you use to render Python data to a JSON file?
a) json.dump()
b) json.writelines()
c) json.write()

2. Which of the following opens a file in Python?


a) with open(file.txt) as file_obj:
pass
b) with file_obj = open('file.txt'):
pass
c) with open('file1.txt') as file_obj:
pass

3. What does the with command do in Python?


a) Opens a file in read-mode.
b) Creates a context-manager, which performs cleanup after exiting the
adjacent indented block.
c) Imports a new module for use by the writer of the code.

4. Which of the following methods on a file object (called file_object) reads the
contents of a file and returns it as a string?
a) file_contents = file_object.readlines()
b) file_contents = file_object.readline()
c) file_contents = file_object.read()
d) file_contents = file_object.get()

89
5. What different modes, passed as arguments to the open() function, are there
for opening a file in Python?
a) Read-mode (‘r’, the default mode), Delete-mode (‘d’), and Update-mode
(‘u’).
b) Read-mode (‘r’, the default mode), Write-mode (‘w’), and Append-mode
(‘a’).
c) Read-mode (‘r’, the default mode), Write-mode (‘w’), and Update-mode
(‘u’).

6. What Python data type would you use to read in a CSV file as a dictionary?
a) csv.DictReader
b) json.load
c) csv.DictWriter

7. What method reads a single line from a file object variable called file_object?
a) file_object.read()
b) file_object.readline()
c) file_object.readlines()

__________________________________________
Project-1

Hacking The Fender


The Fender, a notorious computer hacker and general villain of the people, has
compromised several top-secret passwords including your own. Your mission,
should you choose to accept it, is threefold. You must acquire access to The
Fender‘s systems, you must update his "passwords.txt" file to scramble the secret
90
data. The last thing you need to do is add the signature of Slash Null, a different
hacker whose nefarious deeds could be very conveniently halted by The Fender if
they viewed Slash Null as a threat.
Use your knowledge of working with Python files to retrieve, manipulate,
obscure, and create data in your quest for justice. Work with CSV files and other
text files in this exploration of the strength of Python file programming.
If you get stuck during this project, check out the project walkthrough
video which can be found in the help menu.

TASKS

Reading In The Passwords


1.
Are you there? We’ve opened up a communications link to The Fender‘s secret
computer. We need you to write a program that will read in the compromised
usernames and passwords that are stored in a file called "passwords.csv".
First import the CSV module, since we’ll be needing it to parse the data.

2.
We need to create a list of users whose passwords have been compromised,
create a new list and save it to the variable compromised_users.

3.
Next we’ll need you to open up the file itself. Store it in a file object
called password_file.

4.

91
Pass the password_file object holder to our CSV reader for parsing. Save the
parsed csv.DictReader object as password_csv.

5.
Now we’ll want to iterate through each of the lines in the CSV.
Create a for loop and save each row of the CSV into the temporary
variable password_row.
6.
Inside your for loop, print out password_row['Username']. This is the username of
the person whose password was compromised.
Run your code, do you see a list of usernames?
7.
Remove the print statement. We want to add each username to the list
of compromised_users. Use the list’s .append() method to add the username
to compromised_users instead of printing them.

8.
Exit out of your with block for "passwords.csv". We have all the data we need
from that file.
Start a new with block, opening a file called compromised_users.txt. Open this file
in write-mode, saving the file object as compromised_user_file.

9.
Inside the new context-managed block opened by the with statement start a
new for loop.
Iterate over each of your compromised_users.
1.
92
Write the username of
each compromised_user in compromised_users to compromised_user_file.

11.
Exit out of that with block. You’re doing great so far! We’ve got the data we need
to employ as insurance against The Fender.
Notifying the Boss
12.
Your boss needs to know that you were successful in retrieving that compromised
data. We’ll need to send him an encoded message over the internet. Let’s use
JSON to do that.
First we’ll need to import the json module.
13.
Open a new JSON file in write-mode called boss_message.json. Save the file
object to the variable boss_message.
14.
Create a Python dictionary object within your with statement that relays a boss
message. Call this boss_message_dict.
Give it a "recipient" key with a value "The Boss".
Also give it a "message" key with the value "Mission Success".

15.
Write out boss_message_dict to boss_message using json.dump().

Scrambling the Password


16.

93
Now that we’ve safely recovered the compromised users we’ll want to remove
the "passwords.csv" file completely.
Create a new with block and open "new_passwords.csv" in write-mode. Save the
file object to a variable called new_passwords_obj.
17.
Enemy of the people, Slash Null, is who we want The Fender to think was behind
this attack. He has a signature, whenever he hacks someone he adds this
signature to one of the files he touches. Here is the signature:
_ _ ___ __ ____
/ )( \ / __) / \(_ _)
) \/ ( ( (_ \( O ) )(
\____/ \___/ \__/ (__)
_ _ __ ___ __ _ ____ ____
/ )( \ / _\ / __)( / )( __)( \
) __ (/ \( (__ ) ( ) _) ) D (
\_)(_/\_/\_/ \___)(__\_)(____)(____/
____ __ __ ____ _ _
___ / ___)( ) / _\ / ___)/ )( \
(___) \___ \/ (_/\/ \\___ \) __ (
(____/\____/\_/\_/(____/\_)(_/
__ _ _ _ __ __
( ( \/ )( \( ) ( )
/ /) \/ (/ (_/\/ (_/\
\_)__)\____/\____/\____/
Save that as a multiline string to the variable slash_null_sig.

18.
Write slash_null_sig to new_passwords_obj. Now we have the file to
replace passwords.csv with!
19.

94
What an incredible success! We’ll take care of moving the new passwords file
over the old one in case you want to practice hacking The Fender in the future.
Thank you for your service, programmer.

95
5. INTRODUCTION TO CLASSES

5.1 Types

Python equips us with many different ways to store data. A float is a different
kind of number from an int, and we store different data in a list than we do in
a dict. These are known as different types. We can check the type of a Python
variable using the type() function.
a_string = "Cool String"
an_int = 12

print(type(a_string))
# prints "<class 'str'>"

print(type(an_int))
# prints "<class 'int'>"
Above, we defined two variables, and checked the type of these two variables. A
variable’s type determines what you can do with it and how you can use it. You
can’t .get() something from an integer, just as you can’t add two dictionaries
together using +. This is because those operations are defined at the type level.

5.1 Types Instructions


1.
Call type() on the integer 5 and print the results.

2.
Define a dictionary my_dict.

96
3.
Print out the type() of my_dict.
4.
Define a list called my_list.
5.
Print out the type() of my_list.

OUTPUT
<class 'int'>
<class 'dict'>
<class 'list'>

5.2 Class

A class is a template for a data type. It describes the kinds of information that
class will hold and how a programmer will interact with that data. Define a class
using the class keyword. PEP 8 Style Guide for Python Code recommends
capitalizing the names of classes to make them easier to identify.
class CoolClass:
pass
In the above example we created a class and named it CoolClass. We used
the pass keyword in Python to indicate that the body of the class was
intentionally left blank so we don’t cause an IndentationError. We’ll learn about
all the things we can put in the body of a class in the next few exercises.

5.2 Class Instructions

97
1.
Define an empty class called Facade. We’ll chip away at it soon!

5.3 Instantiation

A class doesn’t accomplish anything simply by being defined. A class must


be instantiated. In other words, we must create an instance of the class, in order
to breathe life into the schematic.
Instantiating a class looks a lot like calling a function. We would be able to create
an instance of our defined CoolClass as follows:
cool_instance = CoolClass()
Above, we created an object by adding parentheses to the name of the class. We
then assigned that new instance to the variable cool_instance for safe-keeping so
we can access our instance of CoolClass at a later time.

5.3 Instantiation Instructions


1.
In script.py we see our Facade class from last exercise. Make a Facade instance
and save it to the variable facade_1.
class Facade:
pass

5.4 Object-Oriented Programming

98
A class instance is also called an object. The pattern of defining classes and
creating objects to represent the responsibilities of a program is known as Object
Oriented Programming or OOP.
Instantiation takes a class and turns it into an object, the type() function does the
opposite of that. When called with an object, it returns the class that the object is
an instance of.
print(type(cool_instance))
# prints "<class '__main__.CoolClass'>"
We then print out the type() of cool_instance and it shows us that this object is of
type __main__.CoolClass.
In Python __main__ means “this current file that we’re running” and so one could
read the output from type() to mean “the class CoolClass that was defined here,
in the script you’re currently running.”

5.4 Object-Oriented Programming Instructions


1.
In script.py we see facade_1 from last exercise. Try calling type() on facade_1 and
saving it to the variable facade_1_type.
2.
Print out facade_1_type.

class Facade:
pass

facade_1 = Facade()

OUTPUT

99
<class '__main__.Facade'>

5.5 Class Variables

When we want the same data to be available to every instance of a class we use
a class variable. A class variable is a variable that’s the same for every instance of
the class.
You can define a class variable by including it in the indented part of your class
definition, and you can access all of an object’s class variables
with object.variable syntax.
class Musician:
title = "Rockstar"

drummer = Musician()
print(drummer.title)
# prints "Rockstar"
Above we defined the class Musician, then instantiated drummer to be an object
of type Musician. We then printed out the drummer’s .title attribute, which is a
class variable that we defined as the string “Rockstar”.
If we defined another musician, like guitarist = Musician() they would have the
same .title attribute.

5.5 Class Variables Instructions


1.
You are digitizing grades for Jan van Eyck High School and Conservatory. At Jan
van High, as the students call it, 65 is the minimum passing grade.
Create a Grade class with a class attribute minimum_passing equal to 65.

100
5.6 Methods

Methods are functions that are defined as part of a class. The first argument in a
method is always the object that is calling the method. Convention recommends
that we name this first argument self. Methods always have at least this one
argument.
We define methods similarly to functions, except that they are indented to be
part of the class.
class Dog:
dog_time_dilation = 7

def time_explanation(self):
print("Dogs experience {} years for every 1 human
year.".format(self.dog_time_dilation))

pipi_pitbull = Dog()
pipi_pitbull.time_explanation()
# Prints "Dogs experience 7 years for every 1 human year."
Above we created a Dog class with a time_explanation method that takes one
argument, self, which refers to the object calling the function. We created
a Dog named pipi_pitbull and called the .time_explanation() method on our new
object for Pipi.
Notice we didn’t pass any arguments when we called .time_explanation(), but
were able to refer to self in the function body. When you call a method it
automatically passes the object calling the method as the first argument.

5.6 Methods Instructions


1.
At Jan van High, the students are constantly calling the school rules into question.
Create a Rules class so that we can explain the rules.
101
In order for your code to run, you have to have something in your class — you
can’t have a defined class with no body like the following:
class exampleClass:
For now, make the body of your class pass. This will allow your code to run
without error.

2.
Give Rules a method washing_brushes that returns the string
"Point bristles towards the basin while washing your brushes."
Since we’ve now given this class a method, we can remove the pass that we
added in the previous step.

5.7 Methods with Arguments


Methods can also take more arguments than just self:
class DistanceConverter:
kms_in_a_mile = 1.609
def how_many_kms(self, miles):
return miles * self.kms_in_a_mile

converter = DistanceConverter()
kms_in_5_miles = converter.how_many_kms(5)
print(kms_in_5_miles)
# prints "8.045"
Above we defined a DistanceConverter class, instantiated it, and used it to
convert 5 miles into kilometers. Notice again that even
though how_many_kms takes two arguments in its definition, we only pass miles,
because self is implicitly passed (and refers to the object converter).

102
5.7 Methods with Arguments Instructions
1.
It’s March 14th (known in some places as Pi day) at Jan van High, and you’re
feeling awfully festive. You decide to create a program that calculates the area of
a circle.
Create a Circle class with class variable pi. Set pi to the approximation 3.14.
2.
Give Circle an area method that takes two parameters: self and radius.
Return the area as given by this formula:
area = pi * radius ** 2

3.
Create an instance of Circle. Save it into the variable circle.
4.
You go to measure several circles you happen to find around.
• A medium pizza that is 12 inches across.
• Your teaching table which is 36 inches across.
• The Round Room auditorium, which is 11,460 inches across.
You save the areas of these three things into pizza_area, teaching_table_area,
and round_room_area.
Remember that the radius of a circle is half the diameter. We gave three
diameters here, so halve them before you calculate the given circle’s area.

5.8 Constructors

103
There are several methods that we can define in a Python class that have special
behavior. These methods are sometimes called “magic,” because they behave
differently from regular methods. Another popular term is dunder methods, so-
named because they have two underscores (double-underscore abbreviated to
“dunder”) on either side of them.
The first dunder method we’re going to use is the __init__() method (note the
two underscores before and after the word “init”). This method is used
to initialize a newly created object. It is called every time the class is instantiated.
Methods that are used to prepare an object being instantiated are
called constructors. The word “constructor” is used to describe similar features in
other object-oriented programming languages but programmers who refer to a
constructor in Python are usually talking about the __init__() method.
class Shouter:
def __init__(self):
print("HELLO?!")

shout1 = Shouter()
# prints "HELLO?!"

shout2 = Shouter()
# prints "HELLO?!"
Above we created a class called Shouter and every time we create an instance
of Shouter the program prints out a shout. Don’t worry, this doesn’t hurt the
computer at all.
Pay careful attention to the instantiation syntax we use. Shouter() looks a lot like
a function call, doesn’t it? If it’s a function, can we pass parameters to it? We
absolutely can, and those parameters will be received by the __init__() method.
class Shouter:
def __init__(self, phrase):
# make sure phrase is a string
if type(phrase) == str:

104
# then shout it out
print(phrase.upper())

shout1 = Shouter("shout")
# prints "SHOUT"

shout2 = Shouter("shout")
# prints "SHOUT"

shout3 = Shouter("let it all out")


# prints "LET IT ALL OUT"
Above we’ve updated our Shouter class to take the additional parameter phrase.
When we created each of our objects we passed an argument to the constructor.
The constructor takes the argument phrase and, if it’s a string, prints out the all-
caps version of phrase.

5.8 Constructors Instructions


1.
Add a constructor to our Circle class.
Since we seem more frequently to know the diameter of a circle, it should take
the argument diameter.
It doesn’t need to do anything yet, just write pass in the body of the constructor.
2.
Now have the constructor print out the message "New circle with diameter:
{diameter}" when a new circle is created.
Create a circle teaching_table with diameter 36.

class Circle:
pi = 3.14
105
# Add constructor here:

OUTPUT
New circle with diameter: 36

5.9 Instance Variables

We’ve learned so far that a class is a schematic for a data type and an object is an
instance of a class, but why is there such a strong need to differentiate the two if
each object can only have the methods and class variables the class has? This is
because each instance of a class can hold different kinds of data.
The data held by an object is referred to as an instance variable. Instance
variables aren’t shared by all instances of a class — they are variables that are
specific to the object they are attached to.
Let’s say that we have the following class definition:
class FakeDict:
pass
We can instantiate two different objects from this
class, fake_dict1 and fake_dict2, and assign instance variables to these objects
using the same attribute notation that was used for accessing class variables.
fake_dict1 = FakeDict()
fake_dict2 = FakeDict()

fake_dict1.fake_key = "This works!"


fake_dict2.fake_key = "This too!"

# Let's join the two strings together!

106
working_string = "{} {}".format(fake_dict1.fake_key, fake_dict2.fake_key)
print(working_string)
# prints "This works! This too!"

5.9 Instance Variables


1.
In script.py we have defined a Store class. Create two objects from this store
class, named alternative_rocks and isabelles_ices.
2.
Give them both instance attributes called store_name.
Set alternative_rocks‘s store_name to "Alternative Rocks".
Set isabelles_ices‘s store_name to "Isabelle's Ices".

class Store:
pass

5.10 Attribute Functions

Instance variables and class variables are both accessed similarly in Python. This is
no mistake, they are both considered attributes of an object. If we attempt to
access an attribute that is neither a class variable nor an instance variable of the
object Python will throw an AttributeError.
class NoCustomAttributes:
pass

attributeless = NoCustomAttributes()

try:

107
attributeless.fake_attribute
except AttributeError:
print("This text gets printed!")

# prints "This text gets printed!"


What if we aren’t sure if an object has an attribute or not? hasattr() will
return True if an object has a given attribute and False otherwise. If we want to
get the actual value of the attribute, getattr() is a Python function that will return
the value of a given object and attribute. In this function, we can also supply a
third argument that will be the default if the object does not have the given
attribute.
The syntax and parameters for these functions look like this:
hasattr(object, “attribute”) has two parameters:
• object : the object we are testing to see if it has a certain attribute
• attribute : name of attribute we want to see if it exists
getattr(object, “attribute”, default) has three parameters (one of which is
optional):
• object : the object whose attribute we want to evaluate
• attribute : name of attribute we want to evaluate
• default : the value that is returned if the attribute does not exist (note: this
parameter is optional)
Calling those functions looks like this:
hasattr(attributeless, "fake_attribute")
# returns False

getattr(attributeless, "other_fake_attribute", 800)


# returns 800, the default value
Above we checked if the attributeless object has the attribute fake_attribute.
Since it does not, hasattr() returned False. After that, we used getattr to attempt
to retrieve other_fake_attribute. Since other_fake_attribute isn’t a real attribute
108
on attributeless, our call to getattr() returned the supplied default value 800,
instead of throwing an AttributeError.

5.10 Attribute Functions Instructions


1.
In script.py we have a list of different data types: a dictionary, a string, an integer,
and a list all saved in the variable can_we_count_it.
For every element in the list, check if the element has the attribute count using
the hasattr() function. If so, print the following line of code:
print(str(type(element)) + " has the count attribute!")

2.
Now let’s add an else statement for the elements that do not have the
attribute count. In this else statement add the following line of code:
print(str(type(element)) + " does not have the count attribute :(")

3.
Let’s go over the terminal output of the past two instructions. You should see the
following output in your terminal right now:
<class 'dict'> does not have the count attribute :(
<class 'str'> has the count attribute!
<class 'int'> does not have the count attribute :(
<class 'list'> has the count attribute!
This is because dictionaries and integers both do not have a count attribute, while
strings and lists do. In this exercise, we have iterated
through can_we_count_it and used hasattr() to determine which elements have
a count attribute. We never actually used the count method, but you can read
more about it here if you are curious about what it is.

109
Click run to move onto the next exercise!

can_we_count_it = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

OUTPUT
<class 'dict'> does not have the count attribute :(
<class 'str'> has the count attribute!
<class 'int'> does not have the count attribute :(
<class 'list'> has the count attribute!

5.11 Self
Since we can already use dictionaries to store key-value pairs, using objects for
that purpose is not really useful. Instance variables are more powerful when you
can guarantee a rigidity to the data the object is holding.
This convenience is most apparent when the constructor creates the instance
variables, using the arguments passed in to it. If we were creating a search
engine, and we wanted to create classes for each separate entry we could return.
We’d do that like this:
class SearchEngineEntry:
def __init__(self, url):
self.url = url

codecademy = SearchEngineEntry("www.codecademy.com")
wikipedia = SearchEngineEntry("www.wikipedia.org")

print(codecademy.url)
# prints "www.codecademy.com"

110
print(wikipedia.url)
# prints "www.wikipedia.org"
Since the self keyword refers to the object and not the class being called, we can
define a secure method on the SearchEngineEntry class that returns the secure
link to an entry.
class SearchEngineEntry:
secure_prefix = "https://"
def __init__(self, url):
self.url = url

def secure(self):
return "{prefix}{site}".format(prefix=self.secure_prefix, site=self.url)

codecademy = SearchEngineEntry("www.codecademy.com")
wikipedia = SearchEngineEntry("www.wikipedia.org")

print(codecademy.secure())
# prints "https://www.codecademy.com"

print(wikipedia.secure())
# prints "https://www.wikipedia.org"
Above we define our secure() method to take just the one required
argument, self. We access both the class variable self.secure_prefix and the
instance variable self.url to return a secure URL.
This is the strength of writing object-oriented programs. We can write our classes
to structure the data that we need and write methods that will interact with that
data in a meaningful way.

5.11 Self Instructions


1.
In script.py you’ll find our familiar friend, the Circle class.

111
Even though we usually know the diameter beforehand, what we need for most
calculations is the radius.
In Circle‘s constructor set the instance variable self.radius to equal half
the diameter that gets passed in.
2.
Define a new method circumference for your circle object that takes only one
argument, self, and returns the circumference of a circle with the given radius by
this formula:
circumference = 2 * pi * radius

3.
Define three Circles with three different diameters.
• A medium pizza, medium_pizza, that is 12 inches across.
• Your teaching table, teaching_table, which is 36 inches across.
• The Round Room auditorium, round_room, which is 11,460 inches across.
4.
Print out the circumferences of medium_pizza, teaching_table, and round_room.

class Circle:
pi = 3.14
def __init__(self, diameter):
print("Creating circle with diameter {d}".format(d=diameter))
# Add assignment for self.radius here:

OUTPUT
Creating circle with diameter 12
112
Creating circle with diameter 36
Creating circle with diameter 11460
37.68
113.04
35984.4

5.12 Everything is an Object

Attributes can be added to user-defined objects after instantiation, so it’s possible


for an object to have some attributes that are not explicitly defined in an object’s
constructor. We can use the dir() function to investigate an object’s attributes at
runtime. dir() is short for directory and offers an organized presentation of object
attributes.
class FakeDict:
pass

fake_dict = FakeDict()
fake_dict.attribute = "Cool"

dir(fake_dict)
# Prints ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__()',
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '__weakref__', 'attribute']
That’s certainly a lot more attributes than we defined! Python automatically adds
a number of attributes to all objects that get created. These internal attributes
are usually indicated by double-underscores. But sure enough, attribute is in that
list.

113
Do you remember being able to use type() on Python’s native data types? This is
because they are also objects in Python. Their classes are int, float, str, list,
and dict. These Python classes have special syntax for their
instantiation, 1, 1.0, "hello", [], and {} specifically. But these instances are still full-
blown objects to Python.
fun_list = [1, "string", {'abc': True}]

type(fun_list)
# Prints <class 'list'>

dir(fun_list)
# Prints ['__add__', '__class__', [...], 'append', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Above we define a new list. We check it’s type and see that’s an instantiation of
class list. We use dir() to explore its attributes, and it gives us a large number of
internal Python dunder attributes, but, afterward, we get the usual list methods.

5.12 Everything is an Object Instructions


1.
Call dir() on the number 5. Print out the results.

2.
Define a function called this_function_is_an_object. It can take any parameters
and return anything you’d like.
3.
Print out the result of calling dir() on this_function_is_an_object.
Functions are objects too!

114
OUTPUT
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__',
'__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__',
'__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__',
'__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__',
'__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
'__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
'__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__',
'__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__',
'__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__',
'__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',
'numerator', 'real', 'to_bytes']
['__annotations__', '__call__', '__class__', '__closure__', '__code__',
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__',
'__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__']

5.13 String Representation

One of the first things we learn as programmers is how to print out information
that we need for debugging. Unfortunately, when we print out an object we get a
default representation that seems fairly useless.
class Employee():
def __init__(self, name):
self.name = name

argus = Employee("Argus Filch")

115
print(argus)
# prints "<__main__.Employee object at 0x14e88390>"
This default string representation gives us some information, like where the class
is defined and our computer’s memory address where this object is stored, but is
usually not useful information to have when we are trying to debug our code.
We learned about the dunder method __init__(). Now, we will learn another
dunder method called __repr__(). This is a method we can use to tell Python what
we want the string representation of the class to be. __repr__() can only have one
parameter, self, and must return a string.
In our Employee class above, we have an instance variable called name that
should be unique enough to be useful when we’re printing out an instance of
the Employee class.
class Employee():
def __init__(self, name):
self.name = name

def __repr__(self):
return self.name

argus = Employee("Argus Filch")


print(argus)
# prints "Argus Filch"
We implemented the __repr__() method and had it return the .name attribute of
the object. When we printed the object out it simply printed the .name of the
object! Cool!

5.13 String Representation Instructions


1.
Add a __repr__() method to the Circle class that returns
Circle with radius {radius}

116
2.
Print out medium_pizza, teaching_table, and round_room.

class Circle:
pi = 3.14

def __init__(self, diameter):


self.radius = diameter / 2

def area(self):
return self.pi * self.radius ** 2

def circumference(self):
return self.pi * 2 * self.radius

medium_pizza = Circle(12)
teaching_table = Circle(36)
round_room = Circle(11460)

OUTPUT
Circle with radius 6.0
Circle with radius 18.0
Circle with radius 5730.0

117
5.14 Review

So far we’ve covered what a data type actually is in Python. We explored what the
functionality of Python’s built-in types (also referred to as primitives) are. We
learned how to create our own data types using the class keyword.
We explored the relationship between a class and an object — we create objects
when we instantiate a class, we find the class when we check the type() of an
object. We learned the difference between class variables (the same for all
objects of a class) and instance variables (unique for each object).
We learned about how to define an object’s functionality with methods. We
created multiple objects from the same class, all with similar functionality, but
with different internal data. They all had the same methods, but produced
different output because they were different instances.
Take a moment to congratulate yourself, object-oriented programming is a
complicated concept.

5.14 Review Instructions


1.
Define a class named Student that will be our data model at Jan van Eyck High
School and Conservatory.
Add a constructor for Student. Have the constructor take in two parameters:
a name and a year. Save those two as attributes .name and .year.

2.
Create three instances of the Student class:
• Roger van der Weyden, year 1
• Sandro Botticelli, year 12

118
• Pieter Bruegel the Elder, year 8
Save them into the variables roger, sandro, and pieter.

3.
Create a Grade class, with minimum_passing as an attribute set to 65.
4.
Give Grade a constructor. Take in a parameter score and assign it to self.score.
5.
In the body of the constructor for Student, declare self.grades as an empty list.
6.
Add an add_grade() method to Student that takes a parameter, grade.
.add_grade() should verify that grade is of type Grade and if so, add it to
the Student‘s .grades.
If grade isn’t an instance of Grade then .add_grade() should do nothing.

7.
Create a new Grade with a score of 10 and add it to pieter‘s .grades attribute
using .add_grade().
8.
Great job! You’ve created two classes and defined their interactions. This is
object-oriented programming! From here you could:
• Write a Grade method is_passing() that returns whether a Grade has a
passing .score.
• Write a Student method get_average() that returns the student’s average
score.

119
• Add an instance variable to Student that is a dictionary called .attendance,
with dates as keys and booleans as values that indicate whether the
student attended school that day.
• Write your own classes to do whatever logic you want!

__________________________________________
Concept Review

Python repr method

The Python __repr__() method is used to tell Python what the string
representation of the class should be. It can only have one parameter, self, and it
should return a string.
class Employee:
def __init__(self, name):
self.name = name

def __repr__(self):
return self.name

john = Employee('John')
print(john) # John

Python class methods

120
In Python, methods are functions that are defined as part of a class. It is common
practice that the first argument of any method that is part of a class is the actual
object calling the method. This argument is usually called self.
# Dog class
class Dog:
# Method of the class
def bark(self):
print("Ham-Ham")

# Create a new instance


charlie = Dog()

# Call the method


charlie.bark()
# This will output "Ham-Ham"

Instantiate Python Class

In Python, a class needs to be instantiated before use.


As an analogy, a class can be thought of as a blueprint (Car), and an instance is an
actual implementation of the blueprint (Ferrari).
class Car:
"This is an empty class"
pass

121
# Class Instantiation
ferrari = Car()

Python Class Variables

In Python, class variables are defined outside of all methods and have the same
value for every instance of the class.
Class variables are accessed with
the instance.variable or class_name.variable syntaxes.
class my_class:
class_variable = "I am a Class Variable!"

x = my_class()
y = my_class()

print(x.class_variable) #I am a Class Variable!


print(y.class_variable) #I am a Class Variable!

Python init method

In Python, the .__init__() method is used to initialize a newly created object. It is


called every time the class is instantiated.
class Animal:
def __init__(self, voice):

122
self.voice = voice

# When a class instance is created, the instance variable


# 'voice' is created and set to the input value.
cat = Animal('Meow')
print(cat.voice) # Output: Meow

dog = Animal('Woof')
print(dog.voice) # Output: Woof

Python type() function

The Python type() function returns the data type of the argument passed to it.
a=1
print(type(a)) # <class 'int'>

a = 1.1
print(type(a)) # <class 'float'>

a = 'b'
print(type(a)) # <class 'str'>

a = None
print(type(a)) # <class 'NoneType'>

123
Python class

In Python, a class is a template for a data type. A class can be defined using
the class keyword.
# Defining a class
class Animal:
def __init__(self, name, number_of_legs):
self.name = name
self.number_of_legs = number_of_legs

Python dir() function

In Python, the built-in dir() function, without any argument, returns a list of all the
attributes in the current scope.
With an object as argument, dir() tries to return all valid object attributes.
class Employee:
def __init__(self, name):
self.name = name

def print_name(self):
print("Hi, I'm " + self.name)

124
print(dir())
# ['Employee', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
'new_employee']

print(dir(Employee))
# ['__doc__', '__init__', '__module__', 'print_name']

__main__ in Python

In Python, __main__ is an identifier used to reference the current file context.


When a module is read from standard input, a script, or from an interactive
prompt, its __name__ is set equal to __main__.
Suppose we create an instance of a class called CoolClass. Printing the type() of
the instance will result in:
<class '__main__.CoolClass'>
This means that the class CoolClass was defined in the current script file.

__________________________________________
5. Quiz

1. What would be printed from the following code?


class User:
def __init__(self, name):
self.name = name

def __repr__(self):
125
return "Hiya {}!".format(self.name)

devorah = User("Devorah")
print(devorah)
a) Hiya devorah!
b) devorah
c) Devorah
d) Hiya Devorah!

2. How would we create an instance of the following class?


class NiceClass:
neat_attribute = "neat"
a) nice_instance = NiceClass()
b) nice_instance = NiceClass
c) nice_instance = new NiceClass

3. What does the hasattr() function call in the last line here evaluate to?
class HoldsFive:
five = 5

five_holder = HoldsFive()

hasattr(five_holder, 'five')
a) True
b) False
c) 5

4. Which method, defined within a class, provides instructions on what to assign


to a new instance when it is created?
a) __create__
126
b) __new__
c) __init__
d) init

5. What is the first argument of a method?


a) The class itself. We usually refer to it as self.
b) The context in which the object is created. We usually name the
parameter this.
c) The instance of the object itself. We usually refer to it as self.

6. What does the type() function do in Python?


a) Returns the class that an object implements.
b) Returns an implementation of a class.
c) Returns a type object that contains some metadata about the class.
d) Returns a string that’s the name of the class.

7. What keyword is used to indicate the start of a class definition?


a) type
b) __init__
c) def
d) class

__________________________________________
Project-2

Basta Fazoolin'

127
You’ve started a position as the lead programmer for the family-style Italian
restaurant Basta Fazoolin’ with My Heart. The restaurant has been doing
fantastically and seen a lot of growth lately. You’ve been hired to keep things
organized.
If you get stuck during this project or would like to see an experienced developer
work through it, click “Get Unstuck“ to see a project walkthrough video.

TASKS

Making the Menus


1.
At Basta Fazoolin’ with my Heart our motto is simple: when you’re here with
family, that’s great! We have four different menus: brunch, early-bird, dinner, and
kids.
Create a Menu class .

2.
Give Menu a constructor with the five parameters self, name, items, start_time,
and end_time.

3.
Let’s create our first menu: brunch. Brunch is served from 11am to 4pm. The
following items are sold during brunch:
{
'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50,
'espresso': 3.00, 'tea': 1.00, 'mimosa': 1.50, 'orange juice': 3.50
}

128
4.
Let’s create our second menu item early_bird. Early-bird Dinners are served from
3pm to 6pm. The following items are available during the early-bird menu:
{
'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza
with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)':
13.50, 'coffee': 1.50, 'espresso': 3.00,
}
5.
Let’s create our third menu, dinner. Dinner is served from 5pm to 11pm. The
following items are available for dinner:
{
'crostini with eggplant caponata': 13.00, 'caesar salad': 16.00, 'pizza with quattro
formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee':
2.00, 'espresso': 3.00,
}
6.
And let’s create our last menu, kids. The kids menu is available from 11am until
9pm. The following items are available on the kids menu.
{
'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00
}
7.
Give our Menu class a string representation method that will tell you the name of
the menu. Also, indicate in this representation when the menu is available.

8.
Try out our string representation. If you call print(brunch) it should print out
something like the following:

129
brunch menu available from 11am to 4pm
9.
Give Menu a method .calculate_bill() that has two parameters: self,
and purchased_items, a list of the names of purchased items.
Have calculate_bill return the total price of a purchase consisting of all the items
in purchased_items.
1.
Test out Menu.calculate_bill(). We have a breakfast order for one order of
pancakes, one order of home fries, and one coffee. Pass that
into brunch.calculate_bill() and print out the price.

11.
What about an early-bird purchase? Our last guests ordered the salumeria plate
and the vegan mushroom ravioli. Calculate the bill with .calculate_bill().

Creating the Franchises


12.
Basta Fazoolin’ with my Heart has seen tremendous success with the family
market, which is fantastic because when you’re at Basta Fazoolin’ with my
Heart with family, that’s great!
We’ve decided to create more than one restaurant to offer our fantastic menus,
services, and ambience around the country.
First, let’s create a Franchise class.
13.
Give the Franchise class a constructor. Take in an address, and assign it
to self.address. Also take in a list of menus and assign it to self.menus.
14.

130
Let’s create our first two franchises! Our flagship store is located at "1232 West
End Road" and our new installment is located at "12 East Mulberry Street". Pass in
all four menus along with these addresses to
define flagship_store and new_installment.
15.
Give our Franchises a string representation so that we’ll be able to tell them
apart. If we print out a Franchise it should tell us the address of the restaurant.

16.
Let’s tell our customers what they can order!
Give Franchise an .available_menus() method that takes in a time parameter and
returns a list of the Menu objects that are available at that time.

17.
Let’s test out our .available_menus() method! Call it with 12 noon as an argument
and print out the results.

18.
Let’s do another test! See what is printed if we call .available_menus() with 5pm
as an argument and print out the results.

Creating Businesses!
19.
Since we’ve been so successful building out a branded chain of restaurants, we’ve
decided to diversify. We’re going to create a restaurant that sells arepas!
First let’s define a Business class.
20.

131
Give Business a constructor. A Business needs a name and a list of franchises.
21.
Let’s create our first Business. The name is "Basta Fazoolin' with my Heart" and
the two franchises are flagship_store and new_installment.
22.
Before we create our new business, we’ll need a Franchise and before
our Franchise we’ll need a menu. The items for our Take a’ Arepa available from
1am until 8pm are the following:
{
'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa':
7.50
}
Save this to a variable called arepas_menu.
23.
Next let’s create our first Take a’ Arepa franchise! Our new restaurant is located
at "189 Fitzgerald Avenue". Save the Franchise object to a variable
called arepas_place.

24.
Now let’s make our new Business! The business is called "Take a' Arepa"!
25.
Congrats! You created a system of classes that help structure your code and
perform all business requirements you need. Whenever we need a new feature
we’ll have the well-organized code required to make developing and shipping it
easy.
26.
If you are stuck on the project or would like to see an experienced developer work
through the project, watch the following project walkthrough video!

132
https://youtu.be/Dk-ePlxdmBU

OUTPUT
brunch menu available from 11am to 4pm
13.5
early_bird menu available from 3pm to 6pm
21.5
Address: 1232 West End Road
Address: 12 East Mulberry Street
[brunch menu available from 11am to 4pm, kids menu available from 11am to
9pm]
[early_bird menu available from 3pm to 6pm, kids menu available from 11am to
9pm]

__________________________________________
3.Article

Python Code Challenges: Strings


Python Code Challenges involving Strings

This article will help you review Python functions by providing some code
challenges about strings.
Some of these challenges are difficult! Take some time to think about them
before starting to code.
133
You might not get the solution correct on your first try — look at your output, try
to find where you’re going wrong, and iterate on your solution.
Finally, if you get stuck, use our solution code! If you “Check Answer” twice with
an incorrect solution, you should see an option to get our solution code. However,
truly investigate that solution — experiment and play with the solution code until
you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
# … do something with the inputs …
return output
For example, a function that finds the difference in length between two Strings
would look like this:
def lengthDiff(str1, str2):
return len(str1) - len(str2)
And this would produce output like:
>>> lengthDiff("Python", "rocks")
1
>>> lengthDiff("Marco", "Polo")
1
>>> lengthDiff("Kevin", "Durant")
-1

Challenges
We’ve included 5 challenges below. Try to answer all of them and polish up your
problem-solving skills and your string expertise.
134
1. Count Letters
For the first code challenge, we are going to count the number of unique letters in
a string. This means that when we are looking at the word, any new letters should
be counted and any duplicates should not be counted. There are a few ways to
solve this, but we can use the provided alphabet string to ensure that duplicates
are not counted. Here is what we need to do:
1. Define the function to accept one parameter — the word whose letters we
are counting
2. Create a counter to keep track of unique letters
3. Loop through every letter in our alphabet string. If the current letter was
found in our word, increase our count
4. Return the count after looping through all letters.

Coding question
Write a function called unique_english_letters that takes the string word as a
parameter. The function should return the total number of unique letters in the
string. Uppercase and lowercase letters should be counted as different letters.
We’ve given you a list of every uppercase and lower case letter in the English
alphabet. It will be helpful to include that list in your function.
letters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno
pqrstuvwxyz"
# Write your unique_english_letters
function here:

# Uncomment these function calls to test


135
your function:
#print(unique_english_letters
("mississippi"))
# should print 4
#print(unique_english_letters("Apple"))
# should print 4

ANS:

This is how we solved it:


def unique_english_letters(word):
uniques = 0
for letter in letters:
if letter in word:
uniques += 1
return uniques
Since the provided alphabet string includes a single instance of all uppercase and
lowercase letters in the English alphabet, we can iterate through that string and
see if our input strings contains the current letter we are looking at. This can be
accomplished using the keyword in. For every letter in the possible letters, we see
if that letter is in our string!

2. Count X

Next, we are going to try something a bit different. This time we are going to
count the number of occurrences of a certain letter within a string. Our function
will accept a parameter for a string and another for the character which we are

136
going to count. For example, providing the word "mississippi" and the
character 's' would result in an answer of 4. These are the steps we need to take:
1. Define the function to accept two parameters. word for the input string
and x for the single character
2. Create a counter to keep track of the occurrences
3. Loop through every letter in the string. If the current letter is equal to the
input letter, increase our counter
4. Return the counter after looping through the entire string.

Coding question
Write a function named count_char_x that takes a string named word and a
single character named x as parameters. The function should return the number
of times x appears in word.

# Write your count_char_x function here:

# Uncomment these function calls to test


your tip function:
#print(count_char_x("mississippi", "s"))
# should print 4
#print(count_char_x("mississippi", "m"))
# should print 1

ANS:

Here is one way to solve it:


137
def count_char_x(word, x):
occurrences = 0
for letter in word:
if letter == x:
occurrences += 1
return occurrences
This solution is similar to the last solution. In this case, we are looping through the
input string and comparing it against the input character. If they are the same,
then we increase the counter.

3. Count Multi X

Now let’s change our function to compare against an entire string instead of a
single character. This function should accept a string and a substring to compare
against. The number of occurrences of the second parameter within the first
parameter string are returned. What this means is that we are checking the
number of occurrences of the shorter string (second parameter) within the longer
string (first parameter). One way to accomplish this is using the split function.
Here is how to do that:
1. Define the function to accept two parameters. word for the input string
and x for the second string we are searching for
2. Split the string into substrings based on the second input parameter
3. Count the number of instances the substring appeared in the first input
string based on the split string
4. Return the result

Coding question
Write a function named count_multi_char_x that takes a string named word and
a string named x. This function should do the same thing as
138
the count_char_x function you just wrote - it should return the number of
times x appears in word. However, this time, make sure your function works
when x is multiple characters long.
For example, count_multi_char_x("Mississippi", "iss") should return 2

# Write your count_multi_char_x function


here:

# Uncomment these function calls to test


your function:
#print(count_multi_char_x("mississippi",
"iss"))
# should print 2
#print(count_multi_char_x("apple", "pp"))
# should print 1

ANS:

Here is one possible way to get the answer:


def count_multi_char_x(word, x):
splits = word.split(x)
return(len(splits)-1)
In our function, we split the first input string using the second input string. What
this does is cut the first string into an array of smaller substrings containing the
parts not equal to our second parameter x. For example, when

139
splitting "mississippi" with the string "iss", the resulting array will be [“m”, “”,
“ippi”]. This includes the characters before "iss" was found, the empty space
between the two instances of "iss" and the characters after the last"iss". Be
careful! In order to get the correct result we need to return one less than the total
number of split sections — in this example, "iss" was in the string twice, resulting
in 3 sections. So we should return 3 - 1.

4. Substring Between

Here is a challenging problem. We need a function that is able to extract a portion


of a string between two characters. The function will take three parameters
where the first parameter is the string we are going to extract the substring from,
the second input is the starting character of our substring and the third character
is the ending character of our substring. Here are the steps we can use:
1. Define the function to accept three parameters, one string and two
characters
2. find the starting index of our substring using the second input parameter
3. find the ending index of our substring using the third input parameter
4. If neither of the indices are -1, return the portion of the first input
parameter string between the starting and ending indices (not including the
starting and ending index)
5. If either of the indices are -1, that means the start or end of the substring
didn’t exist in our string. Return the original string in this case.

Coding question
Write a function named substring_between_letters that takes a string
named word, a single character named start, and another character named end.
This function should return the substring between the first occurrence

140
of start and end in word. If start or end are not in word, the function should
return word.
For example, substring_between_letters("apple", "p", "e") should return "pl".

# Write your substring_between_letters


function here:

# Uncomment these function calls to test


your function:
#print(substring_between_letters("apple",
"p", "e"))
# should print "pl"
#print(substring_between_letters("apple",
"p", "c"))
# should print "apple"

ANS:

Here is this solution:


def substring_between_letters(word, start, end):
start_ind = word.find(start)
end_ind = word.find(end)
if start_ind > -1 and end_ind > -1:
return(word[start_ind+1:end_ind])
return word

141
In this solution, we use the find function to get the starting and ending indices of
our substring using our starting and ending characters. After getting those, we
check to make sure neither of them are -1. In order to extract the portion of the
string within those indices, we use slicing. We provide the starting index plus one
in order to not include the starting character. We do not need to provide the end
index plus one, since the value on the right of the colon is excluded. This causes
our slicing to look like: word[start_ind+1:end_ind]).

5. X Length

Let’s use the split method in a different way. We need a new function that is able
to accept two inputs: one for a sentence and another for a number. The function
returns True if every single word in the sentence has a length greater than or
equal to the number provided. These are the steps:
1. Define the function to accept two parameters, one string, and one number
2. Split up the sentence into an array of words
3. Loop through the words. If the length of any of the words is less than the
provided number return False
4. If we made it through the loop without returning False then return True

Coding question
Create a function called x_length_words that takes a string named sentence and
an integer named x as parameters. This function should return True if every word
in sentence has a length greater than or equal to x.

# Write your x_length_words function here:

142
# Uncomment these function calls to test
your tip function:
#print(x_length_words("i like apples", 2))
# should print False
#print(x_length_words("he likes apples",
2))
# should print True

ANS:

Here is what we did:


def x_length_words(sentence, x):
words = sentence.split(" ")
for word in words:
if len(word) < x:
return False
return True
We can use the split function with the space character provided in order to get an
array of all of the words in the sentence. Next, we use the in keyword in order to
loop through every element in our array of words. We check the length of each
word and compare it against x to see if it is shorter. If any of the words in the
array are shorter then we immediately return False and end the function. If we
make through all of the words without returning False, we know we should
return True since all of the word’s lengths were longer than x.

__________________________________________

143
4.Article

Python Code Challenges: Strings (Advanced)

Difficult Python Code Challenges Involving Strings

This article will help you review Python functions by providing some code
challenges involving strings.
Some of these challenges are difficult! Take some time to think about them
before starting to code.
You might not get the solution correct on your first try — look at your output, try
to find where you’re going wrong, and iterate on your solution.
Finally, if you get stuck, use our solution code! If you “Check Answer” twice with
an incorrect solution, you should see an option to get our solution code. However,
truly investigate that solution — experiment and play with the solution code until
you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
# … do something with the inputs …
return output
For example, a function that finds the difference in length between two Strings
would look like this:

144
def lengthDiff(str1, str2):
return len(str1) - len(str2)
And this would produce output like:
>>> lengthDiff("Python", "rocks")
1
>>> lengthDiff("Marco", "Polo")
1
>>> lengthDiff("Kevin", "Durant")
-1

Challenges
We’ve included 5 challenges below. Try to answer all of them and polish up your
problem-solving skills!

1. Check Name
You are creating an app that allows users to interact and share their coding
project ideas online. The first step is to provide your name in the application and
a greeting for other people to see which contains your name. Let’s create a
function that is able to check if a user’s name is located within their greeting. We
need a function that accepts two parameters, a string for our sentence and a
string for a name. The function should return True if the name exists within the
string (ignoring any differences in capitalization). Here is what we need to do:
1. Define the function to accept two parameters, one string for the sentence
and one string for the name
2. Convert all of the strings to the same case so we don’t have to worry about
differences in capitalization
3. Check if the name is within the sentence. If so, then return True. Otherwise,
return False

145
Coding question
Write a function called check_for_name that takes two strings as parameters
named sentence and name. The function should return True if name appears
in sentence in all lowercase letters, all uppercase letters, or with any mix of
uppercase and lowercase letters. The function should return False otherwise.
For example, the following three calls should all return True:
check_for_name("My name is Jamie", "Jamie")
check_for_name("My name is jamie", "Jamie")
check_for_name("My name is JAMIE", "Jamie")

ANS:

Here is how we did it:


def check_for_name(sentence, name):
return name.lower() in sentence.lower()
As you can see, this function can be created using one line. The in keyword will
return True if the first provided string is within the second. So in this case, we’re
checking if name is in sentence. In order to ignore differences in capitalization, we
can use the .lower() function which converts all characters to lowercase
characters.

2. Every Other Letter


For this next challenge, we are going to create a function that extracts every other
letter from a string and returns the resulting string. There are a few different ways
you can solve this problem. Here are the steps needed for one of the ways:
1. Define the function to accept one parameter for the string
2. Create a new empty string to hold every other letter from the input string
3. Loop through the input string while incrementing by two every time
146
4. Inside the loop, append the character at the current location to the new
string we initialized earlier
5. Return the new string

Coding question
Create a function named every_other_letter that takes a string named word as a
parameter. The function should return a string containing every other letter
in word.

ANS:

Here is one way to do it:


def every_other_letter(word):
every_other = ""
for i in range(0, len(word), 2):
every_other += word[i]
return every_other
In order to alternate which character is added to the every_other string, we use
a range of indices which starts at index 0 (the beginning of our word) and ends at
the end of our word. The third parameter in the range function determines what
value to increment by. In this case, we want to increment by 2 in order to get
every other letter.
Another way to loop through all indices of our original string, but only add the
letters that correspond to an even index. As a challenge, try solving this problem
that way!

3. Reverse

147
This one is similar to the last challenge. Instead of selecting every other letter, we
want to reverse the entire string. This can be performed in a similar manner, but
we will need to modify the range we are using. Here is what we need to do:
1. Define the function to accept one parameter for the string
2. Create a new empty string to hold the reversed string
3. Loop through the input string by starting at the end, and working towards
the beginning
4. Inside the loop, append the character at the current location to the new
string we initialized earlier
5. Return the result

Coding question
Write a function named reverse_string that has a string named word as a
parameter. The function should return word in reverse.

ANS:

Here is this solution:


def reverse_string(word):
reverse = ""
for i in range(len(word)-1, -1, -1):
reverse += word[i]
return reverse
This is similar to the last solution, but our range has been modified in order to
start at the last index of the string (length of the string minus one) up to the first
index. Since the parameter for the ending index is exclusive we need to provide
the index of one more iteration than what we want to stop at. We want to stop
at 0, and since we are incrementing by -1, we will set the ending index to -1.

148
Finally, make sure to add the third parameter of -1. This makes us increment by -
1 at each step.

4. Make Spoonerism
A Spoonerism is an error in speech when the first syllables of two words are
switched. For example, a Spoonerism is made when someone says “Belly Jeans”
instead of “Jelly Beans”. We are going to make a function that is similar, but
instead of using the first syllable, we are going to switch the first character of two
words. Here is what we need to do:
1. Define the function to accept two parameters for our two words
2. Get the first character of the first word and the first character of the second
word
3. Get the remaining characters of the first word and the remaining characters
of the second word.
4. Append the first character of the second word to the remaining character
of the first word
5. Append a space character
6. Append the first character of the first word to the remaining characters of
the second word.
7. Return the result

Coding question
Write a function called make_spoonerism that takes two strings as parameters
named word1 and word2. Finding the first syllable of a word is a difficult task, so
for our function, we’re going to switch the first letters of each word. Return the
two new words as a single string separated by a space.

ANS:
149
Here is how we did it:
def make_spoonerism(word1, word2):
return word2[0]+word1[1:]+" "+word1[0]+word2[1:]
We can accomplish the task in one line by appending and slicing at the same time.
We can get the first index of our words by using word1[0] and word2[0] which
gets the letter at the first index. In order to get the remaining letters we can
use word1[1:] and word2[1:]. This returns all characters in the strings starting
with index 1 and on. We concatenate everything together to get the result.

5. Add Exclamation
Let’s say we are writing a program that displays a large message on a blimp and
we need to fill in any missing space if a short phrase is provided. Our function will
accept a string and if the size is less than 20, it will fill in the remaining space with
exclamation marks until the size reaches 20. If the provided string already has a
length greater than 20, then we will simply return the original string. Here are the
steps:
1. Define the function to accept one parameter for our string
2. Loop while the length of our input string is less than 20
3. Inside the loop, append an exclamation mark
4. Once done, return the result

Coding question
Create a function named add_exclamation that has one parameter named word.
This function should add exclamation points to the end
of word until word is 20 characters long. If word is already at least 20 characters
long, just return word.

ANS:

150
Here is this solution:
def add_exclamation(word):
while(len(word) < 20):
word += "!"
return word
This function shows how we can continuously append to our string based on
some condition. In this case, we keep testing the length of the string to see if we
should keep going. Once the length has reached 20, either by adding exclamation
marks or by already being long, we return the result.

__________________________________________
5.Article

Python Code Challenges: Dictionaries

Python Code Challenges Involving Dictionaries

This article will help you review Python functions by providing some code
challenges involving dictionaries.
Some of these challenges are difficult! Take some time to think about them
before starting to code.
You might not get the solution correct on your first try — look at your output, try
to find where you’re going wrong, and iterate on your solution.
Finally, if you get stuck, use our solution code! If you “Check Answer” twice with
an incorrect solution, you should see an option to get our solution code. However,
truly investigate that solution — experiment and play with the solution code until
you have a good grasp of how it is working. Good luck!
151
Function Syntax
def some_function(some_input1, some_input2):
… do something with the inputs …
return output
For example, a function that counts the number of values in a dictionary that are
above a given number would look like this:
def greater_than_ten(my_dictionary, number):
count = 0
for value in my_dictionary.values():
if value > number:
count += 1
return count
And this would produce output like:
>>> greater_than_ten({"a":1, "b":2, "c":3}, 0)
3
>>> greater_than_ten({"a":1, "b":2, "c":3}, 5)
0

Challenges
We’ve included 5 challenges below. Try to answer all of them and polish up your
problem-solving skills!

1. Sum Values
For the first code challenge, we are going to look at only the values in a dictionary.
This function should sum up all of the values from the key-value pairs in the
dictionary. Here are the steps we need:
1. Define the function to accept one parameter for our dictionary

152
2. Create a variable to keep track of our sum
3. Loop through every value in the dictionary
4. Inside the loop, add each value to the sum
5. Return the sum

Coding question
Write a function named sum_values that takes a dictionary
named my_dictionary as a parameter. The function should return the sum of the
values of the dictionary
# Write your sum_values function here:

# Uncomment these function calls to test


your sum_values function:
#print(sum_values({"milk":5, "eggs":2,
"flour": 3}))
# should print 1
#print(sum_values({1:1, 10:2, 100:3}))
# should print 6

ANS
Here is this solution:
def sum_values(my_dictionary):
total = 0
for value in my_dictionary.values():
total += value
return total

153
We start by creating a variable to keep track of the total. Next, we use
the values() function in our for loop in order to iterate through each of the values
in the dictionary. Using this, we can access each value and add it to
our total variable. At the end of our loop, we return the total.

2. Even Keys
Next, we are going to do something similar, but we are going to use the keys in
order to retrieve the values. Additionally, we are going to only look at every even
key within the dictionary. Here are the steps:
1. Define the function to accept one parameter for our dictionary
2. Create a variable to keep track of our sum
3. Loop through every key in the dictionary
4. Inside the loop, if the key is even, add the value from the even key
5. After the loop, return the sum

Coding question
Create a function called sum_even_keys that takes a dictionary
named my_dictionary, with all integer keys and values, as a parameter. This
function should return the sum of the values of all even keys.
# Write your sum_even_keys function here:

# Uncomment these function calls to test


your function:
#print(sum_even_keys({1:5, 2:2, 3:3}))
# should print 2
#print(sum_even_keys({1:1, 10:2, 100:3}

154
))
# should print 6

ANS

Here is one solution:


def sum_even_keys(my_dictionary):
total = 0
for key in my_dictionary.keys():
if key%2 == 0:
total += my_dictionary[key]
return total
Similar to the previous problem, we are iterating through our dictionary, except
this time we are iterating through the keys instead of the values. In order to get
the keys we use the keys() function and to get the value of a key we can use
brackets. To test if the key is even we use the modulus operator and test if the
remainder is 0 when dividing by 2.

3. Add Ten
Let’s loop through the keys again, but this time let’s modify the values within the
dictionary. Our function should add 1 to every value in the dictionary and return
the modified dictionary. Here is what we need to do:
1. Define the function to accept one parameter for our dictionary
2. Loop through every key in the dictionary
3. Retrieve the value using the key and add 1 to it. Make sure to re-save the
new value to the original key.
4. After the loop, return the modified dictionary

155
Coding question
Create a function named add_ten that takes a dictionary with integer values
named my_dictionary as a parameter. The function should add 1 to every value
in my_dictionary and return my_dictionary
# Write your add_ten function here:

# Uncomment these function calls to test


your function:
#print(add_ten({1:5, 2:2, 3:3}))
# should print {1:15, 2:12, 3:13}
#print(add_ten({1:1, 10:2, 100:3}))
# should print {1:11, 10:12, 100:13}

ANS

Here is how we did it:


def add_ten(my_dictionary):
for key in my_dictionary.keys():
my_dictionary[key] += 1
return my_dictionary
We use a for loop to iterate through each key and we access the value using the
key. After accessing it, we overwrite the value with the value plus 1. Finally, we
return the modified dictionary.

4. Values That Are Keys


156
We are making a program that will create a family tree. Using a dictionary, we
want to return a list of all the children who are also parents of other children.
Using dictionaries we can consider those people to be values which are also keys
in our dictionary of family data. Here is what we need to do:
1. Define the function to accept one parameter for our dictionary
2. Create an empty list to hold the values we find
3. Loop through every value in the dictionary
4. Inside the loop, test if the current value is a key in the dictionary. If it is
then append it to the list of values we found
5. After the loop, return the list of values which are also keys

Coding question
Create a function named values_that_are_keys that takes a dictionary
named my_dictionary as a parameter. This function should return a list of all
values in the dictionary that are also keys.
# Write your values_that_are_keys
function here:

# Uncomment these function calls to test


your function:
#print(values_that_are_keys({1:10, 2:1,
3:4, 4:1}))
# should print [1, 4]
#print(values_that_are_keys({"a":"apple",
"b":"a", "c":10}))
157
# should print ["a"]

ANS

Here is this solution:


def values_that_are_keys(my_dictionary):
value_keys = []
for value in my_dictionary.values():
if value in my_dictionary:
value_keys.append(value)
return value_keys
For this solution, we iterate through every value within the dictionary. In order to
check if it is also a key, we can use the in keyword. This checks the value against
all of the keys in the dictionary to see if it exists as a key as well. If it does, then
we append it to our list of values which are also keys.

5. Largest Value
For the last challenge, we are going to create a function that is able to find the
maximum value in the dictionary and return the associated key. This is a twist on
the max algorithm since it is using a dictionary rather than a list. These are the
steps:
1. Define the function to accept one parameter for our dictionary
2. Initialize the starting key to a very low number
3. Initialize the starting value to a very low number
4. Iterate through the dictionary’s key/value pairs.
5. Inside the loop, if the current value is larger than the current largest value,
replace the largest key and largest value with the current ones you are
looking at

158
6. Once you are done iterating through all key/value pairs, return the key
which has the largest value

Coding question
Write a function named max_key that takes a dictionary named my_dictionary as
a parameter. The function should return the key associated with the largest value
in the dictionary.
# Write your max_key function here:

# Uncomment these function calls to test


your function:
#print(max_key({1:10, 2:1, 3:4, 4:1}))
# should print 1
#print(max_key({"a":10, "b":1, "c":100}
))
# should print "c"
ANS

Here is this solution:


def max_key(my_dictionary):
largest_key = float("-inf")
largest_value = float("-inf")
for key, value in my_dictionary.items():
if value > largest_value:
largest_value = value
largest_key = key
return largest_key

159
In order to program the max algorithm using dictionaries, we need to keep track
of the max value and the key which is used to access it. We start by using float("-
inf") in order to initialize them to the lowest possible value. To retrieve the key
and value at the same time, we use the items() function. Inside our loop, we
overwrite the current largest value and the key used to access whenever we find
a larger value. We return the largest value’s key once we have iterated through
the entire dictionary.

__________________________________________
6.Article

Python Code Challenges: Dictionaries (Advanced)

Difficult Python Code Challenges Involving Dictionaries


This article will help you review Python functions by providing some code
challenges involving dictionaries.
Some of these challenges are difficult! Take some time to think about them
before starting to code.
You might not get the solution correct on your first try — look at your output, try
to find where you’re going wrong, and iterate on your solution.
Finally, if you get stuck, use our solution code! If you “Check Answer” twice with
an incorrect solution, you should see an option to get our solution code. However,
truly investigate that solution — experiment and play with the solution code until
you have a good grasp of how it is working. Good luck!

Function Syntax

160
def some_function(some_input1, some_input2):
… do something with the inputs …
return output
For example, a function that counts the number of values in a dictionary that are
above a given number would look like this:
def greater_than_ten(my_dictionary, number):
count = 0
for value in my_dictionary.values():
if value > number:
count += 1
return count
And this would produce output like:
>>> greater_than_ten({"a":1, "b":2, "c":3}, 0)
3
>>> greater_than_ten({"a":1, "b":2, "c":3}, 5)
0

Challenges
We’ve included 4 challenges below. Try to answer all of them and polish up your
problem-solving skills!

1. Word Length Dict


Let’s start by writing a function that creates a new dictionary based on a list of
strings. The keys of our dictionary will be every string in our list of strings, while
the values will be the length of each of the words in the string list. Here are the
steps:
1. Define the function to accept one parameter for our list of strings
2. Create a new empty dictionary

161
3. Loop through every string in the list of strings
4. Inside the loop, add the string as a key and the length of the string as the
value to the dictionary
5. After the loop, return the new dictionary

Coding question
Write a function named word_length_dictionary that takes a list of strings
named words as a parameter. The function should return a dictionary of
key/value pairs where every key is a word in words and every value is the length
of that word.
# Write your word_length_dictionary
function here:

# Uncomment these function calls to test


your function:
#print(word_length_dictionary(["apple",
"dog", "cat"]))
# should print {"apple":5, "dog": 3,
"cat":3}
#print(word_length_dictionary(["a", ""]))
# should print {"a": 1, "": 0}

ANS

Here is this solution:

162
def word_length_dictionary(words):
word_lengths = {}
for word in words:
word_lengths[word] = len(word)
return word_lengths
To create a new dictionary we set a variable equal to {}. While iterating through
each string in our string list, we can add the key and value to our dictionary using
this syntax: word_lengths[word] = len(word).

2. Frequency Count

This next function is similar, but instead of counting the length of each string in
the list of strings, we will be counting the frequency of each string. This function
will also accept a list of strings as input and return a new dictionary. Here is what
we need to do:
1. Define the function to accept one parameter for our list of strings
2. Create a new empty dictionary
3. Loop through every string in the list of strings
4. Inside the loop, if the string is not already in our dictionary, store the string
as a key with a value of 0 in our dictionary. Then, increment the value by 1.
5. After the loop, return the new dictionary

Coding question
Write a function named frequency_dictionary that takes a list of elements
named words as a parameter. The function should return a dictionary containing
the frequency of each element in words.
# Write your frequency_dictionary

163
function here:

# Uncomment these function calls to test


your function:
#print(frequency_dictionary(["apple",
"apple", "cat", 1]))
# should print {"apple":2, "cat":1, 1:1}
#print(frequency_dictionary([0,0,0,0,0]))
# should print {0:5}

ANS

Here is how we solved it:


def frequency_dictionary(words):
freqs = {}
for word in words:
if word not in freqs:
freqs[word] = 0
freqs[word] += 1
return freqs
To create a new dictionary we set a variable equal to {}. We iterate through each
of the strings in the list of strings and check if it is already in our dictionary using
the in keyword. If it is not then we add it as a new key-value pair where the value
is 0. Regardless of whether the string was already in the dictionary, increase the
value by 1. This will make it so all new entries will have a value of 1 and all existing
entries will increase their old value by 1.

3. Unique Values
164
Now let’s try reading a dictionary as input and finding how many values are
unique. The function should return a number which is the count of all values from
the dictionary without including duplicates. These are the steps:
1. Define the function to accept one parameter for our dictionary
2. Create a new empty list
3. Loop through every value in our dictionary
4. Inside the loop, if the value is not already in our list, append the value to
our list
5. After the loop, return the length of our list

Coding question
Create a function named unique_values that takes a dictionary
named my_dictionary as a parameter. The function should return the number of
unique values in the dictionary.
# Write your unique_values function here:

# Uncomment these function calls to test


your function:
#print(unique_values({0:3, 1:1, 4:1, 5:3})
)
# should print 2
#print(unique_values({0:3, 1:3, 4:3, 5:3})
)
# should print 1

ANS
165
Here is this solution:
def unique_values(my_dictionary):
seen_values = []
for value in my_dictionary.values():
if value not in seen_values:
seen_values.append(value)
return len(seen_values)
This function has a similar structure to the last one except that the input has been
changed to a dictionary. We iterate through each of the values and whenever we
find one we have not added to our list already, we add it to the list. After the
loop, we return the length of the list since that contains all unique values from the
dictionary.

4. Count First Letter

This function accepts a dictionary where the keys are last names and the values
are lists of first names of people who have that last name. We need to calculate
the number of people who have the same first letter in their last name. Here are
the steps we need:
1. Define the function to accept one parameter for our dictionary
2. Create a new empty dictionary called letters
3. Loop through every key in our names dictionary
4. Inside the loop, get the first letter of the last name we are looking at. If the
first letter is not in our letter dictionary, add it as a key with a value of 0.
Then, increment that key by the number of people that have that last name
5. After the loop, return the letters dictionary

166
Coding question
Create a function named count_first_letter that takes a dictionary
named names as a parameter. names should be a dictionary where the key is a
last name and the value is a list of first names. For example, the dictionary might
look like this:
names = {"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister":
["Jaime", "Cersei", "Tywin"]}
The function should return a new dictionary where each key is the first letter of a
last name, and the value is the number of people whose last name begins with
that letter.
So in example above, the function would return:
{"S" : 4, "L": 3}

# Write your count_first_letter function


here:

# Uncomment these function calls to test


your function:
#print(count_first_letter({"Stark":
["Ned", "Robb", "Sansa"], "Snow" : ["Jon"]
, "Lannister": ["Jaime", "Cersei",
"Tywin"]}))
# should print {"S": 4, "L": 3}
#print(count_first_letter({"Stark":
["Ned", "Robb", "Sansa"], "Snow" : ["Jon"]
, "Sannister": ["Jaime", "Cersei",

167
"Tywin"]}))
# should print {"S": 7}

ANS

Here is what we did:


def count_first_letter(names):
letters = {}
for key in names:
first_letter = key[0]
if first_letter not in letters:
letters[first_letter] = 0
letters[first_letter] += len(names[key])
return letters
This function uses two dictionaries instead of one dictionary and one list. We
iterate through each of the keys (which are the last names) and store the first
letter of the last name in first_letter. We then use similar logic to what we have
used before by testing if we have already seen that letter before. If we haven’t
seen that letter before, then we add it to our dictionary with a value of 0. Next,
we are going to increment the value. Since we know that some people share the
last name (as seen by the list of first names in our names dictionary), we are going
to increment the value in our letters dictionary by the length of first names that
share the last name for our current iteration (key).

__________________________________________
7.Article

Python Code Challenges: Classes

168
Python Code Challenges Involving Classes
This article will help you review Python classes by providing some interesting code
challenges.
Some of these challenges are difficult! Take some time to think about them
before starting to code.
You might not get the solution correct on your first try — look at your output, try
to find where you’re going wrong, and iterate on your solution.
Finally, if you get stuck, use our solution code! If you “Check Answer” twice with
an incorrect solution, you should see an option to get our solution code. However,
truly investigate that solution — experiment and play with the solution code until
you have a good grasp of how it is working. Good luck!

Class Syntax
As a refresher, class syntax looks like this:
class MyClass:
# ... class variables ...

def __init__(self):
# ... instance variables ...
For example, a class which defines a rectangle using a class variable, instance
variables, and a method looks like this:
class Rectangle:
sides = 4

def __init__(self, width=0, height=0):


169
self.width = width
self.height = height

def calculate_area(self):
return self.width * self.height

rectangle_1 = Rectangle(5, 1)
rect_area = rectangle_1.calculate_area()
The last two lines in the above example show how to initialize an object of the
class as well as calling one of the methods.

Challenges
You have decided to use your programming knowledge to create a new robotics
company. Your idea for micro driving robots which are able to pick up and deliver
objects was promising and now you want to start programming the logic. These
code challenges will use your knowledge of Classes to solve some example
scenarios. Try solving the five challenge problems below!

1. Setting Up Our Robot


Let’s begin by creating the class for our robot. We will begin by setting up the
instance variables to keep track of important data related to the robot. Here are
the steps we need to do:
1. Create a new class called DriveBot
2. Set up a basic constructor (no parameters needed)

170
3. Initialize three instance variables within our constructor which all default to
0: motor_speed, direction, and sensor_range

Coding question
Create a python class called DriveBot. Within this class, create instance
variables for motor_speed, sensor_range, and direction. All of these should
be initialized to 0 by default. After setting up the class, create an object
from the class called robot_1. Set the motor_speed to 5,
the direction to 90, and the sensor_range to 1. Use the provided print
statements to check your work!
# Define the DriveBot class here!

# print(robot_1.motor_speed)
# print(robot_1.direction)
# print(robot_1.sensor_range)

ANS

Here is how we solved this:


class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0
This shows the structure of a simple class that only contains instance
variables. The three instance variables are set to 0 for now, which means
that they can only be changed by manually accessing them from an object
of the DriveBot class.

171
Here is an example of how you can manually set the values for an object of
the DriveBot class:
test_bot = DriveBot()
test_bot.motor_speed = 30
test_bot.direction = 90
test_bot.sensor_range = 25

2. Adding Robot Logic

Now we want to add some logic to our robot. It would be very useful to be
able to control our robot, so we are going to create a control_bot method
which changes the speed and direction. We are also going to create a
method called adjust_sensor. This method is used to change the range of
our robot’s sensors which are used to detect obstacles. Here are the steps:
1. Define a function within the DriveBot class which accepts two additional
parameters: one for a new speed and one for a new direction
2. Replace the instance variables for speed and direction with the input
parameters
3. Define another function called adjust_sensor which accepts one additional
parameter
4. Replace the instance variable sensor_range with the input parameter

Coding question
In the DriveBot class, add a method called control_bot which accepts
parameters: new_speed and new_direction. These should replace the
associated instance variables. Create another method
called adjust_sensor which accepts a parameter
called new_sensor_range which replaces the sensor_range instance
variable. Afterwards, use these methods to rotate the robot 180 degrees
172
at 1 miles per hour with a sensor range of 20 feet. Use the provided print
statements to check your code!
class DriveBot:
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0

# Add the methods here!

robot_1 = DriveBot()
# Use the methods here!

# print(robot_1.motor_speed)
# print(robot_1.direction)
# print(robot_1.sensor_range)

ANS

Here are the methods we added:


def control_bot(self, new_speed, new_direction):
self.motor_speed = new_speed
self.direction = new_direction

def adjust_sensor(self, new_sensor_range):


self.sensor_range = new_sensor_range

173
These two methods were added inside of the DriveBot class. They are used
to replace the instance variables with new values from the input
parameters. We use self.variable_name to access a certain instance
variable within the class.

3. Enhanced Constructor

It can be tedious manually setting the values for each instance variable
after we have created an object from the DriveBot class. We can enhance
our constructor to automatically assign the values we provide to the
instance variables. Instead of taking zero parameters, we are going to make
the constructor take three parameters. Here is what we need to do:
1. Modify the constructor to take three parameters (in addition to self): one
for motor_speed, one for direction, and one for sensor_range
2. For the first parameter, make the default value 0
3. For the second parameter, make the default value 180
4. For the third parameter, make the default value 1
5. Within the constructor, replace the instance variables with the variables
from the input parameters

Coding question
Upgrade the constructor in the DriveBot class in order to accept three
optional parameters. The constructor can accept motor_speed (which
defaults to 0 if not provided), direction (which defaults to 180 if not
provided, and sensor_range (which defaults to 1 if not provided). These
parameters should replace the associated instance variables. Test out the
upgraded constructor by initializing a new robot called robot_2 with a
speed of 35, a direction of 75, and a sensor range of 25.

174
class DriveBot:
# Update this constructor!
def __init__(self):
self.motor_speed = 0
self.direction = 0
self.sensor_range = 0

def control_bot(self, new_speed,


new_direction):
self.motor_speed = new_speed
self.direction = new_direction

def adjust_sensor(self,
new_sensor_range):
self.sensor_range =
new_sensor_range

robot_1 = DriveBot()
robot_1.motor_speed = 5
robot_1.direction = 90

ANS

Here is the updated constructor:

175
def __init__(self, motor_speed = 0, direction = 180, sensor_range = 1):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
This upgraded constructor includes input parameters as well as default
values for those parameters. This means that if no value is provided for
those parameters, then the value they are set equal to will be used. Here
are some examples of different ways to use the constructor:
# sensor_range defaults to 1
test_bot_1 = DriveBot(1, 270)

# direction defaults to 180


test_bot_2 = DriveBot(sensor_range = 20, motor_speed = 45)

# direction defaults to 180 and sensor_range defaults to 1


test_bot_3 = DriveBot(50)

# all default values are used


test_bot_4 = DriveBot()

# no default values are used


test_bot_5 = DriveBot(18, 95, 30)

4. Controlling Them All

We want to add a new feature which allows the use to control multiple
robots at once. The robots should be able to all have the
same latitude and longitude GPS destination coordinates as well as a
setting for disabling them all called all_disabled. We can accomplish this
using class variables. Here is how we can do it:

176
1. Create a new class variable within the DriveBot class
called all_disabled and set it equal to False
2. Create a new class variable within the DriveBot class called latitude and set
it equal to -999999
3. Create a new class variable within the DriveBot class called longitude and
set it equal to -999999
4. Outside of the class, test the class variables by setting the longitude of all
robots to 50.0, the latitude to -50.0 and all_disabled to True

Coding question
Create a class variable called all_disabled which is set to False. Next, create
two more class variables called latitude and longitude. Set both of those
variables to equal -999999. A third robot has been created below the first
two robots. Set the latitude of all of the robots to -50.0 at once.
Additionally, set the longitude of the robots to 50.0 and
set all_disabled to True. You should be able to set those values using three
lines of code.
class DriveBot:
# Create the class variables!

def __init__(self, motor_speed = 0,


direction = 180, sensor_range = 1):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range

def control_bot(self, new_speed,

177
new_direction):
self.motor_speed = new_speed
self.direction = new_direction

def adjust_sensor(self,
new_sensor_range):
self.sensor_range =
new_sensor_range

robot_1 = DriveBot()

ANS

Here are the changes we made in the class:


class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
We placed the class variables at the top of the class outside of the
constructor. These variables can be accessed within the scope of the entire
class. This means that the class variables contained within every object
from the DriveBot class will change if we modify the class variable directly.
Here is an example of how to change each of these class variables:
DriveBot.longitude = -79.98553
DriveBot.latitude = 40.60793
DriveBot.all_disabled = False

178
5. Identifying Robots

In order to keep track of the robots we are creating, we want to be able to


assign an ID value to each robot when it is created. If we create five robots
in a row, we want the IDs of each robot to be 1, 2, 3, 4, and 5 respectively.
This can be accomplished by using a class variable counter which
increments and is assigned to an instance variable for the ID whenever the
constructor is called. Here are the steps:
1. Create a new class variable in the DriveBot class called robot_count
2. In the constructor, increment the robot_count by 1
3. After incrementing the value, assign the value of robot_count to a new
instance variable called id.

Coding question

Within the DriveBot class, create an instance variable called id which will
be assigned to the robot when the object is created. Every time a robot is
created, increment a counter (stored as a class variable) so that the next
robot will have a different id. For example, if three robots were
created: first_robot, next_robot, and last_robot; first_robot will have
an id of 1 next_robot will have an id of 2 and last_robot will have
an id of 3.
class DriveBot:
# Create a counter to keep track of how
many robots were created
all_disabled = False
latitude = -999999

179
longitude = -999999

def __init__(self, motor_speed = 0,


direction = 180, sensor_range = 1):
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
# Assign an `id` to the robot
when it is constructed by incrementing
the counter and assigning the value to
`id`

def control_bot(self, new_speed,


new_direction):
self.motor_speed = new_speed

ANS

Here is the complete class:


class DriveBot:
all_disabled = False
latitude = -999999
longitude = -999999
robot_count = 0

def __init__(self, motor_speed = 0, direction = 180, sensor_range = 1):

180
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
DriveBot.robot_count += 1
self.id = DriveBot.robot_count

def control_bot(self, new_speed, new_direction):


self.motor_speed = new_speed
self.direction = new_direction

def adjust_sensor(self, new_sensor_range):


self.sensor_range = new_sensor_range
The final modifications to this class can be seen at the top of the class and
in the constructor. We use a class variable to keep track of the total
number of robots. This information is shared across all robot objects we
create from the class. Every time a robot object is created, the constructor
is called and the count is incremented. Each robot has an instance variable
for id which is local to that robot object. This is assigned at the time of
construction and stores what the count was at that time.

__________________________________________
8.Article
Next Steps

You’ve completed the Learn Python 3 course! What’s


next?
Congratulations, you’ve successfully completed the Learn Python 3 course!
You got an introduction to fundamental programming concepts and the
Python programming language syntax. More specifically, you learned
about:
• How to write Python syntax to print and work with user input
181
• How to use Python control flow, boolean variables, and logic operators to
create programs that can make dynamic decisions
• How to utilize the list data structure to store and manipulate ordered
groups of data
• How to use loops to reduce code repetition and effectively execute a group
of statements several times
• How to create functions to organize code into reusable blocks
• How to work with the string data type to automatically create, rearrange,
reassign, disassemble, and reassemble blocks of text
• How code in Python is grouped and shared across a codebase via modules
• How to utilize the dictionary data structure to organize information in a
key-value format
• How to work with files in an automated way
• How the relationship between a class and an object works to create object-
oriented code
Your learning journey into Python isn’t over yet! There are plenty of other
topics that you can dive into to continue learning. Here are our
recommendations for the next steps:

Intermediate Python
Feeling comfortable with the basics of Python? Intermediate Python 3 is a
stepping stone to take your skills to the next level. This course will provide
you with the knowledge to make your Python code cleaner, more efficient,
and more manageable. We’ll also dive under the hood of fundamental
concepts that will deepen your understanding of the Python language.
This course is a deep dive into the inner workings of some of Python’s most
popular features to teach you how to use the language’s unique features to
get closer to becoming a Python expert.
While completing Learn Intermediate Python 3, you’ll learn about:
182
• The various ways to utilize functions to create cleaner and more
manageable code
• The core pillars of one of the most popular programming paradigms -
Object-Oriented Programming
• How Python iteration works under the hood and how to create custom
iterators using generator functions
• How to use specialized Python collections as alternatives to Python’s
general-purpose built-in containers
• How to better manage resources using context managers
• How to use the Python Unittest library to test complex applications
Get started now!

Pass the Technical Interview with Python


You’ll need to pass a technical interview if you want to be hired for a
technical role. Don’t worry — these interviews are pretty predictable, and
the same kinds of problems appear again and again. Even if you don’t have
a technical interview scheduled just yet, practicing these common problems
will help you grow as a programmer and problem solver, and will help you
write cleaner more efficient code.
In this path, you’ll get a broad overview of computer science concepts: data
structures, algorithms, and common applications of both. You’ll build
implementations of each data structure and algorithm from scratch in
modern Python.
Jump into interview prep now!

More Python!
Don’t worry, if the above courses don’t pique your interest, we have plenty
of other options:

183
• Build Python Web Apps with Flask
In this path, you will learn the foundations of Python so you can use it to
create fully-featured, interactive web applications. Along your journey, you
will learn how to code in Python, design and access databases, create
interactive web applications, and share your apps with the world.
Alternatively, try out Build Python Web Apps with Django, another popular
web framework for Python!
• Analyze Data with Python
Data is everywhere. That means more companies are tracking, analyzing,
and using the insights they find to make better decisions. In this Skill Path,
you’ll learn the fundamentals of data analysis while building Python skills.
• Build Chatbots with Python
It turns out, you don’t need to know linear algebra to make advanced
chatbots with artificial intelligence. In this Skill Path, we’ll take you from
being a complete Python beginner to creating chatbots that teach
themselves. Say hello to your next cutting-edge skill.

184
JAVA
1. HELLO WORLD
1.1 Introduction to Java
Welcome to the world of Java programming!

Programming languages enable humans to write instructions that a computer


can perform. With precise instructions, computers coordinate applications and
systems that run the modern world.

Sun Microsystems released the Java programming language in 1995. Java is


known for being simple, portable, secure, and robust. Though it was released
over twenty years ago, Java remains one of the most popular programming
languages today.

One reason people love Java is the Java Virtual Machine, which ensures the
same Java code can be run on different operating systems and platforms. Sun
Microsystems’ slogan for Java was “write once, run everywhere”.

Programming languages are composed of syntax, the specific instructions which


Java understands. We write syntax in files to create programs, which are
executed by the computer to perform the desired task.

Let’s start with the universal greeting for a programming language. We’ll explore
the syntax in the next exercise.

185
1.1 Introduction to Java Instructions
1.
You’re looking at a computer program written in Java.

Run the code in the text editor to see what is printed to the screen.

public class HelloWorld {


public static void main(String[] args) {
186
System.out.println("Hello World!");
}
}
OUTPUT
Hello World!

1.2 Hello Java File!


Java runs on different platforms, but programmers write it the same way. Let’s
explore some rules for writing Java.
In the last exercise, we saw the file HelloWorld.java. Java files have
a .java extension. Some programs are one file, others are hundreds of files!
Inside HelloWorld.java, we had a class:
public class HelloWorld {

}
We’ll talk about classes more in the future, but for now think of them as
a single concept.
The HelloWorld concept is: Hello World Printer. Other class concepts could be:
Bicycle, or: Savings Account.
We marked the domain of this concept using curly braces: {}. Syntax inside the
curly braces is part of the class.
Each file has one primary class named after the file. Our class
name: HelloWorld and our file name: HelloWorld. Every word is capitalized.
Inside the class we had a main() method which lists our program tasks:
public static void main(String[] args) {

}
Like classes, we used curly braces to mark the beginning and end of a method.

187
public, static, and void are syntax we’ll learn about in future lessons. String[]
args is a placeholder for information we want to pass into our program. This
syntax is necessary for the program to run but more advanced than we need to
explore at the moment.
Our program also displayed the text "Hello World" on the screen. This was
accomplished using a print statement:
System.out.println("Hello World");
We’ll learn more about print statements in the next exercise!
1.2 Hello Java File! Instructions
1.
The text editor has a file, HelloYou.java, that contains a HelloYou class with
a main() method.
Inside main(), add a statement which prints Hello someName!, with your name
replacing someName. Make sure to end the statement with a semicolon.
For example, if your name were “Maria,” the program would print Hello Maria!.
public class HelloYou {
public static void main(String[] args) {

}
}
OUTPUT
Hello Vishva!

1.3 Print Statements


Let’s take a closer look at this instruction from our previous program:
System.out.println("Hello World");

188
Print statements output information to the screen (also referred to as
the output terminal). Let’s break this line of code down a little more. Don’t worry
if some of the terms here are new to you. We’ll dive into what all of these are in
much more detail later on!
● System is a built-in Java class that contains useful tools for our programs.
● out is short for “output”.
● println is short for “print line”.
We can use System.out.println() whenever we want the program to create a new
line on the screen after outputting a value:
System.out.println("Hello World");
System.out.println("Today is a great day to code!");
After "Hello World" is printed, the output terminal creates a new line for the next
statement to be outputted. This program will print each statement on a new line
like so:
Hello World
Today is a great day to code!
We also can output information using System.out.print(). Notice that we’re
using print(), not println(). Unlike System.out.println(), this type of print
statement outputs everything on the same line. For example:
System.out.print("Hello ");
System.out.print("World");
The above code will have the following output:
Hello World
In this example, if you were to use print() or println() again, the new text will print
immediately after World on the same line. It’s important to remember where you
left your program’s “cursor”. If you use println() the cursor is moved to the next
line. If you use print() the cursor stays on the same line.

189
Note: Going forward after this exercise, all exercises will
use System.out.println() to output values. You will get to practice
using System.out.print() statements in the Checkpoints below, however.
1.3 Print Statements Instructions
1.
Inside main() and underneath the print statement System.out.println("Let's play
hide and seek.");, output the following two statements using System.out.print():
● "Three..."
● "Two..."

2.
Underneath your previous statements, output the following two text values
using System.out.println():
● "One..."
● "Ready or not, here I come!"
public class HideAndSeek {
public static void main(String[] args) {
System.out.println("Let's play hide and seek.");

}
}
OUTPUT
Let's play hide and seek.
Three...Two...One...
Ready or not, here I come!

190
1.4 Commenting Code
Writing code is an exciting process of instructing the computer to complete
fantastic tasks.
Code is also read by people, and we want our intentions to be clear to humans
just like we want our instructions to be clear to the computer.
Fortunately, we’re not limited to writing syntax that performs a task. We can also
write comments, notes to human readers of our code. These comments are not
executed, so there’s no need for valid syntax within a comment.
When comments are short we use the single-line syntax: //.
// calculate customer satisfaction rating
When comments are long we use the multi-line syntax: /* and */.
/*
We chose to store information across multiple databases to
minimize the possibility of data loss. We'll need to be careful
to make sure it does not go out of sync!
*/
Another type of commenting option is the Javadoc comment which is represented
by /** and */. Javadoc comments are used to create documentation for APIs
(Application Programming Interfaces). When writing Javadoc comments,
remember that they will eventually be used in the documentation that your users
might read, so make sure to be especially thoughtful when writing these
comments.
Javadoc comments are typically written before the declaration of fields, methods,
and classes (which we’ll cover later in this course):
/**
* The following class accomplishes the following task...
*/
Here’s how a comment would look in a complete program:

191
/**
* The following class shows what a comment would look like in a program.
*/
public class CommentExample {
// I'm a comment inside the class
public static void main(String[] args) {
// I'm a comment inside a method
System.out.println("This program has comments!");
}
}
Comments are different from printing to the screen, when we
use System.out.println(). These comments won’t show up in our terminal, they’re
only for people who read our code in the text editor.
1.4 Commenting Code Instructions
1.
The file Timeline.java has plain text information about Java.
Plain text facts aren’t valid syntax. We’ll use comments to avoid breaking the
program.
Use the single-line comment syntax for the first fact.
Change this line into a comment:
Sun Microsystems announced the release of Java in 1995

2.
Our program is still broken!
Use the multi-line syntax to make these lines into a single comment:
James Gosling is a Canadian engineer who created Java while
working at Sun Microsystems. His favorite number is the
square root of 2!
You should still see You are a fun language! printed!
192
public class Timeline {
public static void main(String[] args) {
System.out.println("Hello Java!");

System.out.println("You were born in 1995");

Sun Microsystems announced the release of Java in 1995

System.out.println("You were created by James Gosling");

James Gosling is a Canadian engineer who


created Java while working at Sun Microsystems.
His favorite number is the square root of 2!

System.out.println("You are a fun language!");


}
}
OUTPUT
Hello Java!
You were born in 1995
You were created by James Gosling
You are a fun language!

1.5 Semicolons and Whitespace


As we saw with comments, reading code is just as important as writing code.

193
We should write code that is easy for other people to read. Those people can be
co-workers, friends, or even yourself!
Java does not interpret whitespace, the areas of the code without syntax, but
humans use whitespace to read code without difficulty.
Functionally, these two code samples are identical:
System.out.println("Java");System.out.println("Lava");System.out.println("Guava"
);
System.out.println("Java");

System.out.println("Lava");

System.out.println("Guava");
They will print the same text to the screen, but which would you prefer to read?
Imagine if it was hundreds of instructions! Whitespace would be essential.
Java does interpret semicolons. Semicolons are used to mark the end of
a statement, one line of code that performs a single task.
The only statements we’ve seen so far are System.out.println("My message!");.
Let’s contrast statements with the curly brace, {}. Curly braces mark the scope of
our classes and methods. There are no semicolons at the end of a curly brace.
1.5 Semicolons and Whitespace Instructions
1.
The LanguageFacts.java file prints information about Java to the screen.
Unfortunately, the writer of the file has avoided using whitespace.
Make the file easier to read by adding a newline after each statement!

2.
Inside main(), add a new statement printing how you feel about coding.
Start the message with: “Programming is… “.
194
Remember to place a semicolon at the end of the statement!
public class LanguageFacts {
public static void main(String[] args) {
// Press enter or return on your keyboard after each semicolon!

System.out.println("Java is a class-based language.");System.out.println("Java


classes have a 'main' method.");System.out.println("Java statements end with a
semicolon.");
}
}
OUTPUT
Java is a class-based language.
Java classes have a 'main' method.
Java statements end with a semicolon.
Programming is... fun!

1.6 Compilation: Catching Errors


Java is a compiled programming language, meaning the code we write in
a .java file is transformed into byte code by a compiler before it is executed by the
Java Virtual Machine on your computer.
A compiler is a program that translates human-friendly programming languages
into other programming languages that computers can execute.

195
Previous exercises have automatically compiled and run the files for you. Off-
platform development environments can also compile and run files for you, but
it’s important to understand this aspect of Java development so we’ll do it
ourselves.
The compiling process catches mistakes before the computer runs our code.
The Java compiler runs a series of checks while it transforms the code. Code that
does not pass these checks will not be compiled.
This exercise will use an interactive terminal. Codecademy has a lesson on the
command line if you’d like to learn more.
For example, with a file called Plankton.java, we could compile it with the
terminal command:
javac Plankton.java
A successful compilation produces a .class file: Plankton.class, that we execute
with the terminal command:
java Plankton
An unsuccessful compilation produces a list of errors. No .class file is made until
the errors are corrected and the compile command is run again.
1.6 Compilation: Catching Errors Instructions
1.
Let’s practice compiling and executing a file by entering commands in the
terminal!
Our text editor contains a broken program so we can see how compilers help us
catch mistakes. Don’t make any corrections!
In the terminal, type this command: javac Compiling.java and
press enter or return.
Then click the Check Work button to check your work and move on to the next
checkpoint.

196
2.
Do you see the error?
The compiler is telling us one of the print statements is missing a semicolon.
In the terminal, type ls and press return or enter.
ls is short for "list" and this command lists all the available files.
There is only one file: Compiling.java, we did not successfully compile the file
because of the error.
Click the Check Work button to move on to the next checkpoint.

3.
Add the missing semicolon in the text editor, then click the Check Work button.
We’ll compile and execute this file in the next exercise!
public class Compiling {
public static void main(String[] args) {

System.out.println("Java is a class-based language.");


System.out.println("Java classes have a 'main' method.");
System.out.println("Java statements end with a semicolon.")

System.out.println("Programming is... fun!");

}
}
OUTPUT

197
1.7 Compilation: Creating Executables
Compilation helped us catch an error. Now that we’ve corrected the file, let’s
walk through a successful compilation.
As a reminder, we can compile a .java file from the terminal with the command:
javac Whales.java
If the file compiles successfully, this command produces
an executable class: FileName.class. Executable means we can run this program
from the terminal.
We run the executable with the command:
java Whales
Note that we leave off the .class part of the filename.
Here’s a full compilation cycle as an example:
// within the file: Welcome.java
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Codecademy's Java course!");
}
}
We have one file: Welcome.java. We compile with the command:
javac Welcome.java
The terminal shows no errors, which indicates a successful compilation.

198
We now have two files:
1. Welcome.java, our original file with Java syntax.
2. Welcome.class, our compiled file with Java bytecode, ready to be executed
by the Java Virtual Machine.
We can execute the compiled class with the command:
java Welcome
The following is printed to the screen:
Welcome to Codecademy's Java course!
1.7 Compilation: Creating Executables Instructions
1.
Let’s compile and execute our program!
Run the ls command in the terminal to see the uncompiled .java file.
Press the Check Work button after you finish each checkpoint.

2.
Compile the file from the terminal and then press the Check Work button.

3.
Enter ls again to see the new .class file.
Run the executable file from the terminal and then press the Check Work button.
public class Compiling {
public static void main(String[] args) {

System.out.println("Java is a class-based language.");


System.out.println("Java classes have a 'main' method.");

199
System.out.println("Java statements end with a semicolon.");

System.out.println("Programming is... fun!");

}
}
OUTPUT

1.8 Java Review: Putting It All Together


In this lesson, we’ve started writing our first programs in Java.
We’ve also learned rules and guidelines for how to write Java programs:
● Java programs have at least one class and one main() method.
o Each class represents one real-world idea.
o The main() method runs the tasks of the program.
● Java comments add helpful context to human readers.
● Java has whitespace, curly braces, and semicolons.
o Whitespace is for humans to read code easily.

200
o Curly braces mark the scope of a class and method.
o Semicolons mark the end of a statement.
● Java is a compiled language.
o Compiling catches mistakes in our code.
o Compilers transform code into an executable class.

1.8 Java Review: Putting It All Together Instructions


1.
The text editor holds an empty file named Review.java. Fill it in!
Define a public class named Review.
Use opening and closing curly braces for the scope of the class.
Remember, no semicolons for classes or methods!

2.
This code produces an error because Java programs need a main() method.
Define the main() method within the curly braces of the Review class.

3.
Inside of the curly braces for the main() method, write The main method executes
the tasks of the class as a single-line comment.

4.
Below the comment, write a statement that prints the following: My first Java
program from scratch!.

__________________________________________
201
Java Program Structure
Java programs have a specific structure. Let’s take a closer look at the Hello
World program — line by line!
Java programs have a specific structure in how the code is written. There are key
elements that all Java programs share.
The Program
We have the text of a program inside the file called HelloWorld.java.
// This program outputs the message "Hello World!" to the monitor

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello World!");
}
}
This program writes Hello World! to your terminal when run.
Case-Sensitivity
Java is a case-sensitive language. Case sensitivity means that syntax, the words
our computer understands, must match the case. For example, the Java command
for outputting text to the screen is System.out.println(). If you were to
type system.out.println() or System.Out.println(), the compiler would not know
that your intention was to use System or out.
Let’s go over this HelloWorld.java program line by line:
Comments
// This program outputs the message "Hello World!" to the monitor
This is a single-line comment that documents the code. The compiler will ignore
everything after // to the end of the line. Comments provide information outside
the syntax of the language.
Classes

202
public class HelloWorld {
// class code
}
This is the class of the file. All Java programs are made of at least one class. The
class name must match the file: our file is HelloWorld.java and our class
is HelloWorld. We capitalize every word, a style known as pascal case. Java
variables and methods are named in a similar style called camel case where every
word after the first is capitalized.
The curly braces, { and }, mark the scope of the class. Everything inside the curly
braces is part of the class.
Methods
public static void main(String[] args) {
// Statements
}
Every Java program must have a method called main(). A method is a sequence of
tasks for the computer to execute. This main() method holds all of the
instructions for our program.
Statements
System.out.println("Hello World!");
This code uses the method println() to send the text “Hello World!” to the
terminal as output. println() comes from an object called out, which is responsible
for various types of output. Objects are packages of state and behavior, and
they’re often modeled on real-world things.
out is located within System, which is another object responsible for representing
our computer within the program! We can access parts of an object with a .,
which is known as dot notation.
This line of code is a statement, because it performs a single task. Statements
always conclude with a semicolon.
Whitespace

203
Java programs allow judicious use of whitespace (tabs, spaces, newlines) to create
code that is easier to read. The compiler ignores whitespace, but humans need it!
Use whitespace to indent and separate lines of code. Whitespace increases the
readability of your code.
Practice
The structure of a Java program will feel familiar the more you work with this
language. Continue learning at Codecademy and you’ll be a Java pro in no time!

For bookmarking:
● Twitter Java Style Guide
● Google Java Style Guide

__________________________________________
1. Quiz
1. What is missing from this Java program?
public class LanguageFacts {

// Covers the history of the Java programming language

a) The curly braces that mark the scope of the class.


b) The main() method: public static void main(String[] args) {}
c) A single-line comment.
d) The line to compile code: javac LanguageFacts.java
2. What would the name of the file be if it contained the following code?
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");

204
}
}
a) HelloWorld.java
b) There are no restrictions on file name in Java.
c) HelloWorld.class
3. The following code will run without an error.
public class LanguageFacts {
public static void main(String[] args) {
System.out.println("Java is a class-based language.");
System.out.println("Java classes have a 'main()' method.");
System.out.println("Java statements end with a semicolon.")
}
}
a) False.
b) True.
4. In Java, what is the purpose of leaving comments in code?
a) They provide human readable notes that clarify thinking.
b) They are how words are printed to the screen.
c) They provide checks that the compiler must pass.
d) They are only present in compiled code.
5. Java is a compiled language, meaning the code we write is translated by
another program into a language the computer understands.
a) True.
b) False.
6. What will the following code print to the screen?
public class HelloYou {
public static void main(String[] args) {
System.out.println("Hello Codey!");
}
}

205
a) This code contains an error.
b) “Hello Codey!”
c) Hello Codey!
7. Comment the code with the correct syntax.
public class Timeline {
public static void main(String[] args) {

____Sun Microsystems announced the release of Java in 1995

______
James Gosling is a Canadian engineer who created Java while
working at Sun Microsystems. His favorite number is the
square root of 2!
______

}
}

__________________________________________
Project-1
Planting a Tree
Introduce yourself to users and plant a tree for them!
Tasks
Creating the Class
1.
We’re starting with a blank Java file named Tree.java.
Define a class that follows the Java naming conventions.

2.

206
This code produces an error because our program needs a main() method.
Define this method inside the curly braces of the Tree class.

3.
Write a comment in main() that describes the task it will perform.
We’re going to introduce ourselves and print a tree to the screen.
You can use the single-line or multi-line syntax for your comment.

4.
Below your comment, print a message introducing yourself to the user.
Try something like “Hey there, I’m Ariel and I’m learning to code in Java!”
When you run the code, you should see this message printed to the screen.

Planting Trees
5.
After introducing yourself, use another print statement to output the project
goal!
Something like “I’m going to plant a tree today!” or “Ready to get my hands
dirty!”
6.
See how the second statement begins on a new line? We’ll use multiple print
statements to plant our tree.
For example:
System.out.println(" * ");
System.out.println(" *** ");
System.out.println(" *** ");

207
System.out.println(" * ");
System.out.println(" * ");
will print a tree like this:
*
***
***
*
*
Try it out!
7.
Have fun and experiment with different trees.
Here are a couple we made:
* ** *
******
****
**
**
~~~~~~~~~~
*****
*****
*****
*
*
#######

__________________________________________
What Is an IDE?
Learn about the Integrated Development Environment, an application that
makes programming easier!
What is an IDE?

208
An IDE, or Integrated Development Environment, enables programmers to
consolidate the different aspects of writing a computer program.
IDEs increase programmer productivity by combining common activities of writing
software into a single application: editing source code, building executables, and
debugging.
Editing Source Code
Writing code is an important part of programming. We start with a blank file,
write a few lines of code, and a program is born! IDEs facilitate this process with
features like syntax highlighting and autocomplete.
Syntax Highlighting
An IDE that knows the syntax of your language can provide visual cues. Keywords,
words that have special meaning like class in Java, are highlighted with different
colors.
Compare these two code samples:
// without syntax highlighting

public class NiceDay {


public static void main(String[] args) {
System.out.println("It's a nice day out!");
}
}
// with syntax highlighting

public class NiceDay {


public static void main(String[] args) {
System.out.println("It's a nice day out!");
}
}
Syntax highlighting makes code easier to read by visually clarifying different
elements of language syntax.
Autocomplete
209
When the IDE knows your programming language, it can anticipate what you’re
going to type next!
We’ve seen statements with System.out.println() quite a bit so far. In an IDE, we
might see System as an autocomplete option after only typing Sy. This saves
keystrokes so the programmer can focus on logic in their code.

Building Executables
Java is a compiled language. Before programs run, the source code of a .java file
must be transformed into an executable .class by the compiler. Once compiled,
the program can be run from the terminal.
This compilation process is necessary for every program, so why not have the IDE
do it for us? IDEs provide automated build processes for languages, so the act of
compiling and executing code is abstracted away, like in Codecademy lessons.
Debugging

210
No programmer avoids writing bugs and programs with errors.
When a program does not run correctly, IDEs provide debugging tools that allow
programmers to examine different variables and inspect their code in a deliberate
way.
IDEs also provide hints while coding to prevent errors before compilation.

Coding On Your Computer


The biggest benefit to using an IDE is that it allows you to code and run Java
programs on your own computer. We recommend IntelliJ IDEA, which you can
download for macOS, Windows, or Linux.
You should download and install Java to your computer before using an IDE.
Here are two videos that walk through how to set up an IDE and run Java code.
● Mac

211
● Windows

______________________________________________
Concept Review
Print Line
System.out.println() can print to the console:
● System is a class from the core library provided by Java
● out is an object that controls the output
● println() is a method associated with that object that receives a single
argument
System.out.println("Hello, world!");
// Output: Hello, world!
Comments
Comments are bits of text that are ignored by the compiler. They are used to
increase the readability of a program.
● Single line comments are created by using //.
● Multi-line comments are created by starting with /* and ending with */.
// I am a single line comment!

/*
And I am a
multi-line comment!
*/
main() Method
In Java, every application must contain a main() method, which is the entry point
for the application. All other methods are invoked from the main() method.

212
The signature of the method is public static void main(String[] args) { }. It accepts
a single argument: an array of elements of type String.
public class Person {

public static void main(String[] args) {

System.out.println("Hello, world!");

}
Classes
A class represents a single concept.
A Java program must have one class whose name is the same as the program
filename.
In the example, the Person class must be declared in a program file
named Person.java.
public class Person {

public static void main(String[] args) {

System.out.println("I am a person, not a computer.");

213
}
Compiling Java
In Java, when we compile a program, each individual class is converted into
a .class file, which is known as byte code.
The JVM (Java virtual machine) is used to run the byte code.
# Compile the class file:
javac hello.java

# Execute the compiled file:


java hello
Whitespace
Whitespace, including spaces and newlines, between statements is ignored.
System.out.println("Example of a statement");

System.out.println("Another statement");

// Output:
// Example of a statement
// Another statement
Statements
In Java, a statement is a line of code that executes a task and is terminated with
a ;.
System.out.println("Java Programming ");

214
2. VARIABLES
2.1 Introduction
Let’s say we need a program that connects a user with new jobs. We need the
user’s name, their salary, and their employment status. All of these pieces of
information are stored in our program.
We store information in variables, named locations in memory.
Naming a piece of information allows us to use that name later, accessing the
information we stored.
Variables also give context and meaning to the data we’re storing. The
value 42 could be someone’s age, a weight in pounds, or the number of orders
placed. With a name, we know the value 42 is age, weightInPounds,
or numOrdersPlaced.
In Java, we specify the type of information we’re storing. Primitive data types are
types of data built-in to the Java system. The three main primitive types we’ll
cover are int, double, and boolean; this lesson will introduce these built-in types
and more.
We must declare a variable to reference it within our program. Declaring a
variable requires that we specify the type and name:
// datatype variableName
int age;
double salaryRequirement;
boolean isEmployed;
The names of the variables above are age, salaryRequirement, and isEmployed.
These variables don’t have any associated value. To assign a value to a variable,
we use the assignment operator =:
age = 85;

215
Now, age has a value of 85. When code is used to represent a fixed value, like 85,
it is referred to as a literal.
It’s also common to declare a variable and assign it a value in one line!
For example, to assign 2011 to a variable named yearCodecademyWasFounded of
type int, we write:
int yearCodecademyWasFounded = 2011;
2.1 Introduction Instructions
1.
In Creator.java, we have defined some variables related to James Gosling, the
creator of Java.
Inside main(), use System.out.println() to print out the variable name.
2.
Use the same command to print out yearCreated.
public class Creator {
public static void main(String[] args) {
String name = "James Gosling";
int yearCreated = 1995;
}
}
Output:
James Gosling
1995

2.2 ints
The first type of data we will store is the whole number. Whole numbers are very
common in programming. You often see them used to store ages, or maximum
sizes, or the number of times some code has been run, among many other uses.
216
In Java, whole numbers are stored in the int primitive data type.
ints hold positive numbers, negative numbers, and zero. They do not store
fractions or numbers with decimals in them.
The int data type allows values between -2,147,483,648 and 2,147,483,647,
inclusive.
To declare a variable of type int, we use the int keyword before the variable
name:
// int variable declaration
int yearJavaWasCreated;
// assignment
yearJavaWasCreated = 1996;
// declaration and assignment
int numberOfPrimitiveTypes = 8;
2.2 ints Instructions
1.
The file CountComment.java has a number of comments in it.
In your head, count the number of comments. Then, inside the main() method,
declare a variable called numComments that holds how many comments you
counted.
2.
Print out numComments.
//This is the class declaration
public class CountComment {
//This is the main method that runs when you compile
public static void main(String[] args) {
//This is where you will define your variable

//This is where you will print your variable


217
}

//This is the end of the class


}

//This is outside the class


Output
6

2.3 doubles
Whole numbers don’t accomplish what we need for every program. What if we
wanted to store the price of something? We need a decimal point. What if we
wanted to store the world’s population? That number would be larger than
the int type can hold.
The double primitive data type can help. double can hold decimals as well as very
large and very small numbers. The maximum value is 1.797,693,134,862,315,7
E+308, which is approximately 17 followed by 307 zeros. The minimum value is
4.9 E-324, which is 324 decimal places!
To declare a variable of type double, we use the double keyword in the
declaration:
// doubles can have decimal places:
double price = 8.99;
// doubles can have values bigger than what an int could hold:
double gdp = 12237700000;
2.3 doubles Instructions
1.

218
As of 2016, Android has 81.7 percent of the market share for mobile operating
systems. Create a variable called androidShare that holds this percentage as a
double.
2.
Print out androidShare to the console.
public class MarketShare {
public static void main(String[] args) {

}
}
OUTPUT
81.7

2.4 booleans
Often our programs face questions that can only be answered with yes or no.
Is the oven on? Is the light green? Did I eat breakfast?
These questions are answered with a boolean, a type that references one of two
values: true or false.
We declare boolean variables by using the keyword boolean before the variable
name.
boolean javaIsACompiledLanguage = true;
boolean javaIsACupOfCoffee = false;
In future lessons, we’ll see how boolean values help navigate decisions in our
programs.
2.4 booleans Instructions
1.
Create a variable called intsCanHoldDecimals. Set it to true if the int type can hold
a decimal number. Set it to false if the int type cannot do this.
219
2.
Print out your intsCanHoldDecimals variable.
public class Booleans {
public static void main(String[] args) {

}
}
OUTPUT
false

2.5 char
How do we answer questions like: What grade did you get on the test? What
letter does your name start with?
The char data type can hold any character, like a letter, space, or punctuation
mark.
It must be surrounded by single quotes, '.
For example:
char grade = 'A';
char firstLetter = 'p';
char punctuation = '!';
2.5 char Instructions
1.
Create a variable called expectedGrade of type char.
Fill it with a single letter, representing the grade you think you would get in a
graded Java course where the grades A, B, C, D and F are possible.
2.
Print out your expectedGrade variable!

220
public class Char {
public static void main(String[] args) {

}
}
OUTPUT
A

2.6 String
So far, we have learned primitive data types, which are the simplest types of data
with no built-in behavior. Our programs will also use Strings, which are objects,
instead of primitives. Objects have built-in behavior.
Strings hold sequences of characters. We’ve already seen instances of a String, for
example, when we printed out "Hello World". There are two ways to create
a String object: using a String literal or calling the String class to create a
new String object.
A String literal is any sequence of characters enclosed in double-quotes (""). Like
primitive-type variables, we declare a String variable by specifying the type first:
String greeting = "Hello World";
We could also create a new String object by calling the String class when declaring
a String like so:
String salutations = new String("Hello World");
There are subtle differences in behavior depending on whether you create
a String using a String literal or a new String object. We’ll dive into those later, but
for now, we’ll almost always be using String literals.
Keep Reading: AP Computer Science A Students
Certain symbols, known as escape sequences, have an alternative use in Java print
statements. Escape sequences are interpreted differently by the compiler than
other characters. Escape characters begin with the character \.

221
There are three escape sequences to be aware of for the AP exam.
The \" escape sequence allows us to add quotation marks " to a String value. :
System.out.println("\"Hello World\"");
// Prints: "Hello World"
If we didn’t use an escape sequence, then Java would think we’re using " to end
the String!
Using the \\ escape sequence allows us to place backslashes in our String text:
System.out.println("This is the backslash symbol: \\");
// Prints: This is the backslash symbol: \
This is similar to the last example - just like ", \ usually has a special meaning. In
this case, \ is used to start an escape sequence. Well, if we don’t want to start an
escape sequence and just want a \ in our String, then we’ll use \\ — we’re using
an escape sequence to say that we don’t want \ to be interpreted as the start of
an escape sequence. It’s a little mind-bending!
Finally, if we place a \n escape sequence in a String, the compiler will output a
new line of text:
System.out.println("Hello\nGoodbye");
/*
Prints:
Hello
Goodbye
*/
You can think of \n as the escape sequence for “newline”.
2.6 String Instructions
1.
Create a variable called openingLyrics that has a value of: "Yesterday, all my
troubles seemed so far away"
2.
Call System.out.println() to print out openingLyrics.
222
public class Song {
public static void main(String[] args) {

}
}
OUTPUT
Yesterday, all my troubles seemed so far away

2.7 Static Checking


The Java programming language has static typing. Java programs will not compile
if a variable is assigned a value of an incorrect type. This is a bug, specifically a
type declaration bug.
Bugs are dangerous! They cause our code to crash, or produce incorrect results.
Static typing helps because bugs are caught during programming rather than
during execution of the code.
The program will not compile if the declared type of the variable does not match
the type of the assigned value:
int greeting = "Hello World";
The String "Hello World" cannot be held in a variable of type int.
For the example above, we see an error in the console at compilation:
error: incompatible types: String cannot be converted to int
int greeting = "Hello World";
When bugs are not caught at compilation, they interrupt execution of the code by
causing runtime errors. The program will crash.
Java’s static typing helps programmers avoid runtime errors, and thus have much
safer code that is free from bugs.
2.7 Static Checking Instructions
1.

223
In the Mess.java file, we have declared a bunch of variables with the wrong type.
Try to compile the file using the command:
javac Mess.java
2.
Change the types of the variables so that they correspond with the type of the
assignment values.
For example, year is assigned 2001, so it should be an int.
3.
Compile the file again. Look at how it compiles with no errors now!
public class Mess {
public static void main(String[] args) {
String year = 2001;
double title = "Shrek";
int genre = 'C';
boolean runtime = 1.58;
char isPG = true;
}
}

2.8 Naming
Let’s imagine we’re storing a user’s name for their profile. Which code example
do you think is better?
String data = "Delilah";
or
String nameOfUser = "Delilah";

224
While both of these will compile, the second example is much easier to
understand. Readers of the code will know the purpose of the value: "Delilah".
Naming variables according to convention leads to clear, readable, and
maintainable code. When someone else, or our future self, reads the code, there
is no confusion about the purpose of a variable.
In Java, variable names are case-sensitive. myHeight is a different variable
from myheight. The length of a variable name is unlimited, but we should keep it
concise while keeping the meaning clear.
A variable starts with a valid letter, or a $, or a _. No other symbols or numbers
can begin a variable name. 1stPlace and *Gazer are not valid variable names.
Variable names of only one word are spelled in all lowercase letters. Variable
names of more than one word have the first letter lowercase while the beginning
letter of each subsequent word is capitalized. This style of capitalization is
called camelCase.
// good style
boolean isHuman;

// bad styles
// no capitalization for new word
boolean ishuman;
// first word should be lowercase
boolean IsHuman;
// underscores don't separate words
boolean is_human;
2.8 Naming Instructions
1.
In the BadNames.java file, we declared variables with confusing names. Run the
file and look at the error messages you get when trying to compile.
2.
Some of these variable names are illegal! Change the ones that are preventing the
file from compiling.
225
public class BadNames {
public static void main(String[] args) {
String 1stName = "Samira";
String blah = "Smith";
String .com = "samira@google.com";
int salaryexpectation = 100000;
int year_of_birth = 1955;

System.out.println("The program runs!");


}
}
OUTPUT
The program runs!

2.9 Review
Creating and filling variables is a powerful concept that allows us to keep track of
all kinds of data in our program.
In this lesson, we learned how to create and print several different data types in
Java, which you’ll use as you create bigger and more complex programs.
We covered:
● int, which stores whole numbers.
● double, which stores bigger whole numbers and decimal numbers.
● boolean, which stores true and false.
● char, which stores single characters using single quotes.
● String, which stores multiple characters using double quotes.
● Static typing, which is one of the safety features of Java.

226
● Variable naming conventions.
Practice declaring variables and assigning values to make sure you have a solid
foundation for learning more complicated and exciting Java concepts!
2.9 Review Instructions
1.
The file MyProfile.java contains a class that represents your hiring profile as
presented to potential employers.
In the main() method, create a variable called name that holds your name, as a
sequence of characters.
2.
Create a variable called age that holds your age as a whole number.
3.
Create a variable called desiredSalary that holds your desired salary per year to a
precision of two decimal points.
4.
Create a variable called gender that holds a single
character, m (male), f (female), n (for none), or o (for other).
5.
Create a variable called lookingForJob that holds whether or not you are currently
open to job offers.
public class MyProfile {
public static void main(String[] args) {

}
}

__________________________________________
227
2. Quiz
1. What line of code declares a variable called numRabbits to store a whole
number?
a) numRabbits int;
b) number numRabbits;
c) int numRabbits;
d) numRabbits = int;
2. Which one of the following values is a valid char?
a) “a”
b) ‘ab’
c) 7
d) ‘F’
3. Which option is a valid variable name and follows the Java naming
conventions?
a) TimeUntilLaunch
b) 2ndPhoneNumber
c) second_phone_number
d) timeUntilLaunch
4. What value CANNOT be assigned to a variable with the datatype double.
a) 6.7
b) 5
c) -.2
d) “60”
5. Which of the following lines would throw a compilation error?
a) int balance = -30;
b) double isRaining = false;
c) String gradeOnTest = "A";
d) char grade_on_test = 'F';
6. Which line declares the variable bestProgrammingLanguage and initializes it to
be "Java"?

228
a) String bestProgrammingLanguage = "Java";
b) bestProgrammingLanguage = String "Java";
c) string bestProgrammingLanguage = "Java";
d) "Java" = String bestProgrammingLanguage;
7. What datatype can only be assigned one of two values?
a) double
b) int
c) boolean
d) char
8. What is the value of num?
int num = (10 - (4 + 3)) * 6;
a) 24
b) 18
c) -32
d) 20

__________________________________________
Project-2
Java Variables: Mad Libs
In this project, we’ll use Java to write a Mad Libs word game! Mad Libs have short
stories with blank spaces that a player can fill in. The result is usually funny (or
strange).
Mad Libs require:
● A short story with blank spaces (asking for different types of words).
● Words from the player to fill in those blanks.

229
“Roses are Red” poem example:

For this project, we have provided the story, but it will be up to you to complete
the following:
1. Create all the variables needed for the story.
2. Print the story with the variables in the right places.
Let’s begin!
Tasks
Mad Libs
1.
Let’s create a comment that describes the program!
The /* and */ are already in place for you. In between them, write a description
that looks something like:
This program generates a mad libbed story.
Author: Laura
Date: 2/19/2049
2.
Take a look at the variable named story. It is set equal to a string that will contain
our story.
230
All of these variables will need to be declared and initialized before the code will
compile without errors.
3.
The story that we have provided is going to need a protagonist.
Create a String called name1 that stores the name of the main character.
4.
You will need to provide three adjectives.
Create three Strings, adjective1, adjective2, and adjective3 and store different
adjectives in them.
5.
You’ll also need to provide one verb.
Create a String called verb1 and store a verb in it.
6.
The story also needs six nouns.
Create six Strings, noun1, noun2, noun3, noun4, noun5, and noun6 and initialize
them to your favorite nouns.
7.
Our story needs another character. Declare a String variable called name2 and
initialize it to the value of another name.
8.
Our story requires one number. Declare an int variable called number and set it to
any whole number you like.
9.
There’s one more variable! Declare a String called place1 and store any place in it.
This could be a city, or a town, or a country, or a planet!
10.

231
Alright! It seems like we have all the variables we need. Save the file to see it run.
Does it compile without errors?
11.
Time to read the story! Use System.out.println() to print the story variable.
12.
Put some whitespace in your code so that the story variable is hidden, and show
your friends the code. Have someone else fill in the variables you have declared
with the nouns, adjectives, verbs, and names that they like.
Then, run the code to see a new story get told!
public class MadLibs {
/*
Your description here
*/
public static void main(String[] args){

//The template for the story


String story = "This morning "+name1+" woke up feeling "+adjective1+". 'It is
going to be a "+adjective2+" day!' Outside, a bunch of "+noun1+"s were
protesting to keep "+noun2+" in stores. They began to "+verb1+" to the rhythm of
the "+noun3+", which made all the "+noun4+"s very "+adjective3+". Concerned,
"+name1+" texted "+name2+", who flew "+name1+" to "+place1+" and dropped
"+name1+" in a puddle of frozen "+noun5+". "+name1+" woke up in the year
"+number+", in a world where "+noun6+"s ruled the world.";
}
}

232
__________________________________________
Concept Review
boolean Data Type
In Java, the boolean primitive data type is used to store a value, which can be
either true or false.
boolean result = true;
boolean isMarried = false;
Strings
A String in Java is a Object that holds multiple characters. It is not a primitive
datatype.
A String can be created by placing characters between a pair of double quotes (").
To compare Strings, the equals() method must be used instead of the primitive
equality comparator ==.
// Creating a String variable
String name = "Bob";

// The following will print "false" because strings are case-sensitive


System.out.println(name.equals("bob"));
int Data Type
In Java, the int datatype is used to store integer values. This means that it can
store all positive and negative whole numbers and zero.
int num1 = 10; // positive value
int num2 = -5; // negative value
int num3 = 0; // zero value
int num4 = 12.5; // not allowed

233
char Data Type
In Java, char is used to store a single character. The character must be enclosed in
single quotes.
char answer = 'y';
Primitive Data Types
Java’s most basic data types are known as primitive data types and are in the
system by default.
The available types are as follows:
● int
● char
● boolean
● byte
● long
● short
● double
● float
null is another, but it can only ever store the value null.
int age = 28;

char grade = 'A';

boolean late = true;

byte b = 20;

234
long num1 = 1234567;

short no = 10;

float k = (float)12.5;

double pi = 3.14;
Static Typing
In Java, the type of a variable is checked at compile time. This is known as static
typing. It has the advantage of catching the errors at compile time rather than at
execution time.
Variables must be declared with the appropriate data type or the program will not
compile.
int i = 10; // type is int
char ch = 'a'; // type is char

j = 20; // won't compile, no type is given


char name = "Lil"; // won't compile, wrong data type
final Keyword
The value of a variable cannot be changed if the variable was declared using
the final keyword.
Note that the variable must be given a value when it is declared
as final. final variables cannot be changed; any attempts at doing so will result in
an error message.
// Value cannot be changed:
final double PI = 3.14;

235
double Data Type
The double primitive type is used to hold decimal values.
double PI = 3.14;
double price = 5.75;
Math Operations
Basic math operations can be applied to int, double and float data types:
● + addition
● - subtraction
● * multiplication
● / division
● % modulo (yields the remainder)
These operations are not supported for other data types.
int a = 20;
int b = 10;

int result;

result = a + b; // 30

result = a - b; // 10

result = a * b; // 200

result = a / b; // 2

236
result = a % b; // 0
Comparison Operators
Comparison operators can be used to compare two values:
● > greater than
● < less than
● >= greater than or equal to
● <= less than or equal to
● == equal to
● != not equal to
They are supported for primitive data types and the result of a comparison is a
boolean value true or false.
int a = 5;
int b = 3;

boolean result = a > b;


// result now holds the boolean value true
Compound Assignment Operators
Compound assignment operators can be used to change and reassign the value of
a variable using one line of code. Compound assignment operators include +=, -
=, *=, /=, and %=.
int number = 5;

number += 3; // Value is now 8


number -= 4; // Value is now 4
number *= 6; // Value is now 24

237
number /= 2; // Value is now 12
number %= 7; // Value is now 5
Increment and Decrement Operators
The increment operator, (++), can increase the value of a number-based variable
by 1 while the decrement operator, (--), can decrease the value of a variable by 1.
int numApples = 5;
numApples++; // Value is now 6

int numOranges = 5;
numOranges--; // Value is now 4
Order of Operations
The order in which an expression with multiple operators is evaluated is
determined by the order of operations: parentheses -> multiplication -> division -
> modulo -> addition -> subtraction.

238
3.Manipulating Variables
3.1 Introduction
Let’s say we are writing a program that represents a user’s bank account. With
variables, we know how to store a balance! We’d use a double, the primitive type
that can hold big decimal numbers. But how would we deposit and withdraw
from the account?
Lucky for us, we have the ability to manipulate the value of our variables. We can
use expressions, arithmetic operators, and more in order to change our variables’
values.
For example, Java has built-in arithmetic operations that perform calculations on
numeric values:
// declare initial balance
double balance = 20000.99;
// declare deposit amount
double depositAmount = 1000.00;
// store result of calculation in our original variable
balance = balance + depositAmount;
In the final line of the code above, we used the expression balance +
depositAmount to determine the new value of the balance variable. When an
expression is executed, it produces a single value.
The data type of a variable plays a large role in the operations we can use to
manipulate it. We can think of a data type as a combination of a set of values, and
a set of operations on those values. For example, the double data type is
comprised of values like 4.8 and operations like addition (+). For now, we’ll mainly
focus on the set of operations that can be used on numbers and booleans.
The data type of an expression is determined by the resulting value. For example,
an expression that uses two int values will evaluate to an int value. If an
expression contains a double value, then the resulting value will also be
type double.

239
Throughout this lesson, we will learn how to manipulate variables of different
data types.
3.1 Introduction Instructions
1.
In the file GuessingGame.java, we have defined two
integers mystery1 and mystery2.
We will talk about these operators, among others, in the rest of the lesson.
Use System.out.println() to print the variable that holds a value of 2.
public class GuessingGame {
public static void main(String[] args) {
int mystery1 = 8 + 6;
int mystery2 = 8 - 6;
}
}
OUTPUT
2

3.2 Addition and Subtraction


In our bank account example from the last exercise, we used the + operator to
add the values balance and depositAmount:
double balance = 20000.99;
double depositAmount = 1000.0;
balance = balance + depositAmount;
// balance now holds 21000.99
If we wanted to withdraw from the balance, we would use the - operator:
double withdrawAmount = 500;
balance = balance - withdrawAmount;
// balance now holds 19500.99
240
Addition and subtraction work with int type values as well! If we had 60 pictures
of cats on our phone, and we took 24 more, we could use the following line of
code to store 84 in numPicturesOfCats.
int numPicturesOfCats = 60 + 24;
What if we took one additional picture of our cat? We can reflect this change
using an increment operator ++. When we append ++ to a number-based variable,
it increases the value by 1. We also have the decrement operator, --, which
decreases the value by 1.
// Take a picture
numPicturesOfCats++ // Value is now 85

// Delete a picture
numPicturesOfCats-- // Value is now 84
3.2 Addition and Subtraction Instructions
1.
Create an int variable called animalsInZoo that holds the amount of zebras plus
the amount of giraffes at the zoo.
Then, print your animalsInZoo variable.
2.
Two of the zebras have been traded to a neighboring rival zoo. Subtract 2 from
the number of zebras and store the result in a variable
called numZebrasAfterTrade.
Then, print the numZebrasAfterTrade variable!
public class PlusAndMinus {
public static void main(String[] args) {
int zebrasInZoo = 8;
int giraffesInZoo = 4;
}

241
}
OUTPUT
12
6

3.3 Multiplication and Division


Let’s say that our employer is calculating our paycheck and depositing it to our
bank account. We worked 40 hours last week, at a rate of $15.50 an hour. Java
can calculate this with the multiplication operator *:
double paycheckAmount = 40 * 15.50;
//paycheckAmount now holds 620.0
If we want to see how many hours our total balance represents, we use the
division operator /:
double balance = 20010.5;
double hourlyRate = 15.5;
double hoursWorked = balance / hourlyRate;
//hoursWorked now holds 1291.0
Division has different results with integers. The / operator does integer division,
which means that any remainder is lost.
int evenlyDivided = 10 / 5;
//evenlyDivided holds 2, because 10 divided by 5 is 2
int unevenlyDivided = 10 / 4;
//unevenlyDivided holds 2, because 10 divided by 4 is 2.5
evenlyDivided stores what you expect, but unevenlyDivided holds 2 because ints
cannot store decimals! It’s important to note that the int doesn’t round the
decimal, but floors it. Java removes the 0.5 to fit the result into an int type!
It’s important to note that if we try to divide any number by 0, we will get
an ArithmeticException error as a result.
3.3 Multiplication and Division Instructions
1.
242
In main(), there is a variable called subtotal, which represents the subtotal of an
amount to pay on a bill, and a variable called tax, which represents the tax rate
that will be applied to that subtotal.
Create a double variable, total, that holds subtotal plus the product
of subtotal and tax.
Print the total variable!
2.
There were 4 people who bought this meal together and want to split the cost.
Create a double variable called perPerson that holds total divided by 4.
Print the perPerson variable!
public class MultAndDivide {
public static void main(String[] args) {
double subtotal = 30;
double tax = 0.0875;
}
}
OUTPUT
32.625
8.15625

3.4 Modulo
If we baked 10 cookies and gave them out in batches of 3, how many would we
have leftover after giving out all the full batches we could?
The modulo operator %, gives us the remainder after two numbers are divided.
int cookiesBaked = 10;
int cookiesLeftover = 10 % 3;
//cookiesLeftover holds 1

243
You have 1 cookie left after giving out all the batches of 3 you could!
Modulo can be a tricky concept, so let’s try another example.
Imagine we need to know whether a number is even or odd. An even number is
divisible by 2.
Modulo can help! Dividing an even number by 2 will have a remainder of 0.
Dividing an odd number by 2 will have a remainder of 1.
7%2
// 1, odd!
8%2
// 0, even!
9%2
// 1, odd!
3.4 Modulo Instructions
1.
You are trying to split up students into groups of 3. How many students will be
left out once the groups are made?
Create a variable called leftOut that holds the modulo of students and 3. Then,
print the variable!
public class Modulo {
public static void main(String[] args) {
int students = 26;
}
}
OUTPUT: 2

3.5 Compound Assignment Operators


Sometimes, we need to adjust the value of a variable.

244
Imagine we’re working at a bake sale and want to keep track of how many
cupcakes we have by creating a variable called numCupcakes:
int numCupcakes = 12;
If we baked 8 more cupcakes, we know that we could update our variable using
the + operator:
numCupcakes = numCupcakes + 8; // Value is now 20
While this method works just fine, we had to write our
variable numCupcakes twice. We can shorten this syntax by using a compound
assignment operator.
Compound assignment operators perform an arithmetic operation on a variable
and then reassigns its value. Using the += compound assignment operator, we can
rewrite our previous code like so:
numCupcakes += 8; // Value is now 20
Now we only need to reference numCupcakes once.
We can use compound assignment operators for all of the arithmetic operators
we’ve covered:
● Addition (+=)
● Subtraction (-=)
● Multiplication (*=)
● Division (/=)
● Modulo (%=)

3.5 Compound Assignment Operators Instructions


1.
You are also in charge of keeping track of how many cookies there are at the bake
sale. This value is represented by the variable numCookies.

245
A customer comes and buys 3 cookies. Use the appropriate compound
assignment operator to reflect this change.

2.
Another customer buys half of the remaining cookies.
Use the appropriate compound assignment operator to reflect this change.
public class BakeSale {
public static void main(String[] args) {
int numCookies = 17;

// Add your code above


System.out.println(numCookies);
}
}
OUTPUT
17

3.6 Order of Operations


If we were to place multiple operators in a single expression, what operation
would the compiler evaluate first?
int num = 5 * (10 - 4) + 4 / 2;
The order of operations dictates the order in which an expression (like the one
above) is evaluated. Operators that share the same precedence are evaluated
from Left-to-Right within the expression.
The order is as follows:
1. Parentheses
246
2. Exponents
3. Modulo/Multiplication/Division
4. Addition/Subtraction
With this new information in mind, let’s dissect the expression from above so that
we can find the value of num:
5 * (10 - 4) + 4 / 2
10 - 4 would be evaluated first because it is wrapped in parentheses. This value
would become 6 making our expression look like this:
5*6+4/2
Next, 5 * 6 will be evaluated because of the * operator. This value is 30. Our
expression now looks like this:
30 + 4 / 2
Following the order of operations, 4 / 2 will be evaluated next because the
division operator / has higher precedence than the addition operator +. Our
expression now resembles the following:
30 + 2
30 + 2 is 32. This means that the value of num is 32.
3.6 Order of Operations Instructions
Take a look at the expressions in Operations.java.
Solve for the value of each of the expressions on your own.
To find out if your calculations are right, uncomment the print statements and run
the code.
public class Operations {
public static void main(String[] args) {

int expression1 = 5 % 2 - (4 * 2 - 1);

247
// System.out.println(expression1);

int expression2 = (3 + (2 * 2 - 5)) + 6 - 5;


// System.out.println(expression2);

int expression3 = 5 * 4 % 3 - 2 + 1;
// System.out.println(expression3);

}
}
OUTPUT
-6
3
1

3.7 Greater Than and Less Than


Now, we’re withdrawing money from our bank account program, and we want to
see if we’re withdrawing less money than what we have available.
Java has relational operators for numeric datatypes that
make boolean comparisons. These include less than (<) and greater than (>),
which help us solve our withdrawal problem.
double balance = 20000.01;
double amountToWithdraw = 5000.01;
System.out.print(amountToWithdraw < balance);
//this will print true, since amountToWithdraw is less than balance
You can save the result of a comparison as a boolean, which you learned about in
the last lesson.

248
double myBalance = 200.05;
double costOfBuyingNewLaptop = 1000.05;
boolean canBuyLaptop = myBalance > costOfBuyingNewLaptop;
//canBuyLaptop is false, since 200.05 is not more than 1000.05
3.7 Greater Than and Less Than Instructions
1.
Print the expression that checks if the amount of credits you have
earned, creditsEarned, is greater than the number of credits you need to
graduate, creditsToGraduate.
2.
Create a variable called creditsAfterSeminar that holds the amount of credits
earned after taking a seminar, which is
worth creditsOfSeminar credits. creditsAfterSeminar should be the sum
of creditsEarned and creditsOfSeminar.
Print out whether creditsToGraduate is less than creditsAfterSeminar.
public class GreaterLessThan {
public static void main(String[] args) {
double creditsEarned = 176.5;
double creditsOfSeminar = 8;
double creditsToGraduate = 180;
}
}
OUTPUT
false
true

3.8 Equals and Not Equals


So how would we validate our paycheck to see if we got paid the right amount?
249
We can use another relational operator to do this. == will tell us if two variables
are equal:
double paycheckAmount = 620;
double calculatedPaycheck = 15.50 * 40;

System.out.print(paycheckAmount == calculatedPaycheck);
// This will print true, since paycheckAmount equals calculatedPaycheck
Notice that the equality check is two equal signs, instead of one. One equal
sign, =, is how we assign values to variables! It’s easy to mix these up, so make
sure to check your code for the right number of equal signs.
To check if two variables are not equal, we can use !=:
double balance = 20000.0;
double amountToDeposit = 620;
double updatedBalance = balance + amountToDeposit;

boolean balanceHasChanged = balance != updatedBalance;


// balanceHasChanged holds true, since balance does not equal updatedBalance
3.8 Equals and Not Equals Instructions
1.
You have unearthed two unlabeled albums, record A and record B.
To see if these are the same album, you’re going to compare the number of songs
on each one, and the total length of the albums.
First, create a variable called sameNumberOfSongs that stores whether the two
albums have the same number of songs.

2.
Now, create a variable called differentLength that stores the result of checking
whether the two album lengths are not the same.
public class EqualNotEqual {

250
public static void main(String[] args) {
int songsA = 9;
int songsB = 9;
int albumLengthA = 41;
int albumLengthB = 53;
}
}

3.9 Greater/Less Than or Equal To


How could we make sure we got paid at least the amount we expected in our
paycheck? We could use greater than or equal to, >=, or less than or equal to, <=!
double paycheckAmount = 620;
double calculatedPaycheck = 15.50 * 40;
System.out.println(paycheckAmount >= calculatedPaycheck);
//this will print true, since paycheckAmount equals calculatedPaycheck
3.9 Greater/Less Than or Equal To Instructions
1.
You have been trying to complete a 30 day challenge to drink enough water per
day.
Create a double variable called totalRecommendedAmount and set it to the
product of the recommended water intake (recommendedWaterIntake) and the
amount of days in the challenge (daysInChallenge).
2.
Create a boolean variable called isChallengeComplete and set it to the result of
checking if your intake, yourWaterIntake, is at least as much as
the totalRecommendedAmount.
Then, print the isChallengeComplete variable.
public class GreaterThanEqualTo {

251
public static void main(String[] args){
double recommendedWaterIntake = 8;
double daysInChallenge = 30;
double yourWaterIntake = 235.5;
}
}
OUTPUT
False

3.10 .equals()
So far, we’ve only been using operations on primitive types. It doesn’t make much
sense to multiply Strings, or see if one String is less than the other. But what if we
had two users logging into a site, and we wanted to see if their usernames were
the same?
With objects, such as Strings, we can’t use the primitive equality operator. To test
equality with objects, we use a built-in method called .equals(). When comparing
objects, make sure to always use .equals(). == will work occasionally, but the
reason why it sometimes works has to do with how objects are stored in memory.
For the purposes of this lesson (as well as good practice) remember to
use .equals() instead of == when comparing objects.
To use it, we call it on one String, by using ., and pass in the String to compare
against in parentheses:
String person1 = "Paul";
String person2 = "John";
String person3 = "Paul";

System.out.println(person1.equals(person2));
// Prints false, since "Paul" is not "John"

252
System.out.println(person1.equals(person3));
// Prints true, since "Paul" is "Paul"
3.10 .equals() Instructions
1.
We have three lines from a song in Song.java.
First, print out whether line1 and line2 are the same.

2.
Now, print whether line2 and line3 are equal.
public class Song {
public static void main(String[] args){
String line1 = "Nah nah nah nah nah nah nah nah nah yeah";
String line2 = "Nah nah nah nah nah nah, nah nah nah, hey Jude";
String line3 = "Nah nah nah nah nah nah, nah nah nah, hey Jude";
}
}
OUTPUT
false
true

3.11 String Concatenation


We have covered a lot of built-in functionality in Java throughout this lesson.
We’ve seen +, -, <, ==, and many other operators. Most of these only work on
primitives, but some work on Strings too!
Let’s say we want to print out a variable, and we want to describe it as we print it
out. For our bank account example, imagine we want to tell the user:
Your username is: <username>
253
With the value of the variable username displayed.
The + operator, which we used for adding numbers together, can be used
to concatenate Strings. In other words, we can use it to join two Strings together!
String username = "PrinceNelson";
System.out.println("Your username is: " + username);
This code will print:
Your username is: PrinceNelson
We can even use a primitive datatype as the second variable to concatenate, and
Java will intelligently make it a String first:
int balance = 10000;
String message = "Your balance is: " + balance;
System.out.println(message);
This code will print:
Your balance is: 10000
3.11 String Concatenation Instructions
1.
In our zoo, we have a certain number of animals, stored in animals, of a certain
species, stored in species.
Use + to make a new String variable called zooDescription. It should hold a String
that looks like:
Our zoo has <animals> <species>s!
For example, if we had 5 animals that were all of the species Masai Giraffe, the
String would say:
Our zoo has 5 Masai Giraffes!

2.
Print out the variable zooDescription!

254
public class Zoo {
public static void main(String[] args){
int animals = 12;
String species = "zebra";
}
}
OUTPUT
Our zoo has 12 zebras!

3.12 final Keyword


Throughout this lesson, we’ve discussed the different ways we can manipulate a
variable; however, what do we do with a variable that should never change its
value?
For example, the year we were born will always stay the same. There’s no way we
can change that information. A value like this in our code should be
unchangeable.
To declare a variable with a value that cannot be manipulated, we need to use
the final keyword. To use the final keyword, prepend final to a variable
declaration like so:
final int yearBorn = 1968;
When we declare a variable using final, the value cannot be changed; any
attempts at doing so will cause an error to occur:
error: cannot assign a value to final variable yearBorn
3.12 final Keyword Instructions
1.
Create an unchangeable double variable called pi and set its value to 3.14.
Print the value of pi.

255
2.
On a new line, try to change the value of pi.
What happens when the program is run?
public class Final {
public static void main(String[] args) {

}
}
OUTPUT
3.14

3.13 Review
What’s the use of having variables if you can’t do anything with them? We’ve now
seen some ways you can operate on variables and compare them. The
possibilities are endless!
We covered:
● Addition and subtraction, using + and -
● Multiplication and division, using * and /
● The modulo operator for finding remainders, %
● Compound assignment operators +=, -=, *=, /=, and %=.
● The order of operations: parentheses -> exponents -> multiplication,
division, modulo -> addition, subtraction
● Greater than, >, and less than, <
● Equal to, ==, and not equal to, !=

256
● Greater than or equal to, >=, and less than or equal to, <=
● equals() for comparing Strings and other objects
● Using + to concatenate Strings
● The final keyword which makes variables unchangeable
Practice some of these concepts here, to make sure you have a solid foundation
for learning more complicated and exciting Java concepts!
3.13 Review Instructions
1.
To review, let’s try building some of the bank account functionality we talked
about throughout the lesson.
First, create a new double variable called updatedBalance, and
store balance with amountToWithdraw subtracted from it.
2.
Now, you’ve decided to split your balance evenly 3 ways and give it to your three
best friends.
Create a double variable called amountForEachFriend that holds your updated
balance divided by 3.
3.
Your friends each want to buy a concert ticket with the money you’ve given them.
The tickets cost 250!
Create a boolean called canPurchaseTicket and set it equal to whether or
not amountForEachFriend is at least enough to purchase a concert ticket.
Then, use System.out.println() to print canPurchaseTicket.

4.
How much money did you give your friends, anyway?
Use + and System.out.println() to print out:
257
I gave each friend <amountForEachFriend>...
with the value of amountForEachFriend where <amountForEachFriend> is.
public class BankAccount {
public static void main(String[] args){
double balance = 1000.75;
double amountToWithdraw = 250;
}
}
OUTPUT
true
I gave each friend 250.25...

______________________________________________
3. Quiz
1. To what value does the following string concatenation evaluate?
"It's " + 5 + "pm"
a) "It's pm"
b) "It's 5pm"
c) Error
d) 11
2. True or False: The value of a variable declared with the final keyword can be
changed after its initial declaration.
a) True
b) False
3. How could we get a result of 10, given the following variable?
double a = 2;
a) a - 12

258
b) a % 10
c) a * 5
d) a / 2
4. What is the best way to tell if the following two Strings are equal?
String username1 = "teracoder";
String username2 = "gigacoder";
a) username1==username2
b) System.out.println(username1)
c) username1.isEqualTo(username2)
d) username1.equals(username2)
5. Which operator can be used to concatenate two Strings?
a) .equals()
b) -
c) +
d) *
6. The expression 5 != 6 will evaluate to what value?
a) true
b) 6
c) false
d) 5
7. After the following code is run, what value will the variable endpoint be
assigned to?
int endpoint = 11 % 3;
a) 2
b) 1
c) 11
d) 2.66
8. What will the following program output?
int num = 12;
num *= 2;
259
num -= 4;
num++;
System.out.println(num);
a) 20
b) 21
c) 9
d) 12
9. What does the following code do?
System.out.println(8 <= 8);

a) Prints true.
b) Prints 8.
c) Prints false.
d) Prints 0.
10. Are there any errors in this Java statement?
int status = 7 < 8;
a) There are no errors.
b) Yes, int should be boolean.
c) Yes, there should be no semicolon.
d) Yes, int should be char.

__________________________________________
Project-3
Math Magic
In this project, you will become a mathemagician and write a small program that
performs a mathematical magic trick! It will involve performing arithmetic operations
on an integer that you choose.
The instructions provided are general guidelines. Upon completion of the project, feel
260
free to explore the code on your own.
If you get stuck during this project or would like to see an experienced developer work
through it, click “Get Unstuck“ to see a project walkthrough video.
Tasks
1.
Create an int variable called myNumber.
Set it equal to any integer other than 0.

2.
We will refer to myNumber as the original number from now on - it might be helpful to
document this.
Write a comment in the program that documents this.

3.
Create an int variable called stepOne.
Set it equal to the original number (myNumber) multiplied by itself.

4.
Create an int variable called stepTwo.
Set it equal to the previous result (stepOne) plus the original number (myNumber).

5.
Create an int variable called stepThree.
Set it equal to the previous result (stepTwo) divided by the original number.

6.

261
Create an int variable called stepFour.
Set it equal to the previous result (stepThree) plus 17.
7.
Create an int variable called stepFive.
Set it equal to the previous result (stepFour) minus the original number.

8.
Create an int variable called stepSix.
Set it equal to the previous result (stepFive) divided by 6.
9.
Print out the value of the last step.
Then, save and run your code!
What number is printed to the console?

10.
Now, go back to your code and change myNumber to any other integer. Run your
program again.
Is the output the same?
It’s math magic!

11.
Great job completing this project! Want to keep challenging yourself?
Recreate this project using only two variables: myNumber and magicNumber. Use your
understanding of compound assignment operators to recreate the above program by
only manipulating magicNumber.

________________________________________________
262
https://www.youtube.com/watch?v=nVrQO2eVU7A&feature=youtu.be

263

You might also like