OOP I(Python+java) (1)
OOP I(Python+java) (1)
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
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
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.
OUTPUT
2023-04-12 05:39:51.465704
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!
8
OUTPUT
12
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
OUTPUT
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')
12
# Import Decimal below:
OUTPUT
0.89
0.3445
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.
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!
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
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
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])
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()
17
r1 = random.randint(0, 1)
print(r1) # Random integer where 0 <= r1 <= 1
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
__________________________________________
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
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.
print(sensors)
OUTPUT
{'living room': 21, 'kitchen': 23, 'bedroom': 20}
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"]}
22
2.3 Invalid Keys
OUTPUT
{'zebras': 8, 'monkeys': 12, 'dinosaurs': 0}
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.
Print user_ids.
OUTPUT
{'teraCoder': 9018293, 'proProgrammer': 119238, 'theLooper': 138475,
'stringQueen': 85739}
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.
oscar_winners = {"Best Picture": "La La Land", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}
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.
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.
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.
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.
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
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"
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"}
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)
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
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")])
33
{"name": "Victor"}.get("nickname")
# returns None
# with default
{"name": "Victor"}.get("nickname", "nickname is not a key")
# returns "nickname is not a key"
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
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}
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"]}
35
room_dict = {key:value for key, value in zip(conference_rooms, capacity)}
print(room_dict)
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
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.
OUTPUT
['Taurus', 'Virgo', 'Capricorn']
['Aries', 'Leo', 'Sagittarius']
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.
39
print(zodiac_elements["energy"])
OUTPUT
Not a Zodiac element
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}
40
>>> building_heights.get('Kilimanjaro', 'No Value')
'No Value'
OUTPUT
10019
10000
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.
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.
OUTPUT
{'health potion': 1, 'cake of the cure': 5, 'green elixir': 20, 'strength sandwich': 25}
65
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
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'])
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]}
45
list(test_scores.values())
However, for most purposes, the dict_values object will act the way you want a
list to act.
OUTPUT
115
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}
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.
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.
OUTPUT
Your past is the Death card.
Your present is the The Fool card.
Your future is the Wheel of Fortune card.
__________________________________________
Concept Review
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"
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"}
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)
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"}
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")])
{"name": "Victor"}.get("nickname")
# returns None
# with default
{"name": "Victor"}.get("nickname", "nickname is not a key")
# returns "nickname is not a key"
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
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
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"]
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'}
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(12 in inventory)
a) False
b) True
c) KeyError
d) "iron spear"
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"
__________________________________________
2.Article
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!
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!.
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!
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.
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,
4. Say you say many money, you write many many many
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,
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.
67
2.
Use the bad_bands_doc.write() method to add the name of a musical group you
dislike to the document bad_bands.
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.
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')
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?
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.
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
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.
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.
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
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.
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
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.
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().
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
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.
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!
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
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!
OUTPUT
Thank you for learning about files in Python with us!
__________________________________________
Concept Review
84
print(file_object)
You might see something like this on the output terminal:
<_io.TextIOWrapper name='somefile.txt' mode='r' encoding='UTF-8'>
# 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
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
"""
After running the above code, companies.csv will contain the following
information:
name,type
Codecademy,Learning
Google,Search
"""
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()
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
TASKS
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().
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.
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.
97
1.
Define an empty class called Facade. We’ll chip away at it soon!
5.3 Instantiation
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.”
class Facade:
pass
facade_1 = Facade()
OUTPUT
99
<class '__main__.Facade'>
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.
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.
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.
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"
class Circle:
pi = 3.14
105
# Add constructor here:
OUTPUT
New circle with diameter: 36
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()
106
working_string = "{} {}".format(fake_dict1.fake_key, fake_dict2.fake_key)
print(working_string)
# prints "This works! This too!"
class Store:
pass
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!")
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.
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
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.
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__']
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
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
116
2.
Print out medium_pizza, teaching_table, and round_room.
class Circle:
pi = 3.14
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.
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
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
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")
121
# Class Instantiation
ferrari = Car()
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()
122
self.voice = voice
dog = Animal('Woof')
print(dog.voice) # Output: Woof
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
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
__________________________________________
5. Quiz
def __repr__(self):
125
return "Hiya {}!".format(self.name)
devorah = User("Devorah")
print(devorah)
a) Hiya devorah!
b) devorah
c) Devorah
d) Hiya Devorah!
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
__________________________________________
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
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().
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
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
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:
ANS:
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.
ANS:
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
ANS:
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
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".
ANS:
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.
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:
__________________________________________
143
4.Article
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
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:
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:
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:
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
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:
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:
154
))
# should print 6
ANS
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:
ANS
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:
ANS
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:
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
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!
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:
ANS
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:
ANS
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:
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.
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}
167
"Tywin"]}))
# should print {"S": 7}
ANS
__________________________________________
7.Article
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 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!
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
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
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
robot_1 = DriveBot()
# Use the methods here!
# print(robot_1.motor_speed)
# print(robot_1.direction)
# print(robot_1.sensor_range)
ANS
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 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
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)
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!
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
178
5. Identifying Robots
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
ANS
180
self.motor_speed = motor_speed
self.direction = direction
self.sensor_range = sensor_range
DriveBot.robot_count += 1
self.id = DriveBot.robot_count
__________________________________________
8.Article
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!
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!
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”.
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.
}
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!
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!");
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!
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) {
}
}
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) {
199
System.out.println("Java statements end with a semicolon.");
}
}
OUTPUT
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.
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
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 {
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) {
______
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
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.
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 {
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 {
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
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
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
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;
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){
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";
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;
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
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;
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
// 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.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
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 (%=)
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;
247
// System.out.println(expression1);
int expression3 = 5 * 4 % 3 - 2 + 1;
// System.out.println(expression3);
}
}
OUTPUT
-6
3
1
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
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;
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;
}
}
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
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!
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