[go: up one dir, main page]

0% found this document useful (0 votes)
957 views246 pages

Python 2 Lessons

This document covers Python syntax and programming concepts over several chapters. It introduces basic Python syntax like variables, strings, numbers, and arithmetic. It also covers programming concepts like conditionals, functions, modules and built-in functions. The document provides examples and exercises to explain each topic.

Uploaded by

Carlos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
957 views246 pages

Python 2 Lessons

This document covers Python syntax and programming concepts over several chapters. It introduces basic Python syntax like variables, strings, numbers, and arithmetic. It also covers programming concepts like conditionals, functions, modules and built-in functions. The document provides examples and exercises to explain each topic.

Uploaded by

Carlos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 246

Contents

1 PYTHON SINTAX...................................................................................................9
1.1 Hello World!.......................................................................................................9
1.2 Print Statements................................................................................................10
1.3 Strings...............................................................................................................10
1.4 Variables...........................................................................................................12
1.5 Arithmetic.........................................................................................................12
1.6 Updating variables............................................................................................12
1.7 Comments.........................................................................................................14
1.8 Numbers............................................................................................................14
1.9 Two Types of Division.....................................................................................14
1.10 Multi-line Strings..........................................................................................15
1.11 Booleans........................................................................................................16
1.12 ValueError.....................................................................................................16
1.13 Review...........................................................................................................17
2 String & Console output..........................................................................................19
2.1 Strings...............................................................................................................19
2.2 Escaping characters...........................................................................................19
2.3 Access by Index................................................................................................20
2.4 String methods..................................................................................................20
2.4.1 lower().......................................................................................................21
2.4.2 upper().......................................................................................................21
2.4.3 str()............................................................................................................21
2.5 Dot Notation.....................................................................................................22
2.6 Printing Strings.................................................................................................22
2.7 Printing Variables.............................................................................................22
2.8 String Concatenation.........................................................................................23
2.9 Explicit String Conversion................................................................................23
2.10 String Formatting with %, Part 1..................................................................24
2.11 String Formatting with %, Part 2..................................................................24
2.12 And Now, For Something Completely Familiar...........................................25
2.13 DATE AND TIME........................................................................................26
2.13.1 The datetime Library.................................................................................26
2.13.2 Getting the Current Date and Time...........................................................26
2.13.3 Extracting Information..............................................................................26
2.13.4 Hot Date.....................................................................................................27
2.13.5 Pretty Time................................................................................................28
2.13.6 Grand Finale..............................................................................................28
3 CONDITIONALS & CONTROL FLOW...............................................................30
3.1 Go With the Flow.............................................................................................30
3.2 Compare Closely!.............................................................................................31
3.3 Compare... Closelier!........................................................................................32
3.4 How the Tables Have Turned...........................................................................33
3.5 To Be and/or Not to Be.....................................................................................33
3.6 And....................................................................................................................34
3.7 Or......................................................................................................................35
3.8 Not....................................................................................................................36
3.9 This and That (or This, But Not That!).............................................................37
3.10 Mix 'n' Match................................................................................................38
3.11 Conditional Statement Syntax.......................................................................38
3.12 If You're Having............................................................................................39
3.13 Else Problems, I Feel Bad for You, Son.......................................................40
3.14 I Got 99 Problems, But a Switch Ain't One..................................................41
3.15 The Big If......................................................................................................42
3.16 PYGLATIN...................................................................................................43
4 FUNCTIONS...........................................................................................................50
4.1 What Good are Functions?...............................................................................50
4.2 Function Junction..............................................................................................50
4.3 Call and Response.............................................................................................51
4.4 Parameters and Arguments...............................................................................51
4.5 Functions Calling Functions.............................................................................52
4.6 Practice Makes Perfect......................................................................................53
4.7 I Know Kung Fu...............................................................................................54
4.8 Generic Imports................................................................................................54
4.9 Function Imports...............................................................................................55
4.10 Universal Imports..........................................................................................56
4.11 Here Be Dragons...........................................................................................56
4.12 On Beyond Strings........................................................................................57
4.13 max().............................................................................................................58
4.14 min()..............................................................................................................58
4.15 abs()...............................................................................................................58
4.16 type().............................................................................................................59
4.17 Review: Functions.........................................................................................59
4.18 Review: Modules..........................................................................................60
4.19 Review: Built-In Functions...........................................................................61
4.20 TAKING A VACATION..............................................................................61
4.20.1 Before We Begin.......................................................................................61
4.20.2 Planning Your Trip....................................................................................62
4.20.3 Getting There.............................................................................................62
4.20.4 Transportation............................................................................................63
4.20.5 Pull it Together..........................................................................................64
4.20.6 Plan Your Trip!..........................................................................................66
5 PYTHON LISTS AND DICTIONARIES...............................................................68
5.1 Introduction to Lists..........................................................................................68
5.2 Access by Index................................................................................................68
5.3 New Neighbors.................................................................................................69
5.4 Late Arrivals & List Length..............................................................................70
5.5 List Slicing........................................................................................................71
5.6 Slicing Lists and Strings...................................................................................72
5.7 Maintaining Order.............................................................................................72
5.8 For One and All................................................................................................73
5.9 More with 'for'...................................................................................................74
5.10 This Next Part is Key....................................................................................75
5.11 New Entries...................................................................................................76
5.12 Changing Your Mind....................................................................................77
5.13 Remove a Few Things...................................................................................78
5.14 It's Dangerous to Go Alone! Take This........................................................78
5.15 A DAY AT THE SUPERMARKET.............................................................80
5.15.1 BeFOR We Begin......................................................................................80
5.15.2 This is KEY!..............................................................................................80
5.15.3 Control Flow and Looping........................................................................82
5.15.4 Lists + Functions.......................................................................................83
5.15.5 String Looping...........................................................................................84
5.15.6 Your Own Store!.......................................................................................85
5.15.7 Investing in Stock......................................................................................86
5.15.8 Keeping Track of the Produce...................................................................86
5.15.9 Something of Value...................................................................................88
5.15.10 Shopping at the Market..........................................................................89
5.15.11 Making a Purchase.................................................................................89
5.15.12 Stocking Out..........................................................................................90
5.15.13 Let's Check Out!....................................................................................91
6 STUDENT BECOMES THE TEACHER...............................................................92
6.1 Lesson Number One.........................................................................................92
6.2 What's the Score?..............................................................................................93
6.3 Put It Together..................................................................................................93
6.4 For the Record..................................................................................................94
6.5 It's Okay to be Average.....................................................................................95
6.6 Just Weight and See..........................................................................................96
6.7 Sending a Letter................................................................................................97
6.8 Part of the Whole..............................................................................................98
6.9 How is Everybody Doing?................................................................................99
7 LISTS AND FUNCTIONS...................................................................................102
7.1 List accessing..................................................................................................102
7.2 List element modification...............................................................................102
7.3 Appending to a list..........................................................................................103
7.4 Removing elements from lists........................................................................103
7.5 Changing the functionality of a function........................................................104
7.6 More than one argument.................................................................................104
7.7 Strings in functions.........................................................................................105
7.8 Passing a list to a function..............................................................................105
7.9 Using an element from a list in a function......................................................106
7.10 Modifying an element of a list in a function...............................................106
7.11 List manipulation in functions....................................................................107
7.12 Printing out a list item by item in a function...............................................108
7.13 Modifying each element in a list in a function............................................109
7.14 Passing a range into a function....................................................................109
7.15 Iterating over a list in a function.................................................................110
7.16 Using two lists as two arguments in a function...........................................113
7.17 Using a list of lists in a function..................................................................113
7.18 BATTLESHIP!...........................................................................................115
7.18.1 Getting Our Feet Wet..............................................................................115
7.18.2 Make a List..............................................................................................115
7.18.3 Check it Twice.........................................................................................116
7.18.4 Custom Print............................................................................................116
7.18.5 Printing Pretty..........................................................................................117
7.18.6 Hide.........................................................................................................118
7.18.7 .and Seek!................................................................................................119
7.18.8 It's Not Cheating—It's Debugging!.........................................................121
Instructions...........................................................................................................121
7.18.9 You win!..................................................................................................122
7.18.10 Danger, Will Robinson!!......................................................................122
7.18.11 Bad Aim...............................................................................................124
Instructions...........................................................................................................125
7.18.12 Not Again!...........................................................................................125
7.18.13 Test Run...............................................................................................126
7.18.14 Play It, Sam..........................................................................................127
7.18.15 Game Over...........................................................................................128
7.18.16 A Real Win..........................................................................................131
7.18.17 To Your Battle Stations!......................................................................133
7.18.18 Extra Credit..........................................................................................134
8 LOOPS..................................................................................................................135
8.1 While you're here............................................................................................135
8.2 Condition........................................................................................................136
8.3 While you're at it.............................................................................................136
8.4 Simple errors...................................................................................................137
8.5 Infinite loops...................................................................................................137
8.6 Break...............................................................................................................138
8.7 While / else.....................................................................................................139
8.8 Your own while / else.....................................................................................140
8.9 For your health................................................................................................141
8.10 For your hobbies.........................................................................................142
8.11 For your strings...........................................................................................143
8.12 For your A...................................................................................................143
8.13 For your lists...............................................................................................144
8.14 Looping over a dictionary...........................................................................145
8.15 Counting as you go......................................................................................146
8.16 Multiple lists................................................................................................147
8.17 For / else......................................................................................................148
8.18 Change it up................................................................................................149
8.19 PRACTICE MAKES PERFECT................................................................150
8.19.1 Practice! Practice Practice!......................................................................150
8.19.2 is_even.....................................................................................................150
8.19.3 is_int........................................................................................................151
8.19.4 digit_sum.................................................................................................151
8.20 is_prime.......................................................................................................154
8.21 reverse.........................................................................................................155
8.22 anti_vowel...................................................................................................156
8.23 scrabble_score.............................................................................................156
8.24 censor..........................................................................................................157
8.25 count............................................................................................................159
8.26 purify...........................................................................................................160
8.27 product.........................................................................................................161
8.28 remove_duplicates.......................................................................................161
8.29 median.........................................................................................................162
9 EXAM STATISTICS............................................................................................166
10 ADVANCED TOPICS IN PYTHON...................................................................175
10.1 Iterators for Dictionaries.............................................................................175
10.2 The 'in' Operator..........................................................................................176
10.3 Building Lists..............................................................................................177
10.4 List Comprehension Syntax........................................................................178
10.5 Now You Try!.............................................................................................179
10.6 List Slicing Syntax......................................................................................179
10.7 Omitting Indices..........................................................................................180
10.8 Reversing a List...........................................................................................181
10.9 Stride Length...............................................................................................182
10.10 Practice Makes Perfect................................................................................182
10.10.1 Anonymous Functions.........................................................................183
10.10.2 Lambda Syntax....................................................................................184
10.10.3 Try It!...................................................................................................184
10.10.4 Iterating Over Dictionaries..................................................................185
10.10.5 Comprehending Comprehensions........................................................186
10.10.6 List Slicing...........................................................................................186
10.10.7 Lambda Expressions............................................................................187
11 INTRODUCTION TO BITWISE OPERATORS.................................................188
11.1.1 Just a Little BIT.......................................................................................188
11.2 The Base 2 Number System........................................................................189
11.3 I Can Count to 1100!...................................................................................191
11.4 The bin() Function.......................................................................................192
11.5 int()'s Second Parameter..............................................................................193
11.6 Slide to the Left! Slide to the Right!...........................................................194
11.7 A BIT of This AND That............................................................................195
11.8 A BIT of This OR That...............................................................................196
11.9 This XOR That?..........................................................................................196
11.10 See? This is NOT That Hard!......................................................................197
11.11 The Man Behind the Bit Mask....................................................................198
11.12 Turn It On....................................................................................................199
11.13 Just Flip Out................................................................................................200
11.14 Slip and Slide..............................................................................................201
12 INTRODUCTION TO CLASSES........................................................................202
12.1 Class Syntax................................................................................................203
12.2 Classier Classes...........................................................................................204
12.3 Let's Not Get Too Selfish............................................................................205
12.4 Instantiating Your First Object....................................................................206
12.5 More on __init__() and self.........................................................................207
12.6 Class Scope.................................................................................................208
12.7 A Methodical Approach..............................................................................209
12.8 They're Multiplying!...................................................................................210
12.9 It's Not All Animals and Fruit.....................................................................212
Concept Review...................................................................................................213
12.10 Warning: Here Be Dragons.........................................................................213
12.10.1 Inheritance Syntax...............................................................................214
12.10.2 Override!..............................................................................................215
12.10.3 This Looks Like a Job For...................................................................217
12.10.4 Class Basics.........................................................................................219
12.10.5 Class It Up...........................................................................................219
12.10.6 Instantiate an Object............................................................................220
12.10.7 Inheritance...........................................................................................221
12.11 CLASSES....................................................................................................222
12.11.1 Class basics..........................................................................................222
12.11.2 Create an instance of a class................................................................223
12.11.3 Class member variables.......................................................................223
Instructions...........................................................................................................223
12.12 Calling class member variables...................................................................223
Instructions...........................................................................................................224
12.13 Initializing a class........................................................................................224
12.14 Referring to member variables....................................................................225
12.15 Creating class methods................................................................................226
Concept Review...................................................................................................227
12.16 Modifying member variables......................................................................228
12.17 Inheritance...................................................................................................229
12.18 Overriding methods.....................................................................................231
12.19 Building useful classes................................................................................232
Concept Review...................................................................................................233
13 FILE INPUT/OUTPUT.........................................................................................234
13.1 See It to Believe It.......................................................................................234
13.2 The open() Function....................................................................................234
13.3 Writing........................................................................................................235
13.4 Reading Between the Lines.........................................................................237
13.5 PSA: Buffering Data...................................................................................238
13.6 The 'with' and 'as' Keywords.......................................................................239
Instructions............................................................................................................240
13.7 Case Closed?...............................................................................................240
1 PYTHON SINTAX
1.1 Hello World!
If programming is the act of teaching a computer to have a
conversation with a user, it would be most useful to first teach the
computer how to speak. In Python, this is accomplished with
the print statement.
print "Hello, world!"
print "Water—there is not a drop of water there! Were Niagara but a cataract
of sand, would you travel your thousand miles to see it?"
A print statement is the easiest way to get your Python program to
communicate with you. Being able to command this communication
will be one of the most valuable tools in your programming toolbox.
Instructions

1.

Using a print statement, output a message of your choosing to the


terminal.
1.2 Print Statements
There are two different Python versions. Both Python 2 and Python 3
are used throughout the globe. The most significant difference
between the two is how you write a print statement. In Python
3, print has parentheses.
print("Hello World!")
print("Deep into distant woodlands winds a mazy way, reaching to overlapping
spurs of mountains bathed in their hill-side blue.")
In this course we will be using Python 2. If you go on to write Python 3
it will be useful to note this key difference.
Instructions

1.

Print something using Python 3’s syntax.


1.3 Strings
When printing things in Python, we are supplying a text block that we
want to be printed. Text in Python is considered a specific type of data
called a string. A string, so named because they’re a series of letters,
numbers, or symbols connected in order — as if threaded together by
string. Strings can be defined in different ways:
print "This is a good string"
print 'You can use single quotes or double quotes for a string'
Above we printed two things that are strings and then attempted to
print two things that are not strings. While double-quotes (“) and
single-quotes (‘) are both acceptable ways to define a string, a string
needs to be opened and closed by the same type of quote mark.

We can combine multiple strings using +, like so:


print "This is " + "a good string"
This code will print out “This is a good string”.
Instructions

1.

Try adding your name to the print statement with the + operator so


that this Python program prints “Hello [your_name]”
Handling Errors

As we get more familiar with the Python programming language, we


run into errors and exceptions. These are complaints that Python
makes when it doesn’t understand what you want it to do. Everyone
runs into these issues, so it is a good habit to read and understand
them. Here are some common errors that we might run into when
printing strings:
print "Mismatched quotes will cause a SyntaxError'
print Without quotes will cause a NameError
If the quotes are mismatched Python will notice this and inform you
that your code has an error in its syntax because the line ended (called
an EOL) before the double-quote that was supposed to close the string
appeared. The program will abruptly stop running with the following
message:
SyntaxError: EOL while scanning a string literal
This means that a string wasn’t closed, or wasn’t closed with the same
quote-character that started it.

Another issue you might run into is attempting to create a string


without quotes at all. Python treats words not in quotes as commands,
like the print statement. If it fails to recognize these words as defined
(in Python or by your program elsewhere) Python will complain the
code has a NameError. This means that Python found what it thinks is a
command, but doesn’t know what it means because it’s not defined
anywhere.
Instructions

1.

We’ve written two print statements that will raise errors. One has


mismatched quotes and the other has no quotes at all.

Fix the two print statements to successfully debug the program!


1.4 Variables
In Python, and when programming in general, we need to build systems for dealing with
data that changes over time. That data could be the location of a plane, or the time of
day, or the television show you’re currently watching. The only important thing is that it
may be different at different times. Python uses variables to define things that are
subject to change.
greeting_message = "Welcome to Codecademy!"
current_excercise = 5
In the above example, we defined a variable called greeting_message and set it equal to
the string “Welcome to Codecademy!”. It also defined a variable
called current_exercise and set it equal to the number 5.
1.5 Arithmetic
One thing computers are capable of doing exceptionally well is performing arithmetic.
Addition, subtraction, multiplication, division, and other numeric calculations are easy
to do in most programming languages, and Python is no exception. Some examples:
mirthful_addition = 12381 + 91817
amazing_subtraction = 981 - 312
trippy_multiplication = 38 * 902
happy_division = 540 / 45
sassy_combinations = 129 * 1345 + 120 / 6 - 12
Above are a number of arithmetic operations, each assigned to a variable. The variable
will hold the final result of each operation. Combinations of arithmetical operators
follow the usual order of operations.
Python also offers a companion to division called the modulo operator. The modulo
operator is indicated by % and returns the remainder after division is performed.
is_this_number_odd = 15 % 2
is_this_number_divisible_by_seven = 133 % 7
In the above code block, we use the modulo operator to find the remainder of 15 divided
by 2. Since 15 is an odd number the remainder is 1.
We also check the remainder of 133 / 7. Since 133 divided by 7 has no remainder, 133%
7 evaluates to 0.
1.6 Updating variables
Changing the contents of a variable is one of the essential operations. As the flow of a
program progresses, data should be updated to reflect changes that have happened.
fish_in_clarks_pond = 50
print "Catching fish"

number_of_fish_caught = 10
fish_in_clarks_pond = fish_in_clarks_pond - number_of_fish_caught
In the above example, we start with 50 fish in a local pond. After catching 10 fish, we
update the number of fish in the pond to be the original number of fish in the pond
minus the number of fish caught. At the end of this code block, the
variable fish_in_clarks_pond is equal to 40.
Updating a variable by adding or subtracting a number to its original value is such a
common task that it has its own shorthand to make it faster and easier to read.
money_in_wallet = 40
sandwich_price = 7.50
sales_tax = .08 * sandwich_price

sandwich_price += sales_tax
money_in_wallet -= sandwich_price
In the above example, we use the price of a sandwich to calculate sales tax. After
calculating the tax we add it to the total price of the sandwich. Finally, we complete the
transaction by reducing our money_in_wallet by the cost of the sandwich (with tax).

january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50


annual_rainfall = january_to_june_rainfall

july_rainfall = 1.05
annual_rainfall += july_rainfall

august_rainfall = 4.91
annual_rainfall += august_rainfall

september_rainfall = 5.16
october_rainfall = 7.20
november_rainfall = 5.06
december_rainfall = 4.06
september_to_december_rainfall=5.16+7.20+5.06+4.06
annual_rainfall+=september_to_december_rainfall
1.7 Comments
Most of the time, code should be written in such a way that it is easy to understand on
its own. However, if you want to include a piece of information to explain a part of your
code, you can use the # sign. A line of text preceded by a # is called a comment. The
machine does not run this code — it is only for humans to read. When you look back at
your code later, comments may help you figure out what it was intended to do.
# this variable counts how many rows of the spreadsheet we have:
row_count = 13
1.8 Numbers
Variables can also hold numeric values. The simplest kind of number in Python is the
integer, which is a whole number with no decimal point:
int1 = 1
int2 = 10
int3 = -5
A number with a decimal point is called a float. You can define floats with numbers
after the decimal point or by just including a decimal point at the end:
float1 = 1.0
float2 = 10.
float3 = -5.5
You can also define a float using scientific notation, with e indicating the power of 10:
# this evaluates to 150:
float4 = 1.5e2
Exercise

cucumbers = 3
price_per_cucumber = 3.25

total_cost = cucumbers * price_per_cucumber
print total_cost

1.9 Two Types of Division


In Python 2, when we divide two integers, we get an integer as a result. When
the quotient is a whole number, this works fine:

quotient = 6/2
# the value of quotient is now 3, which makes sense
However, if the numbers do not divide evenly, the result of the division is
truncated into an integer. In other words, the quotient is rounded down to a
whole number. This can be surprising when you expect to receive a decimal and
you receive a rounded-down integer:

quotient = 7/2
# the value of quotient is 3, even though the result of the division here is
3.5
To yield a float as the result instead, programmers often change either the
numerator or the denominator (or both) to be a float:

quotient1 = 7./2
# the value of quotient1 is 3.5
quotient2 = 7/2.
# the value of quotient2 is 3.5
quotient3 = 7./2.
# the value of quotient3 is 3.5
An alternative way is to use the float() method:

quotient1 = float(7)/2
# the value of quotient1 is 3.5
Exercise

cucumbers=100
num_people=6
whole_cucumbers_per_person=cucumbers/num_people
print "whole_cucumbers_per_person"
float_cucumbers_per_person=float(cucumbers)/num_people

1.10 Multi-line Strings


We have seen how to define a string with single quotes and with double quotes.
If we want a string to span multiple lines, we can also use triple quotes:

address_string = """136 Whowho Rd


Apt 7
Whosville, WZ 44494"""
This address spans multiple lines, and is still contained in one
variable, address_string.

When a string like this is not assigned to a variable, it works as a multi-line


comment. This can be helpful as your code gets more complex:

"""The following piece of code does the following steps:


takes in some input
does An Important Calculation
returns the modified input and a string that says "Success!" or "Failure..."
"""
... a complicated piece of code here...
Task:

haiku="""The old pond,
A frog jumps in:
Plop!"""

1.11 Booleans
Sometimes we have a need for variables that are either true or false. This
datatype, which can only ever take one of two values, is called a boolean. In
Python, we define booleans using the keywords True and False:

a = True
b = False
A boolean is actually a special case of an integer. A value of True corresponds to
an integer value of 1, and will behave the same. A value of False corresponds to
an integer value of 0.

Instructions
1.
Someone has introduced themselves to you using comments in script.py.
Read the comments and then create a variable called age_is_12 and set it to
be True or False depending on if this person’s age is 12.
Checkpoint 2 Passed
Stuck? Get a hint
2.
Create a variable called name_is_maria and set it to be True or False depending on if
this person’s name is Maria.

 Hi! I'm Maria and I live in script.py.
# I'm an expert Python coder.
# I'm 21 years old and I plan to program cool stuff forever.
age_is_12= False
name_is_maria= True

1.12 ValueError
Python automatically assigns a variable the appropriate datatype based
on the value it is given. A variable with the value  7  is an
integer,  7.  is a float,  "7"  is a string. Sometimes we will want to
convert variables to different datatypes. For example, if we wanted to
print out an integer as part of a string, we would want to convert that
integer to a string first. We can do that using str():
age = 13
print "I am " + str(age) + " years old!"
This would print:
>>> "I am 13 years old!"
Similarly, if we have a string like "7" and we want to perform arithmetic
operations on it, we must convert it to a numeric datatype. We can do
this using int():
number1 = "100"
number2 = "10"

string_addition = number1 + number2


#string_addition now has a value of "10010"

int_addition = int(number1) + int(number2)


#int_addition has a value of 110
If you use int() on a floating point number, it will round the number
down. To preserve the decimal, you can use float():
string_num = "7.5"
print int(string_num)
print float(string_num)
>>> 7
>>> 7.5Instructions
1.

Create a variable called product that contains the result of multiplying


the float value of float_1 and float_2.
2.

Create a string called big_string that says:


The product was X
with the value of product where the X is.

1.13 Review
Great! So far we’ve looked at:

 Print statements

 How to create, modify, and use variables


 Arithmetic operations like addition, subtraction, division, and
multiplication

 How to use comments to make your code easy to understand

 Different data types, including strings, ints, floats, and booleans

 Converting between data types

Instructions

1.

Let’s apply all of the concepts you have learned one more time!

Create a variable called skill_completed and set it equal to the


string "Python Syntax".
2.

Create a variable called exercises_completed and set it equal to 13. Create


another variable called points_per_exercise and set it equal to 5.
3.

Create a variable called point_total and set it equal to 100.


4.

Update point_total to be what it was before plus the result of


multiplying exercises_completed and points_per_exercise.
Stuck? Get a hint

5.

Add a comment above your declaration of points_per_exercise that says:


The amount of points for each exercise may change, because points don't exist
yet
6.

Print a string to the console that says:


I got X points!
with the value of point_total where X is.

skill_completed = "Python Syntax"
exercises_completed = 13
#The amount of points for each exercise may change, because points don't 
exist yet
points_per_exercise = 5
point_total = 100
point_total += exercises_completed*points_per_exercise

print("I got "+str(point_total)+" points!")

2 String & Console output


2.1 Strings
Another useful data type is the string. A string can contain letters, numbers,
and symbols.

name = "Ryan"
age = "19"
food = "cheese"

1. In the above example, we create a variable name and set it to the string


value "Ryan".
2. We also set age to "19" and food to "cheese".

Strings need to be within quotes.


2.2 Escaping characters
There are some characters that cause problems. For example:

'There's a snake in my boot!'


This code breaks because Python thinks the apostrophe in 'There's' ends the
string. We can use the backslash to fix the problem, like this:

'There\'s a snake in my boot!'

2.3 Access by Index


Great work!

Each character in a string is assigned a number. This number is called the index.


Check out the diagram in the editor.

c = "cats"[0]
n = "Ryan"[3]

1. In the above example, we create a new variable called c and set it to "c",


the character at index zero of the string "cats".
2. Next, we create a new variable called n and set it to "n", the character at
index three of the string "Ryan".

Notice that in the first “cat” example we are calling the 0th letter of “cat” and
getting “c” in return. This is because in Python indices begin counting at 0.
Therefore, in the string “cats”, the first letter, “c”, is at the 0th index and the last
letter, “s”, is at the 3rd index.

2.4 String methods


Great work! Now that we know how to store strings, let’s see how we can
change them using string methods.

String methods let you perform specific tasks for strings.

We’ll focus on four string methods:

1. len()
2. lower()
3. upper()
4. str()
Let’s start with len(), which gets the length (the number of characters) of a
string!

On line 1, create a variable named parrot and set it to the string "Norwegian Blue".


On line 2, type len(parrot) after the word print, like so: print len(parrot). The output will
be the number of characters in "Norwegian Blue"!

parrot="Norwegian Blue"
print len(parrot)

2.4.1 lower()
Well done!

You can use the lower() method to get rid of all the capitalization in your
strings. You call lower() like so:

"Ryan".lower()
which will return "ryan".

1.
Call lower() on parrot (after print) on line 3 in the editor.

parrot ="Norwegian Blue"

print parrot.lower()

2.4.2 upper()
Now your string is 100% lower case! A similar method exists to make a string
completely upper case.

Call upper() on parrot (after print on line 3) in order to


capitalize all the characters in the string!

parrot = "norwegian blue"
print parrot.upper()

2.4.3 str()
Now let’s look at str(), which is a little less straightforward. The str() method
turns non-strings into strings! For example:

str(2)
would turn 2 into "2".

2.5 Dot Notation


Let’s take a closer look at why you use len(string) and str(object), but dot
notation (such as "String".upper()) for the rest.

lion = "roar"
len(lion)
lion.upper()
Methods that use dot notation only work with strings.

On the other hand, len() and str() can work on other data types.

On line 3, call the len() function with the argument ministry.


On line 4, invoke the ministry‘s .upper() function.

ministry = "The Ministry of Silly Walks"

print len(ministry)
print ministry.upper()

2.6 Printing Strings


The area where we’ve been writing our code is called the editor.

The console (the window to the right of the editor) is where the results of your
code is shown.

print simply displays your code in the console.

2.7 Printing Variables


Great! Now that we’ve printed strings, let’s print variables

Declare a variable called the_machine_goes and assign it the string value "Ping!" on


line 5.
Go ahead and print the_machine_goes in line 6.
"""Assign the string "Ping!" to
the variable the_machine_goes on
line 5, then print it out on line 6!"""

the_machine_goes= "Ping!"
print the_machine_goes

2.8 String Concatenation


You know about strings, and you know about arithmetic operators. Now let’s
combine the two!

print "Life " + "of " + "Brian"


This will print out the phrase Life of Brian.

The + operator between strings will ‘add’ them together, one after the other.
Notice that there are spaces inside the quotation marks after Life and of so that
we can make the combined string look like 3 words.

Combining strings together like this is called concatenation. Let’s try


concatenating a few strings together now!

1.
Let’s give it a try. Print the concatenated strings "Spam ", "and ", "eggs" on line 3, just
like the example above.
Make sure you include the spaces at the end of "Spam " and "and ".

# Print the concatenation of "Spam and eggs" on line 3!

print "Spam " + "and " + "eggs"

2.9 Explicit String Conversion


Sometimes you need to combine a string with something that isn’t a string. In
order to do that, you have to convert the non-string into a string.

print "I have " + str(2) + " coconuts!"


This will print I have 2 coconuts!.

The str() method converts non-strings into strings. In the above example, you


convert the number 2 into a string and then you concatenate the strings
together just like in the previous exercise.

Now try it yourself!


1.
Run the code as-is. You get an error!
Use str() to turn 3.14 into a string. Then run the code again.

# Turn 3.14 into a string on line 3!

print "The value of pi is around " + str(3.14)

2.10 String Formatting with %, Part 1


When you want to print a variable with a string, there is a better
method than concatenating strings together.
name = "Mike"
print "Hello %s" % (name)
The % operator after the string is used to combine a string with
variables. The % operator will replace the %s in the string with the string
variable that comes after it.

If you’d like to print a variable that is an integer, you can “pad” it with
zeros using %02d. The 0 means “pad with zeros”, the 2 means to pad to 2
characters wide, and the d means the number is a signed integer (can
be positive or negative).
day = 6
print "03 - %s - 2019" % (day)
# 03 - 6 - 2019
print "03 - %02d - 2019" % (day)
# 03 - 06 - 2019
Instructions

1.

Take a look at the code in the editor. What do you think it’ll do? Click
Run when you think you know.

2.11 String Formatting with %, Part 2


Remember, we used the % operator to replace the %s placeholders with
the variables in parentheses.
name = "Mike"
print "Hello %s" % (name)
You need the same number of %s terms in a string as the number of
variables in parentheses:
print "The %s who %s %s!" % ("Knights", "say", "Ni")
# This will print "The Knights who say Ni!"
Instructions

1.

Now it’s your turn! We have ___ in the code to show you what you need
to change!

1. Inside the string, replace the three ___ with %s.

2. After the string but before the three variables, replace the
final ___ with a %.

3. Hit Run.
4. name = "Alex"
5. quest = "Teaching Python"
6. color = "Blue"
7.
8. print "Ah, so your name is %s, your quest is %s, " \
9. "and your favorite color is %s." %(name, quest, color)
2.12 And Now, For Something Completely Familiar
Great job! You’ve learned a lot in this unit, including:

Three ways to create strings


'Alpha'
"Bravo"
str(3)
String methods
len("Charlie")
"Delta".upper()
"Echo".lower()
Printing a string
print "Foxtrot"
Advanced printing techniques
g = "Golf"
h = "Hotel"
print "%s, %s" % (g, h)
Instructions

1.

Let’s wrap it all up!


1. On line 3, create the variable my_string and set it to any string
you’d like.

2. On line 4, use len() to print the length of my_string.

3. On line 5, print the .upper() case version of my_string.

2.13 DATE AND TIME


2.13.1 The datetime Library
A lot of times you want to keep track of when something happened.
We can do so in Python using datetime.

Here we’ll use datetime to print the date and time in a nice format.
Instructions

1.

Click Run to continue.

2.13.2 Getting the Current Date and Time


We can use a function called datetime.now() to retrieve the current date
and time.
from datetime import datetime

print datetime.now()
The first line imports the datetime library so that we can use it.

The second line will print out the current date and time.

Instructions

1.

Create a variable called now and store the result of datetime.now() in it.

Then, print the value of now.


from datetime import datetime
now= datetime.now()
print now
2.13.3 Extracting Information
Notice how the output looks like 2013-11-25 23:45:14.317454. What if you
don’t want the entire date and time?
from datetime import datetime
now = datetime.now()

current_year = now.year
current_month = now.month
current_day = now.day
You already have the first two lines.

In the third line, we take the year (and only the year) from the
variable now and store it in current_year.

In the fourth and fifth lines, we store the month and day from now.
Instructions

1.

On a new line, print now.year. Make sure you do it after setting


the now variable!

Then, print out now.month.

Finally, print out now.day.

from datetime import datetime
now= datetime.now()
print now
current_year=now.year
current_month=now.month
current_day=now.day
print current_year
print current_month
print current_day

2.13.4 Hot Date


What if we want to print today’s date in the following
format? mm/dd/yyyy. Let’s use string substitution again!
from datetime import datetime
now = datetime.now()

print '%02d-%02d-%04d' % (now.month, now.day, now.year)


# will print the current date as mm-dd-yyyy
Remember that the standalone % operator after the string will fill
the %02d and %04d placeholders in the string on the left with the numbers
and strings in the parentheses on the right.

%02d pads the month and day numbers with zeros to two places,
and %04d pads the year to four places. This is one way dates are
commonly displayed.
Instructions

1.

Print the current date in the form of mm/dd/yyyy.

Change the string used above so that it uses a / character in between


the %02d and %04d placeholders instead of a - character.

from datetime import datetime
now = datetime.now()
print "%02d/%02d/%04d" % (now.month, now.day, now.year)

2.13.5 Pretty Time


Nice work! Let’s do the same for the hour, minute, and second.
from datetime import datetime
now = datetime.now()

print now.hour
print now.minute
print now.second
In the above example, we just printed the current hour, then the
current minute, then the current second.

We can again use the variable now to print the time.


Instructions

1.

Similar to the last exercise, print the current time in the pretty form
of hh:mm:ss.

1. Change the string that you are printing so that you have
a : character in between the %02d placeholders.
2. Change the three things that you are printing from month, day,
and year to now.hour, now.minute, and now.second.
3. from datetime import datetime
4. now = datetime.now()
5.
6. print '%02d:%02d:%04d' % (now.hour, now.minute, now.second)

2.13.6 Grand Finale


We’ve managed to print the date and time separately in a very pretty
fashion. Let’s combine the two!
from datetime import datetime
now = datetime.now()

print '%02d/%02d/%04d' % (now.month, now.day, now.year)


print '%02d:%02d:%02d' % (now.hour, now.minute, now.second)
The example above will print out the date, then on a separate line it will
print the time.

Let’s print them all on the same line in a single print statement!


Instructions

1.

Print the date and time together in the form: mm/dd/yyyy hh:mm:ss.

To start, change the format string to the left of the % operator.

1. Ensure that it has five %02d and one %04d placeholder.

2. Put slashes and colons and a space between the placeholders so


that they fit the format above.Then, change the variables in the
parentheses to the right of the % operator.

3. Place the variables so that now.month, now.day, now.year are


before now.hour, now.minute, now.second. Make sure that there is
a ( before the six placeholders and a ) after them.
4. from datetime import datetime
5. now = datetime.now()
6.
7. print '%02d/%02d/%04d %02d:%02d:%02d' % (now.year, now.month, no
w.day, now.hour, now.minute, now.second)
3 CONDITIONALS & CONTROL FLOW
3.1 Go With the Flow
Just like in real life, sometimes we’d like our code to be able to make
decisions.
The Python programs we’ve written so far have had one-track minds:
they can add two numbers or print something, but they don’t have the
ability to pick one of these outcomes over the other.

Control flow gives us this ability to choose among outcomes based on


what else is happening in the program.
Instructions

1.

Check out the code in the editor. You’ll see the type of program you’ll
be able to write once you’ve mastered control flow. Click Run to see
what happens!

def clinic():
    print "You've just entered the clinic!"
    print "Do you take the door on the left or the right?"
    answer = raw_input("Type left or right and hit 'Enter'.").lower()
    if answer == "left" or answer == "l":
        print "This is the Verbal Abuse Room, you heap of parrot dropping
s!"
    elif answer == "right" or answer == "r":
        print "Of course this is the Argument Room, I've told you that al
ready!"
    else:
        print "You didn't pick left or right! Try again."
        clinic()

clinic()

3.2 Compare Closely!


Let’s start with the simplest aspect of control flow: comparators. There
are six:

Equal to (==)
>>> 2 == 2
True
>>> 2 == 5
False
Not equal to (!=)
>>> 2 != 5
True
>>> 2 != 2
False
Less than (<)
>>> 2 < 5
True
>>> 5 < 2
False
Less than or equal to (<=)
>>> 2 <= 2
True
>>> 5 <= 2
False
Greater than (>)
>>> 5 > 2
True
>>> 2 > 5
False
Greater than or equal to (>=)
>>> 5 >= 5
True
>>> 2 >= 5
False
Comparators check if a value is (or is not) equal to, greater than (or
equal to), or less than (or equal to) another value.

Note that == compares whether two things are equal, and = assigns a


value to a variable.
Instructions

1.

Set each variable to True or False depending on what you think the


result will be. For example, 1 < 2 will be True, because one is less than
two.

 Set bool_one equal to the result of 17 < 328

 Set bool_two equal to the result of 100 == (2 * 50)

 Set bool_three equal to the result of 19 <= 19

 Set bool_four equal to the result of -22 >= -18

 Set bool_five equal to the result of 99 != (98 + 1)


3.3 Compare... Closelier!
Excellent! It looks like you’re comfortable with basic expressions and
comparators.

But what about extreme expressions and comparators?


Instructions

1.

Let’s run through the comparators again with more complex


expressions. Set each variable to True or False depending on what you
think the result will be.

 Set bool_one to the result of (20 - 10) > 15

 Set bool_two to the result of (10 + 17) == 3**16

 Set bool_three to the result of 1**2 <= -1

 Set bool_four to the result of 40 * 4 >= -4

 Set bool_five to the result of 100 != 10**2


 # Assign True or False as appropriate on the lines below!

 # (20 - 10) > 15
 bool_one = False    # We did this one for you!

 # (10 + 17) == 3**16
 # Remember that ** can be read as 'to the power of'. 3**16 is about 
43 million.
 bool_two = False

 # 1**2 <= -1
 bool_three = False

 # 40 * 4 >= -4
 bool_four = True

 # 100 != 10**2
 bool_five = False
3.4 How the Tables Have Turned
Comparisons result in either True or False, which are booleans as we
learned before in this exercise.
# Make me true!
bool_one = 3 < 5
Let’s switch it up: we’ll give the boolean, and you’ll write the
expression, just like the example above.
Instructions

1.

For each boolean value in the editor, write an expression that evaluates
to that value. Remember, comparators are: ==, !=, >, >=, <, and <=.

Use at least three different ones!

Don’t just use True and False! That’s cheating!

3.5 To Be and/or Not to Be


Boolean operators compare statements and result in boolean values.
There are three boolean operators:

1. and, which checks if both the statements are True;

2. or, which checks if at least one of the statements is True;

3. not, which gives the opposite of the statement.

We’ll go through the operators one by one.


Instructions

Check out the truth tables to the right. They show the results of using
AND, OR, and NOT boolean operators given the boolean inputs A and
B.

Click next to continue.


3.6 And
The boolean operator and returns True when the expressions on both
sides of and are true. For instance:

 1 < 2 and 2 < 3 is True.

 1 < 2 and 2 > 3 is False.

Instructions

1.

Let’s practice with and. Assign each variable to the appropriate boolean


value.

 Set bool_one equal to the result of


False and False

 Set bool_two equal to the result of


-(-(-(-2))) == -2 and 4 >= 16 ** 0.5

 Set bool_three equal to the result of


19 % 4 != 300 / 10 / 10 and False

 Set bool_four equal to the result of


-(1 ** 2) < 2 ** 0 and 10 % 10 <= 20 - 10 * 2
 Set bool_five equal to the result of
True and True

bool_one = 3==1 and 4<3

bool_two = -(-(-(-2)))==-2 and 4>=16**0.5

bool_three = 19%4 != 300/10/10 and 60<=5*5
bool_four =-(1**2)<2**0 and 10%10<=20-10*2 

bool_five = 6!=6*2 and 60<=(60+1)

3.7 Or
The boolean operator or returns True when at least one expression on
either side of or is true. For example:

 1 < 2 or 2 > 3 is True;

 1 > 2 or 2 > 3 is False.

Instructions

1.

Time to practice with or!

 Set bool_one equal to the result of


2 ** 3 == 108 % 100 or 'Cleese' == 'King Arthur'

 Set bool_two equal to the result of


True or False

 Set bool_three equal to the result of


100 ** 0.5 >= 50 or False

 Set bool_four equal to the result of


True or True

 Set bool_five equal to the result of


1 ** 100 == 100 ** 1 or 3 * 2 * 1 != 3 + 2 + 1

bool_one = 2**3==108%100 or 'Cleese'=='King Arthur'

bool_two = 2<=2 or 3==5

bool_three = 100**0.5 >= 50 or 45**3<=100

bool_four = 100==10**2 or 5*5==5**2

bool_five = 1**100==100**1 or 3*2*1 != 3+2+1

3.8 Not
The boolean operator not returns True for false statements and False for
true statements.

For example:

 not False will evaluate to True, while not 41 > 40 will return False.

Instructions

1.

Let’s get some practice with not.

 Set bool_one equal to the result of


not True

 Set bool_two equal to the result of


not 3 ** 4 < 4 ** 3

 Set bool_three equal to the result of


not 10 % 3 <= 10 % 2

 Set bool_four equal to the result of


not 3 ** 2 + 4 ** 2 != 5 ** 2

 Set bool_five equal to the result of


not not False
3.9 This and That (or This, But Not That!)
Boolean operators aren’t just evaluated from left to right. Just like with
arithmetic operators, there’s an order of operations for boolean
operators:

1. not is evaluated first;

2. and is evaluated next;

3. or is evaluated last.

For example, True or not False and False returns True. If this isn’t clear,


look at the Hint.

Parentheses () ensure your expressions are evaluated in the order you


want. Anything in parentheses is evaluated as its own unit.
Instructions

1.

Assign True or False as appropriate for bool_one through bool_five.

 Set bool_one equal to the result of


False or not True and True

 Set bool_two equal to the result of


False and not True or True

 Set bool_three equal to the result of


True and not (False or False)

 Set bool_four equal to the result of


not not True or False and not True

 Set bool_five equal to the result of


False or not (True and True)
3.10 Mix 'n' Match
Great work! We’re almost done with boolean operators.
# Make me false
bool_one = (2 <= 2) and "Alpha" == "Bravo"
Instructions

1.

This time we’ll give the expected result, and you’ll use some
combination of boolean operators to achieve that result.

Remember, the boolean operators are and, or, and not. Use each one at


least once!

# Make me false!
bool_one = (2 <= 2) and (45 == 4+5)  # We did this one for you!

# Make me true!
bool_two = (3*5<3+5) or (2+2==2**2)

# Make me false!
bool_three = (7**7!=7*7)  and (56==5+6)

# Make me true!
bool_four = (not 3+3==3*3) and (4==2+2)

# Make me true!
bool_five = (66+6!=72) or (1==1)

3.11 Conditional Statement Syntax


if is a conditional statement that executes some specified code after
checking if its expression is True.

Here’s an example of if statement syntax:


if 8 < 9:
print "Eight is less than nine!"
In this example, 8 < 9 is the checked expression and print "Eight is less
than nine!" is the specified code.

Pay attention to the indentation before the print statement. This space,


called white space, is how Python knows we are entering a new block of
code. Python accepts many different kinds of indentation to indicate
blocks. In this lesson, we use four spaces but elsewhere you might
encounter two-space indentation or tabs (which Python will see as
different from spaces).

If the indentation from one line to the next is different and there is no
command (like if) that indicates an incoming block then Python will
raise an IndentationError. These errors could mean, for example, that one
line had two spaces but the next one had three. Python tries to indicate
where this error happened by printing the line of code it couldn’t parse
and using a ^ to point to where the indentation was different from
what it expected.
Instructions

1.

If you think the print statement will print to the console,


set response equal to 'Y'; otherwise, set response equal to 'N'.

3.12 If You're Having...


Let’s get some practice with if statements. Remember, the syntax looks
like this:
if some_function():
# block line one
# block line two
# et cetera
Looking at the example above, in the event
that some_function() returns True, then the indented block of code after it
will be executed. In the event that it returns False, then the indented
block will be skipped.

Also, make sure you notice the colons at the end of the if statement.
We’ve added them for you, but they’re important.
Instructions

1.

In the editor you’ll see two functions. Don’t worry about anything
unfamiliar. We’ll explain soon enough.

 Replace the underline on line 2 with an expression that


returns True.
 Replace the underline on line 6 with an expression that
returns True.

If you do it successfully, then both "Success #1" and "Success #2" are


printed.
def using_control_once():
    if 45!= 4+5:
        return "Success #1"

def using_control_again():
    if 100 != 10**10:
        return "Success #2"

print using_control_once()
print using_control_again()

3.13 Else Problems, I Feel Bad for You, Son...


The else statement complements the if statement. An if/else pair says:
“If this expression is true, run this indented code block; otherwise, run
this code after the else statement.”

Unlike if, else doesn’t depend on an expression. For example:


if 8 > 9:
print "I don't get printed!"
else:
print "I get printed!"
Instructions

1.

Complete the else statements to the right. Note the indentation for


each line!

answer = "'Tis but a scratch!"

def black_knight():
    if answer == "'Tis but a scratch!":
        return True
    else:             
        return False       # Make sure this returns False

def french_soldier():
    if answer == "Go away, or I shall taunt you a second time!":
        return True
    else:             
        return False       # Make sure this returns False

3.14 I Got 99 Problems, But a Switch Ain't One


elif is short for “else if.” It means exactly what it sounds like:
“otherwise, if the following expression is true, do this!”
if 8 > 9:
print "I don't get printed!"
elif 8 < 9:
print "I get printed!"
else:
print "I also don't get printed!"
In the example above, the elif statement is only checked if the
original if statement is False.
Instructions

1.

On line 2, fill in the if statement to check if answer is greater than 5.

On line 4, fill in the elif so that the function outputs -1 if answer is less


than 5.

def greater_less_equal_5(answer):
    if answer>5:
        return 1
    elif answer<5:          
        return -1
    else:
        return 0
        
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

3.15 The Big If


Really great work! Here’s what you’ve learned in this unit:
Comparators
3 < 4
5 >= 5
10 == 10
12 != 13
Boolean operators
True or False
(3 < 4) and (5 >= 5)
this() and not that()
Conditional statements
if this_might_be_true():
print "This really is true."
elif that_might_be_true():
print "That is true."
else:
print "None of the above."
Let’s get to the grand finale.
Instructions

1.

In the workspace to your right, there is the outline of a function


called grade_converter().

The purpose of this function is to take a number grade (1-100), defined


by the variable grade, and to return the appropriate letter grade (A, B, C,
D, or F).

Your task is to complete the function by creating


appropriate if and elif statements that will compare the
input grade with a number and then return a letter grade.

Your function should return the following letter grades:

 90 or higher should get an “A”

 80 - 89 should get a “B”

 70 - 79 should get a “C”

 65 - 69 should get a “D”

 Anything below a 65 should receive an “F”


3.16 PYGLATIN
Break It Down
Now let’s take what we’ve learned so far and write a Pig Latin
translator.
Pig Latin is a language game, where you move the first letter of
the word to the end and add “ay.” So “Python” becomes
“ythonpay.” To write a Pig Latin translator in Python, here are the
steps we’ll need to take:
1. Ask the user to input a word in English.
2. Make sure the user entered a valid word.
3. Convert the word from English to Pig Latin.
4. Display the translation result.
Instructions
When you’re ready to get coding, click Next. Since we took the
time to write out the steps for our solution, you’ll know what’s
coming!
Ahoy! (or Should I Say Ahoyay!)
Let’s warm up by printing a welcome message for our translator users.
Instructions

1.

Please print the phrase “Pig Latin”.

Input!
Next, we need to ask the user for input.
name = raw_input("What's your name?")
print name
In the above example, raw_input() accepts a string, prints it, and then
waits for the user to type something and press Enter (or Return).

In the interpreter, Python will ask:


What's your name?
Once you type in your name and hit Enter, it will be stored in name.
Instructions

1.

On line 4, use raw_input("Enter a word: ") to ask the user to enter a word.


Save the results of raw_input() in a variable called original.

Click Run

Type a word in the console window and press Enter (or Return).

print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = raw_input("Enter a word:")

Check Yourself!

Next we need to ensure that the user actually typed something.


empty_string = ""
if len(empty_string) > 0:
# Run this block.
# Maybe print something?
else:
# That string must have been empty.
We can check that the user’s string actually has characters!
Instructions

1.

Write an if statement that verifies that the string has characters.

 Add an if statement that checks that len(original) is greater than


zero. Don’t forget the : at the end of the if statement!

 If the string actually has some characters in it, print the user’s


word.

 Otherwise (i.e. an else: statement), please print "empty".


You’ll want to run your code multiple times, testing an empty string
and a string with characters. When you’re confident your code works,
continue to the next exercise.
print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0:
  print original
else:
  print "empty"

al imprimir variable no es necesario usar “”


Check Yourself... Some More
Now we know we have a non-empty string. Let’s be even more
thorough and check that our string only contains letters.

Consider the following code:


x = "J123"
x.isalpha() # This will return 'False'
In the first line, we create a string with letters and numbers.

The second line then runs the method .isalpha() which


returns False since the string contains non-letter characters.

You can use .isalpha() to check that a string doesn’t contain any non-
letter characters! For example:
Instructions

1.

Use and to add a second condition to your if statement. In addition to


your existing check that the string contains characters, you should also
use .isalpha() to make sure that it only contains letters.

Don’t forget to keep the colon at the end of the if statement!

print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0 and original.isalpha():
  print original
else:
  print "empty"

Pop Quiz!

When you finish one part of your program, it’s important to test it
multiple times, using a variety of inputs.
Instructions

1.

Take some time to test your current code. Try some inputs that should
pass and some that should fail. Enter some strings that contain non-
alphabetical characters and an empty string.

When you’re convinced your code is ready to go, click Next to move
forward!

Ay B C
Now we can get ready to start translating to Pig Latin! Let’s review the
rules for translation:

You move the first letter of the word to the end and then append the
suffix ‘ay’. Example: python -> ythonpay

Let’s create a variable to hold our translation suffix.


Instructions

1.

Create a variable named pyg and set it equal to the suffix 'ay'.

Word Up
Let’s simplify things by making the letters in our word lowercase.
the_string = "Hello"
the_string = the_string.lower()
The .lower() function does not modify the string itself, it simply returns
a lowercase-version. In the example above, we store the result back
into the same variable.

We also need to grab the first letter of the word.


first_letter = the_string[0]
second_letter = the_string[1]
third_letter = the_string[2]
Remember that we start counting from zero, not one, so we access the
first letter by asking for [0].
Instructions

1.

Inside your if statement:

 Create a new variable called word that holds the .lower()-case


conversion of original.

 Create a new variable called first that holds word[0], the first


letter of word.
 pyg = 'ay'

 original = raw_input('Enter a word:')

 if len(original) > 0 and original.isalpha():
   word = original.lower()
   first = word[0]
 else:
     print 'empty'

Move it on Back

Now that we have the first letter stored, we need to add both the
letter and the string stored in pyg to the end of the original
string.conca

Remember how to concatenate (i.e. add) strings together?


greeting = "Hello "
name = "D. Y."
welcome = greeting + name
Instructions
1.

On a new line after where you created the first variable:

Create a new variable called new_word and set it equal to the


concatenation of word, first, and pyg.
pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
  word = original.lower()
  first = word[0]
  new_word = word + first + pyg
else:
    print 'empty'

Ending Up
Well done! However, now we have the first letter showing up both at
the beginning and near the end.
s = "Charlie"

print s[0]
# will print "C"

print s[1:4]
# will print "har"

1. First we create a variable s and give it the string "Charlie"

2. Next we access the first letter of "Charlie" using s[0]. Remember


letter positions start at 0.

3. Then we access a slice of "Charlie" using s[1:4]. This returns


everything from the letter at position 1 up till position 4.

We are going to slice the string just like in the 3rd example above.
Instructions

1.

Set new_word equal to the slice from the 1st index all the way to the end
of new_word. Use [1:len(new_word)] to do this.
My response
pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
  word = original.lower()
  first = word[0]
  new_word = word + first + pyg
  new_word = s[1:len(new_word)] 
else:
    print 'empty'

Computer response
pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
  word = original.lower()
  first = word[0]
  new_word = word + first + pyg
  new_word = new_word[1:len(new_word)]
else:
    print 'empty'

Testing, Testing, is This Thing On?


Yay! You should have a fully functioning Pig Latin translator. Test your
code thorougly to be sure everything is working smoothly.

You’ll also want to take out any print statements you were using to


help debug intermediate steps of your code. Now might be a good
time to add some comments too! Making sure your code is clean,
commented, and fully functional is just as important as writing it in the
first place.
Instructions
1.

When you’re sure your translator is working just the way you want it,
click Run Code to finish this project.

What is the importance of raw_input


4 FUNCTIONS
4.1 What Good are Functions?
You might have considered the situation where you would like to reuse
a piece of code, just with a few different values. Instead of rewriting the
whole code, it’s much cleaner to define a function, which can then be
used repeatedly.
Instructions

1.

Check out the code in the editor. We’ve defined two functions: tax to


calculate the tax on a bill, and tip to compute the tip.

See how much of the code you understand at first glance (we’ll explain
it all soon). When you’re ready, click Run to continue.

4.2 Function Junction


Functions are defined with three components:

1. The header, which includes the def keyword, the name of the


function, and any parameters the function requires. Here’s an
example:
def hello_world(): # There are no parameters
2. An optional comment that explains what the function does.
"""Prints 'Hello World!' to the console."""
3. The body, which describes the procedures the function carries
out. The body is indented, just like conditional statements.
print "Hello World!"
Here’s the full function pieced together:
def hello_world():
"""Prints 'Hello World!' to the console."""
print "Hello World!"
Instructions

1.

Go ahead and create a function, spam, that prints the string "Eggs!" to the


console. Don’t forget to include a comment of your own choosing
(enclose it in triple quotes!).

def spam():
  """Prints 'Eggs!' to the console."""
  print "Eggs!"

4.3 Call and Response


After defining a function, it must be called to be implemented. In the
previous exercise, spam() in the last line told the program to look for
the function called  spam  and execute the code inside it.
Instructions

1.

We’ve set up a function, square. Call it on the number 10 (by


putting 10 between the parentheses of square()) on line 10!

def square(n):
  """Returns the square of a number."""
  squared = n ** 2
  print "%d squared is %d." % (n, squared)
  return squared
  
# Call the square function on line 10! Make sure to
# include the number 10 between the parentheses.

square(10)

4.4 Parameters and Arguments


Let’s take another look at the definition of the function square from the
previous exercise:
def square(n):
Here, n is a parameter of square. A parameter is a variable that is an
input to a function. It says, “Later, when square is used, you’ll be able to
input any value you want, but for now we’ll call that future value n.” A
function can have any number of parameters.

The values of the parameters passed into a function are known as


the arguments. Recall in the previous example, we called: py square(10)

Here, the function square was called with the parameter n set to the


argument 10.

Typically, when you call a function, you should pass in the same
number of arguments as there are parameters.

To summarize:

 When defining a function, placeholder variables are called


parameters.

 When using, or calling, a function, inputs into the function are


called arguments.

Instructions

1.

Check out the function in the editor, power. It should take two


arguments, a base and an exponent, and raise the first to the power of
the second. It’s currently broken, however, because its parameters are
missing.

Replace the ___s with the parameters base and exponent and then call


the power function with a base of 37 and an exponent of 4.

def power(base, exponent):  # Add your parameters here!
  result = base ** exponent
  print "%d to the power of %d is %d." % (base, exponent, result)

power(37, 4)  # Add your arguments here!
4.5 Functions Calling Functions
We’ve seen functions that can print text or do simple arithmetic, but
functions can be much more powerful than that. For example, a
function can call another function:
def fun_one(n):
return n * 5

def fun_two(m):
return fun_one(m) + 7
Instructions

1.

Let’s look at the two functions in the editor: one_good_turn (which


adds 1 to the number it takes in as an argument)
and deserves_another (which adds 2).

Change the body of deserves_another so that it always adds 2 to the


output of one_good_turn.
def one_good_turn(n):
  return n + 1
    
def deserves_another(n):
  return one_good_turn(n) + 2

4.6 Practice Makes Perfect


Let’s create a few more functions just for good measure.
def shout(phrase):
if phrase == phrase.upper():
return "YOU'RE SHOUTING!"
else:
return "Can you speak up?"

shout("I'M INTERESTED IN SHOUTING")


The example above is just there to help you remember how functions
are structured.

Don’t forget the colon at the end of your function definition!

Instructions

1.
First, def a function called cube that takes an argument called number.
Don’t forget the parentheses and the colon!

Make that function return the cube of that number (i.e. that number


multiplied by itself and multiplied by itself once again).

Define a second function called by_three that takes an argument


called number.

if that number is divisible by 3, by_three should


call cube(number) and return its result. Otherwise, by_three should return
False.

Don’t forget that if and else statements need a : at the end of that


line!
def cube(number):
  return number * number * number

def by_three(number):
  if number % 3 == 0:
    return cube(number)
  else:
    return False

4.7 I Know Kung Fu


Remember import this from the first exercise in this course? That was an
example of import*ing a *module. A module is a file that contains
definitions—including variables and functions—that you can use once
it is imported.
Instructions

1.

Before we try any fancy importing, let’s see what Python already knows
about square roots. On line 3 in the editor, ask Python to
print sqrt(25)
which we would expect to equal five.

Instead, it throws an error.


4.8 Generic Imports
Did you see that? Python said: NameError: name 'sqrt' is not
defined. Python doesn’t know what square roots are—yet.

There is a Python module named math that includes a number of useful


variables and functions, and sqrt() is one of those functions. In order
to access math, all you need is the import keyword. When you simply
import a module this way, it’s called a generic import.

Instructions

1.

You’ll need to do two things here:

 Type import math on line 2 in the editor.

 Insert math. before sqrt() so that it has the form math.sqrt(). This


tells Python not only to import math, but to get the sqrt() function
from within math. Then hit Run to see what Python now knows.
 import math
 print math.sqrt(25)

4.9 Function Imports


Nice work! Now Python knows how to take the square root of a
number.

However, we only really needed the sqrt function, and it can be


frustrating to have to keep typing math.sqrt().

It’s possible to import only certain variables or functions from a given


module. Pulling in just a single function from a module is called
a function import, and it’s done with the from keyword:
from module import function
Now you can just type sqrt() to get the square root of a number—no
more math.sqrt()!
Instructions

1.
Let’s import only the sqrt function from math this time. (You don’t need
the () after sqrt in the from math import sqrt bit.)

# Import *just* the sqrt function from math on line 3!

from math import sqrt

4.10 Universal Imports


Great! We’ve found a way to handpick the variables and functions we
want from modules.

What if we still want all of the variables and functions in a module


but don’t want to have to constantly type math.?

Universal import can handle this for you. The syntax for this is:
from module import *
Instructions

1.

Use the power of from module import * to import everything from


the math module on line 3 of the editor.
from math import *

4.11 Here Be Dragons


Universal imports may look great on the surface, but they’re not a
good idea for one very important reason: they fill your program with
a  ton  of variable and function names without the safety of those names
still being associated with the module(s) they came from.

If you have a function of your very own named sqrt and you import math,


your function is safe: there is your sqrt and there is math.sqrt. If you
do from math import *, however, you have a problem: namely, two
different functions with the exact same name.

Even if your own definitions don’t directly conflict with names from
imported modules, if you import * from several modules at once, you
won’t be able to figure out which variable or function came from
where.
For these reasons, it’s best to stick with either import module and
type module.name or just import specific variables and functions from
various modules as needed.
Instructions

1.

The code in the editor will show you everything available in


the math module.

Click Run to check it out (you’ll see sqrt, along with some other useful
things like pi, factorial, and trigonometric functions.

import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print everything # Prints 'em all!

4.12 On Beyond Strings


Now that you understand what functions are and how to import
modules, let’s look at some of the functions that are built in to Python
(no modules required!).

You already know about some of the built-in functions we’ve used with
strings, such as .upper(), .lower(), str(), and len(). These are great for
doing work with strings, but what about something a little more
analytic?
Instructions

1.

What do you think the code in the editor will do? Click Run when you
think you have an idea

def biggest_number(*args):
  print max(args)
  return max(args)
    
def smallest_number(*args):
  print min(args)
  return min(args)
def distance_from_zero(arg):
  print abs(arg)
  return abs(arg)

biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)

4.13 max()
The max() function takes any number of arguments and returns the
largest one. (“Largest” can have odd definitions here, so it’s best to
use max() on integers and floats, where the results are straightforward,
and not on other objects, like strings.)

For example, max(1,2,3) will return 3 (the largest number in the set of


arguments).
Instructions

1.

Try out the max() function on line 3 of the editor. You can provide any
number of integer or float arguments to max().

maximum = max(5,5.5, 7, 9.5)

print maximum

4.14 min()
min() then returns the smallest of a given series of arguments.
Instructions

1.

Go ahead and set minimum equal to the min() of any set of integers or


floats you’d like.
minimum = min(5,5.5, 7, 9.5)

print minimum
4.15 abs()
The abs() function returns the absolute value of the number it takes as
an argument—that is, that number’s distance from 0 on an imagined
number line. For instance, 3 and -3 both have the same absolute
value: 3. The abs() function always returns a positive value, and
unlike max() and min(), it only takes a single number.

Instructions

1.

Set absolute equal to the absolute value of -42 on line 1.

absolute = abs(-42)
print absolute

4.16 type()
Finally, the type() function returns the type of the data it receives as an
argument. If you ask Python to do the following:
print type(42)
print type(4.2)
print type('spam')
Python will output:
<type 'int'>
<type 'float'>
<type 'str'>
Instructions

1.

Have Python print out the type of an int, a float, and a str string in the
editor. You can pick any values on which to call type(), so long as they
produce one of each.

print type(100)
print type(3.5)
print type('Endure to the end')
4.17 Review: Functions
Okay! Let’s review functions.
def speak(message):
return message

if happy():
speak("I'm happy!")
elif sad():
speak("I'm sad.")
else:
speak("I don't know what I'm feeling.")
Again, the example code above is just there for your reference!
Instructions

1.

First, def a function, shut_down, that takes one argument s. Don’t forget


the parentheses or the colon!

Then, if the shut_down function receives an s equal to "yes", it


should return "Shutting down"

Alternatively, elif s is equal to "no", then the function should return


"Shutdown aborted".esl

Finally, if shut_down gets anything other than those inputs, the function


should return "Sorry"

def shut_down(s):
  if s == "yes":
    return "Shutting down"
  elif s == "no":
    return "Shutdown aborted"
  else:
    return "Sorry"

4.18 Review: Modules


Good work! Now let’s see what you remember about importing
modules (and, specifically, what’s available in the math module).
Instructions

1.
Import the math module in whatever way you prefer. Call
its sqrt function on the number 13689 and print that value to the
console.

from math import sqrt
print sqrt(13689)

4.19 Review: Built-In Functions


Perfect! Last but not least, let’s review the built-in functions you’ve
learned about in this lesson.
def is_numeric(num):
return type(num) == int or type(num) == float:

max(2, 3, 4) # 4
min(2, 3, 4) # 2

abs(2) # 2
abs(-2) # 2
Instructions

1.

First, def a function called distance_from_zero, with one argument (choose


any argument name you like).

If the type of the argument is either int or float, the function


should return the absolute value of the function input.

Otherwise, the function should return "Nope"

4.20 TAKING A VACATION


4.20.1 Before We Begin
Let’s first quickly review functions in Python.
def bigger(first, second):
print max(first, second)
return True
In the example above:

1. We define a function called bigger that has two arguments


called first and second.
2. Then, we print out the larger of the two arguments using the
built-in function max.

3. Finally, the bigger function returns True.

Now try creating a function yourself!


Instructions

1.

Write a function called answer that takes no arguments and returns the


value 42.

Even without arguments, you will still need parentheses.Don’t forget


the colon at the end of the function definition!

def answer():
  return 42

4.20.2 Planning Your Trip


When planning a vacation, it’s very important to know exactly how
much you’re going to spend.
def wages(hours):
# If I make $8.35/hour...
return 8.35 * hours
The above example is just a refresher in how functions are defined.

Let’s use functions to calculate your trip’s costs.


Instructions

1.

Define a function called hotel_cost with one argument nights as input.

The hotel costs $140 per night. So, the function hotel_cost should return


140 * nights.

ef hotel_cost(nights):
 return 140*nights

4.20.3 Getting There


You’re going to need to take a plane ride to get to your location.
def fruit_color(fruit):
if fruit == "apple":
return "red"
elif fruit == "banana":
return "yellow"
elif fruit == "pear":
return "green"

1. The example above defines the function fruit_color that accepts a


string as the argument fruit.

2. The function returns a string if it knows the color of that fruit.

Instructions

1.

Below your existing code, define a function called plane_ride_cost that


takes a string, city, as input.

The function should return a different price depending on the location,


similar to the code example above. Below are the valid destinations
and their corresponding round-trip prices.

 "Charlotte": 183

 "Tampa": 220

 "Pittsburgh": 222

 "Los Angeles": 475

def hotel_cost(nights):
 return 140*nights
def plane_ride_cost(city):
  if city == "Charlotte":
   return 183
  elif city == "Tampa":
   return 220
  elif city == "Pittsburgh":
   return 222
  elif city == "Los Angeles":
   return 475
4.20.4 Transportation
You’re also going to need a rental car in order for you to get around.
def finish_game(score):
tickets = 10 * score
if score >= 10:
tickets += 50
elif score >= 7:
tickets += 20
return tickets
In the above example, we first give the player 10 tickets for every point
that the player scored. Then, we check the value of score multiple times.

1. First, we check if score is greater than or equal to 10. If it is, we


give the player 50 bonus tickets.

2. If score is just greater than or equal to 7, we give the player 20


bonus tickets.

3. At the end, we return the total number of tickets earned by the


player.

Remember that an elif statement is only checked if all


preceding if/elif statements fail.
Instructions

1.

Below your existing code, define a function called rental_car_cost with


an argument called days.

Calculate the cost of renting the car:

 Every day you rent the car costs $40.

 if you rent the car for 7 or more days, you get $50 off your total.

 Alternatively (elif), if you rent the car for 3 or more days, you get
$20 off your total.

 You cannot get both of the above discounts.

Return that cost.


Just like in the example above, this check becomes simpler if you make
the 7-day check an if statement and the 3-day check
an elif statement.
def rental_car_cost(days):
  cost = 40*days
  if days >= 7:
    cost = 40*days-50
  elif days >=3:
    cost = 40*days
  return cost

4.20.5 Pull it Together


Great! Now that you’ve got your 3 main costs figured out, let’s put
them together in order to find the total cost of your trip.
def double(n):
return 2 * n

def triple(p):
return 3 * p

def add(a, b):


return double(a) + triple(b)
1. We define two simple functions, double(n) and triple(p) that
return 2 times or 3 times their input. Notice that they
have n and p as their arguments
2. We define a third function, add(a, b) that returns the sum of the
previous two functions when called with a and b, respectively.
Notice that even though the names of the parameters for add(a,
b) are different than the names of the parameters
for double(n) and triple(p) we can still pass them into those
functions as arguments
Instructions

1.

Below your existing code, define a function called trip_cost that takes


two parameters, city and days and returns the sum of calling
the rental_car_cost(days), hotel_cost(days - 1),
and plane_ride_cost(city) functions.

Notice that we changed the argument


of hotel_costs() from nights to days - 1. Since we want trip-cost to only
depend on two parameters, we have to convert the
variable nights into days. If you are going to be staying somewhere, the
number of nights you stay there is one less than the number of days
you were there (imagine a weekend trip to visit family, you leave
Saturday and return Sunday, so you visit for two days, but only stay for
one night).

def trip_cost(city,days):
  return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(c
ity)

Hey, You Never Know!

You can’t expect to only spend money on the plane ride, hotel, and
rental car when going on a vacation. There also needs to be room for
additional costs like fancy food or souvenirs.

Instructions

1.

Modify your trip_cost function definition. Add a third


argument, spending_money.

Modify what the trip_cost function does. Add the


variable spending_money to the sum that it returns.

def trip_cost(city,days,spendig_money):
  return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(c
ity) + spendig_money

4.20.6 Plan Your Trip!


Nice work! Now that you have it all together, let’s take a trip.

What if we went to Los Angeles for 5 days and brought an extra 600
dollars of spending money?
Instructions

1.
After your previous code, print out the trip_cost( to "Los
Angeles" for 5 days with an extra 600 dollars of spending money.

Don’t forget the closing ) after passing in the 3 previous values!


print trip_cost("Los Angeles",5,600)

def hotel_cost(nights):
 return 140*nights
def plane_ride_cost(city):
  if city == "Charlotte":
   return 183
  elif city == "Tampa":
   return 220
  elif city == "Pittsburgh":
   return 222
  elif city == "Los Angeles":
   return 475
def rental_car_cost(days):
  cost = 40*days
  if days >= 7:
    cost = 40*days-50
  elif days >=3:
    cost = 40*days-20
  return cost
def trip_cost(city,days,spendig_money):
  return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(c
ity) + spendig_money
print trip_cost("Los Angeles",5,600)
5 PYTHON LISTS AND DICTIONARIES
5.1 Introduction to Lists
Lists are a datatype you can use to store a collection of different pieces of
information as a sequence under a single variable name. (Datatypes you’ve
already learned about include strings, numbers, and booleans.)

You can assign items to a list with an expression of the form

list_name = [item_1, item_2]


with the items in between brackets. A list can also be empty: empty_list = [].

Lists are very similar to strings, but there are a few key differences.
Instructions

1.

The list zoo_animals has three items (check them out on line 1). Go ahead
and add a fourth! Just enter the name of your favorite animal (as
a "string") on line 1, after the final comma but before the closing ].

zoo_animals = ["pangolin", "cassowary", "sloth","dog" ];
# One animal is missing!

if len(zoo_animals) > 3:
  print "The first animal at the zoo is the " + zoo_animals[0]
  print "The second animal at the zoo is the " + zoo_animals[1]
  print "The third animal at the zoo is the " + zoo_animals[2]
  print "The fourth animal at the zoo is the " + zoo_animals[3]

The first animal at the zoo is the pangolin


The second animal at the zoo is the cassowary
The third animal at the zoo is the sloth
The fourth animal at the zoo is the dog

5.2 Access by Index


You can access an individual item on the list by its index. An index is
like an address that identifies the item’s place in the list. The index
appears directly after the list name, in between brackets, like
this: list_name[index].

List indices begin with 0, not 1! You access the first item in a list like
this: list_name[0]. The second item in a list is at index 1: list_name[1].
Computer scientists love to start counting from zero.
Instructions

1.

Write a statement that prints the result of adding the second and
fourth items of the list. Make sure to access the list by index!

numbers = [5, 6, 7, 8]

print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
# Your code here!
print numbers[1] + numbers[3]

Adding the numbers at indices 0 and 2...


12
Adding the numbers at indices 1 and 3...
14

5.3 New Neighbors


A list index behaves like any other variable name! It can be used to
access as well as assign values.
You saw how to access a list index like this:
zoo_animals[0]
# Gets the value "pangolin"
You can see how assignment works on line 5:
zoo_animals[2] = "hyena"
# Changes "sloth" to "hyena"
Instructions

1.

Write an assignment statement that will replace the item that currently
holds the value "tiger" with another animal (as a string). It can be any
animal you like.

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked 
# the poor tiger and ate it whole.

# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"

# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] = "crocodile"

5.4 Late Arrivals & List Length


A list doesn’t have to have a fixed length. You can add items to the end
of a list any time you like!
letters = ['a', 'b', 'c']
letters.append('d')
print len(letters)
print letters

1. In the above example, we first create a list called letters.

2. Then, we add the string 'd' to the end of the letters list.

3. Next, we print out 4, the length of the letters list.

4. Finally, we print out ['a', 'b', 'c', 'd'].

Instructions
1.

On lines 5, 6, and 7, append three more items to the suitcase list, just


like the second line of the example above. (Maybe bring a bathing
suit?)

Then, set list_length equal to the length of the suitcase list.


suitcase = [] 
suitcase.append("sunglasses")

# Your code here!
suitcase.append("coat")
suitcase.append("hat")
suitcase.append("shoes")

list_length = len(suitcase)# Set this to the length of suitcase

print "There are %d items in the suitcase." % (list_length)
print suitcase

There are 4 items in the suitcase.


['sunglasses', 'coat', 'hat', 'shoes']

5.5 List Slicing


Sometimes, you only want to access a portion of a list. Consider the
following code:
letters = ['a', 'b', 'c', 'd', 'e']
slice = letters[1:3]
print slice
print letters
What is this code doing?

First, we create a list called letters.

Then, we take a subsection of the list and store it in the slice list. We


do this by defining the indices we want to include after the name of
the list: letters[1:3]. In Python, when we specify a portion of a list in this
manner, we include the element with the first index, 1, but
we exclude the element with the second index, 3.

Next, we print out slice, which will print ['b','c']. Remember, in Python


indices always start at 0, so the 1 element is actually b.
Finally, we print out ['a', 'b', 'c', 'd', 'e'], notice that we did not
modify the original letters list.
Instructions

1.

On line 7, create a list called middle containing only the two middle


items from suitcase.

On line 10, create a list called last made up only of the last two items
from suitcase.

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]

# The first and second items (index zero and one)
first = suitcase[0:2]

# Third and fourth items (index two and three)
middle = suitcase[2:4]

# The last two items (index four and five)
last = suitcase[4:6]

5.6 Slicing Lists and Strings


You can slice a string exactly like a list! In fact, you can think of strings
as lists of characters: each character is a sequential item in the list,
starting from index 0.
my_list[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last items
If your list slice includes the very first or last item in a list (or a string),
the index for that item doesn’t have to be included.
Instructions

1.

Assign to dog a slice of animals from index 3 up until but not


including index 6.

Assign to frog a slice of animals from index 6 until the end of the string.
animals = "catdogfrog"

# The first three characters of animals
cat = animals[:3]

# The fourth through sixth characters
dog = animals[3:6]

# From the seventh character to the end
frog = animals[6:]

5.7 Maintaining Order


Sometimes you need to search for an item in a list.
animals = ["ant", "bat", "cat"]
print animals.index("bat")

1. First, we create a list called animals with three strings.

2. Then, we print the first index that contains the string "bat", which
will print 1.

We can also insert items into a list.


animals.insert(1, "dog")
print animals

1. We insert "dog" at index 1, which moves everything down by 1.

2. We print out ["ant", "dog", "bat", "cat"]

Instructions

1.

Use the .index(item) function to find the index of "duck". Assign that


result to a variable called duck_index.

Then .insert(index, item) the string "cobra" at that index.

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")# Use index() to find "duck"
# Your code here!
animals.insert(duck_index,"cobra")

print animals # Observe what prints after the insert operation

5.8 For One and All


If you want to do something with every item in the list, you can use
a for loop. If you’ve learned about for loops in JavaScript, pay close
attention! They’re different in Python.
for variable in list_name:
# Do stuff!
A variable name follows the for keyword; it will be assigned the value of
each list item in turn.

Then in list_name designates list_name as the list the loop will work on.


The line ends with a colon (:) and the indented code that follows it will
be executed once per item in the list.
Instructions

1.

Write a statement in the indented part of the for-loop that prints a


number equal to 2 * number for every list item.

my_list = [1,9,3,8,5,7]

for number in my_list:
  # Your code here
  print 2 * number
  

2
18
6
16
10
14

5.9 More with 'for'


If your list is a jumbled mess, you may need to sort() it.
animals = ["cat", "ant", "bat"]
animals.sort()

for animal in animals:


print animal

1. First, we create a list called animals with three strings. The strings


are not in alphabetical order.

2. Then, we sort animals into alphabetical order. Note


that .sort() modifies the list rather than returning a new list.

3. Then, for each item in animals, we print that item out as "ant",
"bat", "cat" on their own line each.

Instructions

1.

Write a for-loop that iterates over start_list and .append()s each


number squared (x ** 2) to square_list.

Then sort square_list!

start_list = [5, 3, 1, 2, 4]
square_list = []

# Your code here!
for number in start_list:
  square_list.append(number ** 2)
square_list.sort()

print square_list

5.10 This Next Part is Key


A dictionary is similar to a list, but you access values by looking up
a key instead of an index. A key can be any string or number.
Dictionaries are enclosed in curly braces, like so:
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
This is a dictionary called d with three key-value pairs. The
key 'key1' points to the value 1, 'key2' to 2, and so on.
Dictionaries are great for things like phone books (pairing a name with
a phone number), login pages (pairing an e-mail address with a
username), and more!
Instructions

1.

Print the values stored under the 'Sloth' and 'Burmese Python' keys.


Accessing dictionary values by key is just like accessing list values by
index:
residents['Puffin']# Gets the value 104
Check the Hint if you need help!

# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] # Prints Puffin's room number

# Your code here!
print residents['Sloth']
print residents['Burmese Python']

104
105
106

5.11 New Entries


Like Lists, Dictionaries are mutable. This means they can be changed
after they are created. One advantage of this is that we can add
new key/value pairs to the dictionary after it is created like so:
dict_name[new_key] = new_value
An empty pair of curly braces {} is an empty dictionary, just like an
empty pair of [] is an empty list.

The length len() of a dictionary is the number of key-value pairs it has.


Each pair counts only once, even if the value is a list. (That’s right: you
can put lists inside dictionaries!)
Instructions

1.
Add at least three more key-value pairs to the menu variable, with the
dish name (as a "string") for the key and the price (a float or integer) as
the value. Here’s an example:
py menu['Spam'] = 2.50

Menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']

# Your code here: Add some dish-price pairs to menu!
menu['Hamburguer'] = 5.00
menu['Tacos'] = 3.00
menu['Arroz chaufa'] = 5.00

print "There are " + str(len(menu)) + " items on the menu."
print menu

14.5
There are 4 items on the menu.
{'Chicken Alfredo': 14.5, 'Arroz chaufa': 5.0,
'Hamburguer': 5.0, 'Tacos': 3.0}

5.12 Changing Your Mind


Because dictionaries are mutable, they can be changed in many
ways. Items can be removed from a dictionary with the del command:
del dict_name[key_name]
will remove the key key_name and its associated value from the
dictionary.

A new value can be associated with a key by assigning a value to the


key, like so:
dict_name[key] = new_value
Instructions

1.

Delete the 'Sloth' and 'Bengal Tiger' items from zoo_animals using del.


Set the value associated with 'Rockhopper Penguin' to anything other
than 'Arctic Exhibit'.

# key - animal_name : value - location 
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines

# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']

# Your code here!
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Jungle House'

print zoo_animals

{'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper


Penguin': 'Jungle House'}

5.13 Remove a Few Things


Sometimes you need to remove something from a list.
beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
This code will print:
["john","paul","george","ringo"]

1. We create a list called beatles with 5 strings.

2. Then, we remove the first item from beatles that matches the


string "stuart". Note that .remove(item) does not return anything.

3. Finally, we print out that list just to see that "stuart" was actually


removed.
Instructions

1.

Remove 'dagger' from the list of items stored in the backpack variable.

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')
print backpack

['xylophone', 'tent', 'bread loaf']

5.14 It's Dangerous to Go Alone! Take This


Let’s go over a few last notes about dictionaries
my_dict = {
"fish": ["c", "a", "r", "p"],
"cash": -4483,
"luck": "good"
}
print my_dict["fish"][0]

1. In the example above, we created a dictionary that holds many


types of values.

2. The key "fish" has a list, the key "cash" has an int, and the


key "luck" has a string.

3. Finally, we print the letter "c". When we access a value in the


dictionary like my_dict["fish"], we have direct access to that value
(which happens to be a list). We can access the item at index 0 in
the list stored by the key "fish".

Instructions

1.

Add a key to inventory called 'pocket'

Set the value of 'pocket' to be a list consisting of the


strings 'seashell', 'strange berry', and 'lint'

.sort() the items in the list stored under the 'backpack' key


Then .remove('dagger') from the list of items stored under
the 'backpack' key

Add 50 to the number stored under the 'gold' key

inventory = {
  'gold' : 500,
  'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pou
ch' key
  'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 

# Your code here
inventory['pocket'] = ['seashell', 'strange berry',  'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = 550

5.15 A DAY AT THE SUPERMARKET


5.15.1 BeFOR We Begin
Before we begin our exercise, we should go over the Python for loop
one more time. For now, we are only going to go over the for loop in
terms of how it relates to lists and dictionaries. We’ll explain more
cool for loop uses in later courses.

for loops allow us to iterate through all of the elements in a list from


the left-most (or zeroth element) to the right-most element. A sample
loop would be structured as follows:
a = ["List", "of", "some", "sort"]
for x in a:
# Do something for every x
This loop will run all of the code in the indented block under the for x
in a: statement. The item in the list that is currently being evaluated
will be x. So running the following:
for item in [1, 3, 21]:
print item
would print 1, then 3, and then 21. The variable between for and in can
be set to any variable name (currently item), but you should be careful
to avoid using the word list as a variable, since that’s a reserved word
(that is, it means something special) in the Python language.
Instructions

1.

Use a for loop to print out all of the elements in the list names.

names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
  print name

Adam
Alex
Mariah
Martine
Columbus

5.15.2 This is KEY!


You can also use a for loop on a dictionary to loop through
its keys with the following:
# A simple dictionary
d = {"foo" : "bar"}

for key in d:
print d[key] # prints "bar"
Note that dictionaries are unordered, meaning that any time you loop
through a dictionary, you will go through every key, but you are not
guaranteed to get them in any particular order.
Instructions

1.

Use a for loop to go through the webster dictionary and print out all of


the definitions.
webster = {
  "Aardvark" : "A star of a popular children's cartoon show.",
  "Baa" : "The sound a goat makes.",
  "Carpet": "Goes on the floor.",
  "Dab": "A small amount."
}

# Add your code below!
for Aardvark in webster:
  print webster[Aardvark]
for Baa in webster:
  print webster[Baa]
for Carpet in webster:
  print webster[Carpet]
for Dab in webster:
  print webster[Dab]

A star of a popular children's cartoon show.


Goes on the floor.
A small amount.
The sound a goat makes.
A star of a popular children's cartoon show.
Goes on the floor.
A small amount.
The sound a goat makes.
A star of a popular children's cartoon show.
Goes on the floor.
A small amount.
The sound a goat makes.
A star of a popular children's cartoon show.
Goes on the floor.
A small amount.
The sound a goat makes.

5.15.3 Control Flow and Looping


The blocks of code in a for loop can be as big or as small as they need
to be.

While looping, you may want to perform different actions depending


on the particular item in the list.
numbers = [1, 3, 4, 7]
for number in numbers:
if number > 6:
print number
print "We printed 7."

1. In the above example, we create a list with 4 numbers in it.

2. Then we loop through the numbers list and store each item in the


list in the variable number.

3. On each loop, if number is greater than 6, we print it out. So, we


print 7.

4. Finally, we print out a sentence.

Make sure to keep track of your indentation or you may get confused!
Instructions

1.

Like step 2 above, loop through each item in the list called a.

Like step 3 above, if the number is even, print it out. You can


test if the item % 2 == 0 to help you out.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for number in a:
  if number%2 == 0:
    print number

0
2
4
6
8
10
12

5.15.4 Lists + Functions


Functions can also take lists as inputs and perform various operations
on those lists.
def count_small(numbers):
total = 0
for n in numbers:
if n < 10:
total = total + 1
return total

lotto = [4, 8, 15, 16, 23, 42]


small = count_small(lotto)
print small

1. In the above example, we define a function count_small that has


one parameter, numbers.

2. We initialize a variable total that we can use in the for loop.

3. For each item n in numbers, if n is less than 10, we increment total.

4. After the for loop, we return total.

5. After the function definition, we create an array of numbers


called lotto.

6. We call the count_small function, pass in lotto, and store the


returned result in small.

7. Finally, we print out the returned result, which is 2 since


only 4 and 8 are less than 10.

Instructions

1.

Write a function that counts how many times the string "fizz" appears


in a list.

 Write a function called fizz_count that takes a list x as input.

 Create a variable count to hold the ongoing count. Initialize it to


zero.

 for each item in x:, if that
item is equal to the string "fizz" then
increment the count variable.

 After the loop, please return the count variable.

For example, fizz_count(["fizz","cat","fizz"]) should return 2.

My answer:
def fizz_count(x):
  count = 0
  for n in x:
    if n = "fizz":
      count= count + 1
return count

Program answer:
def fizz_count(x):
  count = 0
  for item in x:
    if item == "fizz":
      count = count + 1
  return count

5.15.5 String Looping


As we’ve mentioned, strings are like lists with characters as elements.
You can loop through strings the same way you loop through lists!
While we won’t ask you to do that in this section, we’ve put an example
in the editor of how looping through a string might work.
Instructions

1.

Run the code to see string iteration in action!

for letter in "Codecademy":
  print letter
    
# Empty lines to make the output pretty
print
print

word = "Programming is fun!"

for letter in word:
  # Only print out the letter i
  if letter == "i":
    print letter
C
o
d
e
c
a
d
e
m
y

i
i

5.15.6 Your Own Store!


Okay—on to the core of our project.

Congratulations! You are now the proud owner of your very own
Codecademy brand supermarket.
animal_counts = {
"ant": 3,
"bear": 6,
"crow": 2
}
In the example above, we create a new dictionary
called animal_counts with three entries. One of the entries has the
key "ant" and the value 3.
Instructions

1.

Create a new dictionary called prices using {} format like the example


above.

Put these values in your prices dictionary, in between the {}:


py "banana": 4, "apple": 2, "orange": 1.5, "pear": 3

Yeah, this place is really expensive. (Your supermarket subsidizes the


zoo from the last course.)

prices = {
  "banana" : 4,
  "apple" : 2,
  "orange" : 1.5,
  "pear" : 3,
}

5.15.7 Investing in Stock


Good work! As a store manager, you’re also in charge of keeping track
of your stock/inventory.
Instructions

1.

Create a stock dictionary with the values below.


py "banana": 6, "apple": 0, "orange": 32, "pear": 15

prices = {
  "banana" : 4,
  "apple" : 2,
  "orange" : 1.5,
  "pear" : 3,
}
stock = {
  "banana" : 6,
  "apple" : 0,
  "orange" : 32,
  "pear" : 15,
}
5.15.8 Keeping Track of the Produce
Now that you have all of your product info, you should print out all of
your inventory information.
once = {'a': 1, 'b': 2}
twice = {'a': 2, 'b': 4}
for key in once:
print "Once: %s" % once[key]
print "Twice: %s" % twice[key]

1. In the above example, we create two dictionaries, once and twice,


that have the same keys.

2. Because we know that they have the same keys, we can loop
through one dictionary and print values from both once and twice.

Instructions
1.

Loop through each key in prices.

Like the example above, for each key, print out the key along with its
price and stock information.

Print the answer in EXACTLY the following format:


apple
price: 2
stock: 0
Like the example above, because you know that
the prices and stock dictionary have the same keys, you can access
the stock dictionary while you are looping through prices.

When you’re printing, make sure to use the syntax from the example
above, with %s.

prices = {
  "banana" : 4,
  "apple" : 2,
  "orange" : 1.5,
  "pear" : 3,
}
stock = {
  "banana" : 6,
  "apple" : 0,
  "orange" : 32,
  "pear" : 15,
}
for key in prices:
  print "Price: %s" % prices[key]
  print "Stock: %s" % stock[key]

prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}

stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}

for food in prices:
  print food
  print "price: %s" % prices[food]
  print "stock: %s" % stock[food]
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

5.15.9 Something of Value


For paperwork and accounting purposes, let’s record the total value
of your inventory. It’s nice to know what we’re worth!
Instructions

1.

Let’s determine how much money you would make if you sold all of
your food.

 Create a variable called total and set it to zero.

 Loop through the prices dictionary.

 For each key in prices, multiply the number in prices by the


number in stock. Print that value into the console and then add it
to total.

 Finally, outside your loop, print total.

My answer

total = 0
for value in prices:
  print prices[value]*stock[value]

Program answer
total = 0
for food in prices:
  print prices[food] * stock[food]
  total = total + prices[food] * stock[food]
print total

48.0
45
24
0
117.0

5.15.10 Shopping at the Market


Great work! Now we’re going to take a step back from the
management side and take a look through the eyes of the shopper.

In order for customers to order online, we are going to have to make a


consumer interface. Don’t worry: it’s easier than it sounds!
Instructions

1.

First, make a list called groceries with the values "banana","orange",


and "apple".

5.15.11 Making a Purchase


Good! Now you’re going to need to know how much you’re paying for
all of the items on your grocery list.
def sum(numbers):
total = 0
for number in numbers:
total += number
return total

n = [1, 2, 5, 10, 13]


print sum(n)

1. In the above example, we first define a function called sum with a


parameter numbers.

2. We initialize the variable total which we will use as our running


sum.

3. For each number in the list, we add that number to the running
sum total.
4. At the end of the function, we return the running sum.

5. After the function, we create, n, a list of numbers.

6. Finally, we call the sum(numbers) function with the variable n and


print the result.

Instructions

1.

Define a function compute_bill that takes one argument food as input.

In the function, create a variable total with an initial value of zero.

For each item in the food list, add the price of that item to total.

Finally, return the total.

Ignore whether or not the item you’re billing for is in stock.Note that
your function should work for any food list.

def compute_bill(food):
  total = 0
  for n in food:
    total += n
  return total
def compute_bill(food):
  total = 0
  for item in food:
    total = total + prices[item]
  return total

5.15.12 Stocking Out


Now you need your compute_bill function to take the stock/inventory of
a particular item into account when computing the cost.

Ultimately, if an item isn’t in stock, then it shouldn’t be included in the


total. You can’t buy or sell what you don’t have!
Instructions

1.

Make the following changes to your compute_bill function:


While you loop through each item of food, only add the price of the
item to total if the item’s stock count is greater than zero.

if theitem is in stock and after you add the price to the total, subtract
one from the item’s stock count.
shopping_list = ["banana", "orange", "apple"]

stock = {
  "banana": 6,
  "apple": 0,
  "orange": 32,
  "pear": 15
}
    
prices = {
  "banana": 4,
  "apple": 2,
  "orange": 1.5,
  "pear": 3
}

# Write your code below!
def compute_bill(food):
  total = 0
  for item in food:
    if stock[item] > 0:
      total = total + prices[item]
      stock[item] = stock [item] - 1
  return total
5.15.13 Let's Check Out!
Perfect! You’ve done a great job with lists and dictionaries in this
project. You’ve practiced:

 Using for loops with lists and dictionaries

 Writing functions with loops, lists, and dictionaries

 Updating data in response to changes in the environment (for


instance, decreasing the number of bananas in stock by 1 when
you sell one).

Thanks for shopping at the Codecademy supermarket!


Instructions

1.

Print your result and click Run to finish this course.

6 STUDENT BECOMES THE TEACHER

6.1 Lesson Number One


Welcome to this “Challenge Course”. Until now we’ve been leading you
by the hand and working on some short and relatively easy projects.
This is a challenge so be ready. We have faith in you!

We’re going to switch it up a bit and allow you to be the teacher of


your own class. Make a gradebook for all of your students.
animal = {
"name": "Mr. Fluffles",
"sounds": ["meow", "purr"]
}
print animal["name"]
The example above is just to remind you how to create a dictionary
and then to access the item stored by the "name" key.
Instructions

1.

Create three dictionaries: lloyd, alice, and tyler.

Give each dictionary the keys "name", "homework", "quizzes", and "tests".

Have the “name” key be the name of the student (that is, lloyd‘s name
should be "Lloyd") and the other keys should be an empty list (We’ll fill
in these lists soon!)

lloyd = {
  "name" : "Lloyd",
  "homework" : [],
  "quizzes" : [],
  "tests" : []
}

alice = {
  "name" : "Alice",
  "homework" : [],
  "quizzes" : [],
  "tests" : []
}

tyler = {
  "name" : "Tyler",
  "homework" : [],
  "quizzes" : [],
  "tests" : []
}

6.2 What's the Score?


Great work!
Instructions

1.

Now fill out your lloyd dictionary with the appropriate scores. To save


you some time, we’ve filled out the rest for you.

Homework: 90.0, 97.0, 75.0, 92.0

Quizzes: 88.0, 40.0, 94.0

Test Scores: 75.0, 90.0

Make sure to include the decimal points so your grades are stored
as floats! This will be important later.

6.3 Put It Together


Now lets put the three dictionaries in a list together.
my_list = [1, 2, 3]
The above example is just a reminder on how to create a list.
Afterwards, my_list contains 1, 2, and 3.
Instructions

1.

Below your code, create a list called students that contains lloyd, alice,


and tyler.

loyd = {
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
}
alice = {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
}
tyler = {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]
}
students = [lloyd, alice, tyler]

6.4 For the Record


Excellent. Now you need a hard copy document with all of your
students’ grades.
animal_sounds = {
"cat": ["meow", "purr"],
"dog": ["woof", "bark"],
"fox": [],
}
print animal_sounds["cat"]
The example above is just to remind you how to create a dictionary
and then to access the item stored by the "cat" key.
Instructions

1.

for each student in your students list, print out that student‘s data, as


follows:

 print the student‘s name

 print the student‘s homework

 print the student‘s quizzes
 print the student‘s tests

for student in students:
  print student
for student in students:
  print student["name"]
  print student["homework"]
  print student["quizzes"]
  print student["tests"]
PRACTICAR

6.5 It's Okay to be Average


When teaching a class, it’s important to take the students’ averages in
order to assign grades.
5 / 2
# 2

5.0 / 2
# 2.5

float(5) / 2
# 2.5
The above example is a reminder of how division works in Python.

 When you divide an integer by another integer, the result is


always an integer (rounded down, if needed).

 When you divide a float by an integer, the result is always a float.

 To divide two integers and end up with a float, you must first
use float() to convert one of the integers to a float.

Instructions

1.

Write a function average that takes a list of numbers and returns the


average.

 Define a function called average that has one argument, numbers.

 Inside that function, call the built-in sum() function with


the numbers list as a parameter. Store the result in a variable
called total.
 Like the example above, use float() to convert total and store the
result in total.

 Divide total by the length of the numbers list. Use the built-


in len() function to calculate that.

 Return that result.

def average(numbers):
  total = sum(numbers)
  total = float(total)
  return total / len(numbers)

PRACTICAR

6.6 Just Weight and See


Great! Now we need to compute a student’s average using weighted
averages.
cost = {
"apples": [3.5, 2.4, 2.3],
"bananas": [1.2, 1.8],
}

return 0.9 * average(cost["apples"]) + \


0.1 * average(cost["bananas"])

1. In the above example, we create a dictionary called cost that


contains the costs of some fruit.

2. Then, we calculate the average cost of apples and the average


cost of bananas. Since we like apples much more than we like
bananas, we weight the average cost of apples by 90% and the
average cost of bananas by 10%.

The \ character is a continuation character. The following line is


considered a continuation of the current line.
Instructions

1.

Write a function called get_average that takes a student dictionary


(like lloyd, alice, or tyler) as input and returns his/her weighted average.
 Define a function called get_average that takes one argument
called student.

 Make a variable homework that stores


the average() of student["homework"].

 Repeat the above step for “quizzes” and “tests”.

 Multiply the 3 averages by their weights and return the sum of


those three. Homework is 10%, quizzes are 30% and tests are
60%.

def get_average(student):
  homework = average(student["homework"])
  quizzes = average(student["quizzes"])
  tests = average(student["tests"])
  return 0.1*homework + \ 
  0.3*quizzes + \ 
  0.6*tests

Respuesta correcta
def get_average(student):
  homework = average(student["homework"])
  quizzes = average(student["quizzes"])
  tests = average(student["tests"])
  
  total = homework *.1 + quizzes * .3 + tests * .6
  return total

6.7 Sending a Letter


Great work!

Now let’s write a get_letter_grade function that takes a number score as


input and returns a string with the letter grade that that student should
receive.
Instructions

1.

Define a new function called get_letter_grade that has one argument


called score. Expect score to be a number.
Inside your function, test score using a chain of if: / elif: /
else: statements, like so:

 If score is 90 or above: return "A"

 Else if score is 80 or above: return "B"

 Else if score is 70 or above: return "C"

 Else if score is 60 or above: return "D"

 Otherwise: return "F"

Finally, test your function!

Print the resulting letter grade with print. Call


the get_letter_grade function and pass in get_average(lloyd).

def get_letter_grade(score):
  if score >= 90:
    return "A"
  elif score >=80:
    return "B"
  elif score >=70:
    return "C"
  elif score >=60:
    return "D"
  else:
    return "F"
  
print get_letter_grade(get_average(lloyd))

B
6.8 Part of the Whole
Good! Now let’s calculate the class average.

You need to get the average for each student and then calculate the
average of those averages.
Instructions

1.
Define a function called get_class_average that has one
argument class_list. You can expect class_list to be a list containing
your three students.

First, make an empty list called results.

For each student item in the class_list, calculate get_average(student) and


then call results.append() with that result.

Finally, return the result of calling average() with results.

def get_class_average(class_list):
  results=[]
for student in class_list:
  get_average(student)
  results.append(get_average(student))
  return average(results)

Comp. response
def get_class_average(class_list):
  results = []
  for student in class_list:
    student_avg = get_average(student)
    results.append(student_avg)
  return average(results)
PRACTICAR

6.9 How is Everybody Doing?


Awesome! You’re doing great. Now let’s use the functions you’ve
created to check on the grade of the class overall.
Instructions

1.

Create a list called students and fill it with the three students, alice, lloyd,


and tyler.
2.

Find the average grade of the class. Print this numerical grade to the
terminal.
Stuck? Get a hint
3.

Finally, determine the letter grade for the class’s average and print it to
the terminal.

students = [lloyd, alice, tyler]

avg = get_class_average(students)
print(avg)
print(get_letter_grade(avg))
PRACTICAR
In this last exercise we call the functions and execute them.

lloyd = {
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
}
alice = {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
}
tyler = {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
  total = sum(numbers)
  total = float(total)
  return total/len(numbers)

def get_average(student):
  homework = average(student["homework"])
  quizzes = average(student["quizzes"])
  tests = average(student["tests"])
  return 0.1 * homework + 0.3 * quizzes + 0.6 * tests

def get_letter_grade(score):
  if score >= 90:
    return "A"
  elif score >=80:
    return "B"
  elif score >=70:
    return "C"
  elif score >=60:
    return "D"
  else:
    return "F"

def get_class_average(class_list):
  results = []
  for student in class_list:
    student_avg = get_average(student)
    results.append(student_avg)
  return average(results)

students = [lloyd, alice, tyler]

avg = get_class_average(students)
print(avg)
print(get_letter_grade(avg))

PRACTICAR
7 LISTS AND FUNCTIONS
7.1 List accessing
This exercise goes over just pulling information from a list, which we’ve
covered in a previous section!
Instructions

1.

Please add the code to print out the second element in the list.

n = [1, 3, 5]

# Add your code below
print n[1]

7.2 List element modification


You’ve already learned how to modify elements of a list in a previous
section. This exercise is just a recap of that!
Instructions
1.

On line 3, multiply the second element of the n list by 5

Overwrite the second element with that result.

Make sure to print the list when you are done!

n = [1, 3, 5]
# Do your multiplication here
number= n[1]*5
n.remove(3)
n.append(number)
print n

Correct
n = [1, 3, 5]
# Do your multiplication here
n[1] = n[1] * 5
print n

7.3 Appending to a list


Here, we’ll quickly recap how to .append() elements to the end of a list.
Instructions

1.

Append the number 4 to the end of the list n.

n = [1, 3, 5]
# Append the number 4 here
n.append(4)
print n

[1, 3, 5, 4]

7.4 Removing elements from lists


This exercise will expand on ways to remove items from a list. You
actually have a few options. For a list called n:
1. n.pop(index) will remove the item at index from the list and return
it to you:
2. n = [1, 3, 5]
3. n.pop(1)
4. # Returns 3 (the item at index 1)
5. print n
# prints [1, 5]
6. n.remove(item) will remove the actual item if it finds it:
7. n.remove(1)
8. # Removes 1 from the list,
9. # NOT the item at index 1
10. print n
# prints [3, 5]
11. del(n[1]) is like .pop in that it will remove the item at the given
index, but it won’t return it:
12. del(n[1])
13. # Doesn't return anything
14. print n
# prints [1, 5]
Instructions

1.

Remove the first item from the list n using either .pop(), .remove(), or del.

n = [1, 3, 5]
# Remove the first item in the list here
n.pop(0)
print n

[3, 5]

7.5 Changing the functionality of a function


In this exercise, you will just be making a minor change to a function to
change what that function does.
Instructions

1.

Change the function so the given argument is multiplied by 3 and


returned.

number = 5
def my_function(x):
    return x * 3

print my_function(number)

7.6 More than one argument


This exercise will recap how to use more than one argument in a
function.
Instructions

1.

Define a function called add_function that has 2 parameters x and y and


adds them together.

m = 5
n = 13
# Add add_function here!
def add_function(x,y):
  print add_function(m, n)

m = 5
n = 13
# Add add_function here!
def add_function(x, y):
  return x + y

print add_function(m, n)
Practicar

7.7 Strings in functions


This is a basic recap on using strings in functions.
Instructions

1.

Write a function called string_function that takes in a string argument (s)


and then returns that argument concatenated with the word 'world'.
Don’t add a space before world!

n = "Hello"
# Your function here!
def string_function(s):
  return s + "world"

print string_function(n)

7.8 Passing a list to a function


You pass a list to a function the same way you pass any other
argument to a function.
Instructions

1.

Click Run to see that using a list as an argument in a function is


essentially the same as using just a number or string!

def list_function(x):
    return x

n = [3, 5, 7]
print list_function(n)

[3, 5, 7]

7.9 Using an element from a list in a function


Passing a list to a function will store it in the argument (just like with a
string or a number!)
def first_item(items):
print items[0]

numbers = [2, 7, 9]
first_item(numbers)

1. In the example above, we define a function called first_item. It


has one argument called items.

2. Inside the function, we print out the item stored at index zero


of items.

3. After the function, we create a new list called numbers.


4. Finally, we call the first_item function with numbers as its argument,
which prints out 2.

Instructions

1.

Change line 2 so that list_function returns only the item stored in index


one of x, rather than the entire x list.

def list_function(x):
    return x[1]

n = [3, 5, 7]
print list_function(n)

7.10 Modifying an element of a list in a function


Modifying an element in a list in a function is the same as if you were
just modifying an element of a list outside a function.
def double_first(n):
n[0] = n[0] * 2

numbers = [1, 2, 3, 4]
double_first(numbers)
print numbers

1. We create a list called numbers.

2. We use the double_first function to modify that list.

3. Finally, we print out [2, 2, 3, 4]

When we pass a list to a function and modify that list, like in


the double_first function above, we end up modifying the original list.
Instructions

1.

Change list_function to:

 Add 3 to the item at index 1 of the list.


 Store the result back into index 1.

 Return the list.

def list_function(x):
  x[1]=x[1]+3
  return x

n = [3, 5, 7]
print list_function(n)

[3, 8, 7]

7.11 List manipulation in functions


You can also append or delete items of a list inside a function just as if
you were manipulating the list outside a function.
my_list = [1, 2, 3]
my_list.append(4)
print my_list
# prints [1, 2, 3, 4]
The example above is just a reminder of how to append items to a list.
Instructions

1.

Define a function called list_extender that has one parameter lst.

Inside the function, append the number 9 to lst.

Then return the modified list.

n = [3, 5, 7]
# Add your function here
def list_extender(lst):
  lst.append(9)
  return lst

print list_extender(n)

[3, 5, 7, 9]
7.12 Printing out a list item by item in a function
This exercise will go over how to utilize every element in a list in a
function. You can use the existing code to complete the exercise and
see how running this operation inside a function isn’t much different
from running this operation outside a function.

Don’t worry about the range function quite yet—we’ll explain it later in


this section.
Instructions

1.

Define a function called print_list that has one argument called x.

Inside that function, print out each element one by one. Use the
existing code as a scaffold.

Then call your function with the argument n.


n = [3, 5, 7]

for i in range(0, len(n)):
    print n[i]
def print_list(x):
  for i in x:
    print x[i]
print_list(n)

n = [3, 5, 7]

def print_list(x):
  for i in range(0, len(x)):
    print x[i]
    
print_list(n)

n = [3, 5, 7]

def print_list(x):
  for i in range(0, len(x)):
    print x[i]
    
print_list(n)
3
5
7

7.13 Modifying each element in a list in a function


This exercise shows how to modify each element in a list. It is useful to
do so in a function as you can easily put in a list of any length and get
the same functionality. As you can see, len(n) is the length of the list.
Instructions

1.

Create a function called double_list that takes a single


argument x (which will be a list) and multiplies each element by 2 and
returns that list. Use the existing code as a scaffold.

n = [3, 5, 7]
def double_list(x):
  for i in range(0, len(x)):
   x[i] = x[i] * 2
  return x
# Don't forget to return your new list!

print double_list(n)

[6, 10, 14]

7.14 Passing a range into a function


Okay! Range time. The Python range() function is just a shortcut for
generating a list, so you can use ranges in all the same places you can
use lists.
range(6) # => [0, 1, 2, 3, 4, 5]
range(1, 6) # => [1, 2, 3, 4, 5]
range(1, 6, 3) # => [1, 4]
The range function has three different versions:

1. range(stop)

2. range(start, stop)

3. range(start, stop, step)


In all cases, the range() function returns a list of numbers from start up
to (but not including) stop. Each item increases by step.

If omitted, start defaults to 0 and step defaults to 1.


Instructions

1.

On line 6, replace the ____ with a range() that returns a list containing [0,


1, 2].

def my_function(x):
  for i in range(0, len(x)):
    x[i] = x[i]
  return x

print my_function(range(3)) # Add your range between the parentheses!

[0, 1, 2]

7.15 Iterating over a list in a function


Now that we’ve learned about range, we have two ways of iterating
through a list.

Method 1 - for item in list:

for item in list:


print item
Method 2 - iterate through indexes:
for i in range(len(list)):
print list[i]
Method 1 is useful to loop through the list, but it’s not possible to
modify the list this way.

Method 2 uses indexes to loop through the list, making it possible to


also modify the list if needed. Since we aren’t modifying the list, feel
free to use either one on this lesson!
Instructions

1.

Create a function that returns the sum of a list of numbers.


 On line 3, define a function called total that accepts one
argument called numbers. It will be a list.

 Inside the function, create a variable called result and set it to


zero.

 Using one of the two methods above, iterate through


the numbers list. For each number, add it to result.

 Finally, return result.

n = [3, 5, 7]

def total(numbers):
  result=0
  for i in numbers:
    result= result + i
    return result

CC response
n = [3, 5, 7]

def total(numbers):
  result = 0
  for i in range(0,len(numbers)):
    result += numbers[i]
  return result

Practicar

Using strings in lists in functions

Now let’s try working with strings!


for item in list:
print item

for i in range(len(list)):
print list[i]
The example above is just a reminder of the two methods for iterating
over a list.
Instructions

1.

Create a function that concatenates strings.

 Define a function called join_strings accepts an argument


called words. It will be a list.

 Inside the function, create a variable called result and set it to "",


an empty string.

 Iterate through the words list and concatenate each word to result.

 Finally, return the result.

Don’t add spaces between the joined strings!

n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
  result= ""
  for i in range(0,len(words)):
    result = result + words[i]
    return result

print join_strings(n)

n = ["Michael", "Lieberman"]
# Add your function here

def join_strings(words):
  result = ""
  for word in words:
    result += word
  return result

print join_strings(n)

MichaelLieberman
7.16 Using two lists as two arguments in a function
Using multiple lists in a function is no different from just using multiple
arguments in a function!
a = [1, 2, 3]
b = [4, 5, 6]
print a + b
# prints [1, 2, 3, 4, 5, 6]
The example above is just a reminder of how to concatenate two lists.
Instructions

1.

Create a function that joins two lists together.

 On line 5, define a function called join_lists that has two


arguments, x and y. They will both be lists.

 Inside that function, return the result of


concatenating x and y together.

m = [1, 2, 3]
n = [4, 5, 6]

# Add your code here!
def join_lists(x, y):
  return x + y
  

print join_lists(m, n)

[1, 2, 3, 4, 5, 6]

7.17 Using a list of lists in a function


Finally, this exercise shows how to make use of a single list that
contains multiple lists and how to use them in a function.
list_of_lists = [[1, 2, 3], [4, 5, 6]]
for lst in list_of_lists:
for item in lst:
print item

1. In the example above, we first create a list containing two items,


each of which is a list of numbers.

2. Then, we iterate through our outer list.

3. For each of the two inner lists (as lst), we iterate through the
numbers (as item) and print them out.

We end up printing out:


1
2
3
4
5
6
Instructions

1.

Create a function called flatten that takes a single list and concatenates


all the sublists that are part of it into a single list.

 On line 3, define a function called flatten with one argument


called lists.

 Make a new, empty list called results.

 Iterate through lists. Call the looping variable numbers.

 Iterate through numbers.

 For each number, .append() it to results.

 Finally, return results from your function.

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
  results = []
  for numbers in lists:
    for item in numbers:
      results.append(lists)
      return results

print flatten(n)

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here

def flatten(lists):
  results = []
  for numbers in lists:
    for number in numbers:
      results.append(number)
  return results

print flatten(n)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

7.18 BATTLESHIP!
7.18.1 Getting Our Feet Wet
The first thing we need to do is to set up the game board.
Instructions

1.

Create a variable board and set it equal to an empty list.

7.18.2 Make a List


Good! Now we’ll use a built-in Python function to generate our board,
which we’ll make into a 5 x 5 grid of all "O"s, for “ocean.”
print ["O"] * 5
will print out ['O', 'O', 'O', 'O', 'O'], which is the basis for a row of our
board.
We’ll do this five times to make five rows. (Since we have to do this five
times, it sounds like a loop might be in order.)
Instructions

1.

Create a 5 x 5 grid initialized to all ‘O’s and store it in board.

 Use range() to loop 5 times.

 Inside the loop, .append() a list containing 5 "O"s to board, just like


in the example above.

Note that these are capital letter “O” and not zeros.

board = []
def battle(x):
  for item in x:
    x.append("O"*5)
print battle(board)

Computer response, Practice!!!!!


board = []
for i in range(5):
  board.append(['O'] * 5)

7.18.3 Check it Twice


Great job! Now that we’ve built our board, let’s show it off.

Throughout our game, we’ll want to print the game board so that the
player can see which locations they have already guessed. Regularly
printing the board will also help us debug our program.

The easiest way to print the board would be to have Python display it
for us using the print command. Let’s give that a try and see what the
results look like—is this a useful way to print our board for Battleship?
Instructions

1.

Use the print command to display the contents of the board list.


7.18.4 Custom Print
Now we can see the contents of our list, but clearly it would be easier
to play the game if we could print the board out like a grid with each
row on its own line.

We can use the fact that our board is a list of lists to help us do this.
Let’s set up a for loop to go through each of the elements in the outer
list (each of which is a row of our board) and print them.
Instructions

1.

First, delete your existing print statement.

Then, define a function named print_board with a single


argument, board_in.

Inside the function, write a for loop to iterates through


each row in board and print it to the screen.

Call your function with board to make sure it works.


board = []
for i in range(5):
  board.append(['O'] * 5)
def print_board(board_in):
  for row in board_in:
    print row
print print_board(board)

['O', 'O', 'O', 'O', 'O']


['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
None

7.18.5 Printing Pretty


We’re getting pretty close to a playable board, but wouldn’t it be nice
to get rid of those quote marks and commas? We’re storing our data
as a list, but the player doesn’t need to know that!
letters = ['a', 'b', 'c', 'd']
print " ".join(letters)
print "---".join(letters)

1. In the example above, we create a list called letters.

2. Then, we print a b c d. The .join method uses the string to


combine the items in the list.

3. Finally, we print a---b---c---d. We are calling the .join function on


the "---" string.

We want to turn each row into "O O O O O".


Instructions

1.

Inside your function, inside your for loop, use " " as the separator


to .join the elements of each row.

7.18.6 Hide...
Excellent! Now, let’s hide our battleship in a random location on the
board.

Since we have a 2-dimensional list, we’ll use two variables to store the
ship’s location, ship_row and ship_col.
from random import randint
coin = randint(0, 1)
dice = randint(1, 6)

1. In the above example, we first import the randint(low,


high) function from the random module.

2. Then, we generate either zero or one and store it in coin.

3. Finally, we generate a number from one to six inclusive.

Let’s generate a random_row and random_col from zero to four!


Instructions

1.

Define two new functions, random_row and random_col, that each


take board_in as input.
These functions should return a random row index and a random
column index from your board, respectively. Use randint(0, len(board_in)
- 1).

Call each function on board.


def random_row(board_in):
  randint(0, len(board_in)-1)
def random_col(board_in):
  randint(0, len(board_in)-1)
random_row(board)
random_col(board)

Computer response, Practice!!!


def random_row(board_in):
  return randint(0, len(board_in) - 1)
    
def random_col(board_in):
  return randint(0, len(board_in) - 1)

random_row(board)
random_col(board)

from random import randint 

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board_in):
  for row in board_in:
    print " ".join(row)

# Add your code below!

def random_row(board_in):
  return randint(0, len(board_in) - 1)
    
def random_col(board_in):
  return randint(0, len(board_in) - 1)
random_row(board)
random_col(board)

7.18.7 .and Seek!


Good job! For now, let’s store coordinates for the ship in the
variables ship_row and ship_col. Now you have a hidden battleship in
your ocean! Let’s write the code to allow the player to guess where it is.
number = raw_input("Enter a number: ")
if int(number) == 0:
print "You entered 0"
raw_input asks the user for input and returns it as a string. But we’re
going to want to use integers for our guesses! To do this, we’ll wrap
the raw_inputs with int() to convert the string to an integer.
Instructions

1.

Create a new variable called guess_row and set it to int(raw_input("Guess


Row: ")).

Create a new variable called guess_col and set it to int(raw_input("Guess


Col: ")).

Click Run and then answer the prompts by typing in a number and


pressing Enter (or Return on some computers).

from random import randint

board = []

for x in range(0,5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

def random_row(board):
  return randint(0, len(board) - 1)
def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

# Add your code below!
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))

7.18.8 It's Not Cheating—It's Debugging!


Awesome! Now we have a hidden battleship and a guess from our
player. In the next few steps, we’ll check the user’s guess to see if they
are correct.

While we’re writing and debugging this part of the program, it will be
helpful to know where that battleship is hidden. Let’s add
a print statement that displays the location of the hidden ship.

Of course, we’ll remove this output when we’re finished debugging


since if we left it in, our game wouldn’t be very challenging. :)
Instructions
1.

Before the lines prompting the user for input:

Print the value of ship_row.

Print the value of ship_col.


from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
# Add your code below!
print ship_row
print ship_col

guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))

1
2
Guess Row:

7.18.9 You win!


Okay—now for the fun! We have the actual location of the ship and the
player’s guess so we can check to see if the player guessed right.

For a guess to be right, guess_col should be equal


to ship_col and guess_row should be equal to ship_row.
if guess_col == 0 and guess_row == 0:
print "Top-left corner."
The example above is just a reminder about if statements.
Instructions

1.

On line 29, add an if to check


if guess_row equals ship_row and guess_col equals ship_col.

If that is the case, please print out "Congratulations! You sank my


battleship!"

When you run this code, be sure to enter integer guesses in the panel
where it asks for “Guess Row” and then “Guess Col”.
7.18.10 Danger, Will Robinson!!
Great! Of course, the player isn’t going to guess right all the time, so
we also need to handle the case where the guess is wrong.
print board[2][3]
The example above prints out "O", the element in the 3rd row and 4th
column.
Instructions

1.

Add an else under the if we wrote in the previous step.

Print out "You missed my battleship!"

Set the list element at guess_row, guess_col to "X".

As the last line in your else statement, call print_board(board) again so


you can see the "X".Make sure to enter a col and row that is on the
board!
from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))
print ship_row
print ship_col

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
  print "Congratulations! You sank my battleship!"
else:
  "You missed my battleship"
  guess_row = "X"
  guess_col = "X"
  print_board(board)

Computer response (Practice)

from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
  print "Congratulations! You sank my battleship!"  
else:
  print "You missed my battleship!"
  board[guess_row][guess_col] = "X"
  print_board(board)

7.18.11 Bad Aim


Great job! Now we can handle both correct and incorrect guesses from
the user. But now let’s think a little bit more about the “miss” condition.

1. They can enter a guess that’s off the board.

2. They can guess a spot they’ve already guessed.

3. They can just miss the ship.

We’ll add these tests inside our else condition. Let’s build the first case
now!
if x not in range(8) or \
y not in range(3):
print "Outside the range"
The example above checks if either x or y are outside those ranges.
The \ character just continues the if statement onto the next line.
Instructions
1.

Add a new if statement that is nested under the else.

Like the example above, it should check if guess_row is not


in range(5) or guess_col is not in range(5).

If that is the case, print out "Oops, that's not even in the ocean."

After your new if statement, add an else that contains your existing


handler for an incorrect guess. Don’t forget to indent the code!

7.18.12 Not Again!


Great! Now let’s handle the second type of incorrect guess: the player
guesses a location that was already guessed. How will we know that a
location was previously guessed?
print board[guess_row][guess_col]
The example above will print an 'X' if already guessed or
an 'O' otherwise.
Instructions

1.

Add an elif to see if the guessed location already has an ‘X’ in it.

If it has, print "You guessed that one already."

Computer response

from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
  print "Congratulations! You sank my battleship!"   
else:
  if guess_row not in range(5) or \
    guess_col not in range(5):
    print "Oops, that's not even in the ocean."
  elif (board[guess_row][guess_col] == 'X'):
    print "You guessed that one already."
  else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
  print_board(board)

7.18.13 Test Run


Congratulations! Now you should have a game of Battleship! that is
fully functional for one guess.

Make sure you play it a couple of times and try different kinds of
incorrect guesses. This is a great time to stop and do some serious
debugging.

In the next step, we’ll move on and look at how to give the user 4
guesses to find the battleship.
Instructions

1.

Thoroughly test your game. Make sure you try a variety of different
guesses and look for any errors in the syntax or logic of your program.

Write al the code againg and describe every code function

7.18.14 Play It, Sam


You can successfully make one guess in Battleship! But we’d like our
game to allow the player to make up to 4 guesses before they lose.
for turn in range(4):
# Make a guess
# Test that guess
We can use a for loop to iterate through a range. Each iteration will be
a turn.
Instructions

1.
Add a for loop that repeats the guessing and checking part of your
game for 4 turns, like the example above.

At the beginning of each iteration, print "Turn", turn + 1 to let the


player know what turn they are on.

Indent everything that should be repeated.

from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

# Everything from here on should be in your for loop
# don't forget to properly indent!
for turn in range(4):
  print "Turn", turn + 1
  guess_row = int(raw_input("Guess Row: "))
  guess_col = int(raw_input("Guess Col: "))

  if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"   
  else:
    if guess_row not in range(5) or \
      guess_col not in range(5):
      print "Oops, that's not even in the ocean."
    elif board[guess_row][guess_col] == "X":
      print( "You guessed that one already." )
    else:
      print "You missed my battleship!"
      board[guess_row][guess_col] = "X"
    print_board(board)

7.18.15 Game Over


If someone runs out of guesses without winning right now, the game
just exits. It would be nice to let them know why.

Since we only want this message to display if the user guesses wrong
on their last turn, we need to think carefully about where to put it.

1. We’ll want to put it under the else that accounts for misses

2. We’ll want to print the message no matter what the cause of the
miss

3. Since our turn variable starts at 0 and goes to 3, we will want to


end the game when turn equals 3.

Instructions

1.

Add an if statement that checks to see if the user is out of guesses.

 Put it under the else that accounts for misses.

 Put it after the if/elif/else statements that check for the reason


the player missed. We want "Game Over" to print regardless of the
reason.

If turn equals 3, print "Game Over".

from random import randint
board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

# Everything from here on should be in your for loop
# don't forget to properly indent!
for turn in range(4):
  print "Turn", turn + 1
  guess_row = int(raw_input("Guess Row: "))
  guess_col = int(raw_input("Guess Col: "))

  if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"   
  else:
    if guess_row not in range(5) or \
      guess_col not in range(5):
      print "Oops, that's not even in the ocean."
    elif board[guess_row][guess_col] == "X":
      print( "You guessed that one already." )
    else:
      print "You missed my battleship!"
    if turn == 3:
      print "Game Over"
    board[guess_row][guess_col] = "X"
    print_board(board)

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
2
3
Turn 1
Guess Row: 2
Guess Col: 2
You missed my battleship!
O O O O O
O O O O O
O O X O O
O O O O O
O O O O O
Turn 2
Guess Row: 3
Guess Col: 3
You missed my battleship!
O O O O O
O O O O O
O O X O O
O O O X O
O O O O O
Turn 3
Guess Row: 4
Guess Col: 4
You missed my battleship!
O O O O O
O O O O O
O O X O O
O O O X O
O O O O X
Turn 4
Guess Row: 3
Guess Col: 4
You missed my battleship!
Game Over
O O O O O
O O O O O
O O X O O
O O O X X
O O O O X

7.18.16 A Real Win


Almost there! We can play Battleship!, but you’ll notice that when you
win, if you haven’t already guessed 4 times, the program asks you to
enter another guess. What we’d rather have happen is for the program
to end—it’s no fun guessing if you know you’ve already sunk the
Battleship!

We can use the break command to get out of a for loop.


Instructions

1.

Add a break under the win condition to end the loop after a win.

from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)

def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

# Everything from here on should be in your for loop
# don't forget to properly indent!
for turn in range(4):
  print "Turn", turn + 1
  guess_row = int(raw_input("Guess Row: "))
  guess_col = int(raw_input("Guess Col: "))

  if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
    break   
  else:
    if guess_row not in range(5) or \
      guess_col not in range(5):
      print "Oops, that's not even in the ocean."
    elif board[guess_row][guess_col] == "X":
      print( "You guessed that one already." )
    else:
      print "You missed my battleship!"
    if turn == 3:
      print "Game Over"
    board[guess_row][guess_col] = "X"
    print_board(board)

7.18.17 To Your Battle Stations!


Congratulations! You have a fully functional Battleship game! Play it a
couple of times and get your friends to try it out, too. (Don’t forget to
go back and remove the debugging output that gives away the
location of the battleship!)

You may want to take some time to clean up and document your code
as well.
Instructions

1.

When you are done playing Battleship! and are ready to move on, click
Run.

from random import randint

board = []

for x in range(0, 5):
  board.append(["O"] * 5)
def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

# Everything from here on should be in your for loop
# don't forget to properly indent!
for turn in range(4):
  print "Turn", turn + 1
  guess_row = int(raw_input("Guess Row: "))
  guess_col = int(raw_input("Guess Col: "))

  if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
    break   
  else:
    if guess_row not in range(5) or \
      guess_col not in range(5):
      print "Oops, that's not even in the ocean."
    elif board[guess_row][guess_col] == "X":
      print( "You guessed that one already." )
    else:
      print "You missed my battleship!"
    if turn == 3:
      print "Game Over"
    board[guess_row][guess_col] = "X"
    print_board(board)
7.18.18 Extra Credit
You can also add on to your Battleship! program to make it more complex and
fun to play. Here are some ideas for enhancements—maybe you can think of
some more!

1. Make multiple battleships: you’ll need to be careful because you need to


make sure that you don’t place battleships on top of each other on the
game board. You’ll also want to make sure that you balance the size of
the board with the number of ships so the game is still challenging and
fun to play.
2. Make battleships of different sizes: this is trickier than it sounds. All the
parts of the battleship need to be vertically or horizontally touching and
you’ll need to make sure you don’t accidentally place part of a ship off
the side of the board.
3. Make your game a two-player game.
4. Use functions to allow your game to have more features like rematches,
statistics and more!
Some of these options will be easier after we cover loops in the next lesson.
Think about coming back to Battleship! after a few more lessons and see what
other changes you can make!

8 LOOPS
8.1 While you're here
The while loop is similar to an if statement: it executes the code inside
of it if some condition is true. The difference is that the while loop will
continue to execute as long as the condition is true. In other words,
instead of executing if something is true, it executes while that thing is
true.

Line 6 decides when the loop will be executed. So, “as long as count is
less than 5,” the loop will continue to execute. Line 8 increases count by
1. This happens over and over until count equals 5.
Instructions

1.

Change the loop so that it counts from 0 up to 9 (inclusive).


Be careful not to alter or remove the count += 1 statement. If your
program has no way to increase count, your loop could go on forever
and become an infinite loop which could crash your computer/browser!

count = 0

if count <= 9:
  print "Hello, I am an if statement and count is", count

while count <= 9:
  print "Hello, I am a while and count is", count
  count += 1

Hello, I am an if statement and count is 0


Hello, I am a while and count is 0
Hello, I am a while and count is 1
Hello, I am a while and count is 2
Hello, I am a while and count is 3
Hello, I am a while and count is 4
Hello, I am a while and count is 5
Hello, I am a while and count is 6
Hello, I am a while and count is 7
Hello, I am a while and count is 8
Hello, I am a while and count is 9

8.2 Condition
The condition is the expression that decides whether the loop is going
to continue being executed or not. There are 5 steps to this program:

1. The loop_condition variable is set to True


2. The while loop checks to see if loop_condition is True. It is, so the
loop is entered.
3. The print statement is executed.
4. The variable loop_condition is set to False.
5. The while loop again checks to see if loop_condition is True. It is not,
so the loop is not executed a second time.
Instructions

1.
See how the loop checks its condition, and when it stops executing?
When you think you’ve got the hang of it, click Run to continue.

loop_condition = True

while loop_condition:
  print "I am a loop"
  loop_condition = False

I am a loop

8.3 While you're at it


Inside a while loop, you can do anything you could do elsewhere,
including arithmetic operations.
Instructions

1.

Create a while loop that prints out all the numbers from 1 to 10 squared
(1, 4, 9, 16, … , 100), each on their own line.

 Fill in the blank space so that our while loop goes


from 1 to 10 inclusive.

 Inside the loop, print the value of num squared. The syntax for
squaring a number is num ** 2.

 Increment num.

num = 1

while num <= 10:
  print num**2
  num += 1

1
4
9
16
25
36
49
64
81
100

8.4 Simple errors


A common application of a while loop is to check user input to see if it
is valid. For example, if you ask the user to enter y or n and they instead
enter 7, then you should re-prompt them for input.
Instructions

1.

Fill in the loop condition so the user will be prompted for a choice over
and over while choice does not equal 'y' and choice does not equal 'n'.

choice = raw_input('Enjoying the course? (y/n)')

while choice != 'y' and choice != 'n':  # Fill in the condition (before t
he colon)
  choice = raw_input("Sorry, I didn't catch that. Enter again: ")

8.5 Infinite loops


An infinite loop is a loop that never exits. This can happen for a few
reasons:

1. The loop condition cannot possibly be false (e.g. while 1 != 2)


2. The logic of the loop prevents the loop condition from becoming
false.
Example:

count = 10
while count > 0:
  count += 1 # Instead of count -= 1
Instructions

1.

The loop in the editor has two problems: it’s missing a colon (a syntax
error) and count is never incremented (logical error). The latter will result
in an infinite loop, so be sure to fix both before running!

count = 0
while count < 10: # Add a colon
  print count
  # Increment count
  count += 1

8.6 Break
The break is a one-line statement that means “exit the current loop.” An
alternate way to make our counting loop exit and stop executing is
with the break statement.

 First, create a while with a condition that is always true. The


simplest way is shown.
 Using an if statement, you define the stopping condition. Inside
the if, you write break, meaning “exit the loop.”
The difference here is that this loop is guaranteed to run at least once.
Instructions

1.

See what the break does? Feel free to mess around with it (but make
sure you don’t cause an infinite loop)! Click Run when you’re ready to
continue.

count = 0

while True:
  print count
  count += 1
  if count >= 10:
    break

0
1
2
3
4
5
6
7
8
9
8.7 While / else
Something completely different about Python is
the while/else construction. while/else is similar to if/else, but there is a
difference: the else block will execute anytime the loop condition is
evaluated to False. This means that it will execute if the loop is never
entered or if the loop exits normally. If the loop exits as the result of
a break, the else will not be executed.

In this example, the loop will break if a 5 is generated, and the else will


not execute. Otherwise, after 3 numbers are generated, the loop
condition will become false and the else will execute.
Instructions

1.

Click Run to see while/else in action!

import random

print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"

count = 0
while count < 3:
  num = random.randint(1, 6)
  print num
  if num == 5:
    print "Sorry, you lose!"
    break
  count += 1
else:
  print "You win!"

Lucky Numbers! 3 numbers will be generated.


If one of them is a '5', you lose!
2
5
Sorry, you lose!
8.8 Your own while / else
Now you should be able to make a game similar to the one in the last
exercise. The code from the last exercise is below:

count = 0
while count < 3:
  num = random.randint(1, 6)
  print num
  if num == 5:
    print "Sorry, you lose!"
    break
  count += 1
else:
  print "You win!"
In this exercise, allow the user to guess what the number is 3 times.

guess = int(raw_input("Your guess: "))
Remember, raw_input turns user input into a string, so we use int() to
make it a number again.
Instructions

1.

Use a while loop to let the user keep guessing so long as guesses_left is


greater than zero.

Ask the user for their guess, just like the second example above.

If they guess correctly, print "You win!" and break.

Decrement guesses_left by one.

Use an else: case after your while loop to print "You lose.".

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
  guess = int(raw_input("Your guess: "))
  if guess == random_number:
    print "You win!"
    break
  guesses_left -= 1
else:
  print "You lose!"

8.9 For your health


An alternative way to loop is the for loop. The syntax is as shown in the
code editor. This example means “for each number i in the range 0 - 9,
print i“.
Instructions

1.

Make the loop print the numbers from 0 to 19 instead of 0 to 9.


print "Counting..."

for i in range(20):
  print i

Counting...
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
8.10 For your hobbies
This kind of loop is useful when you want to do something a certain
number of times, such as append something to the end of a list.
Instructions

1.

Create a for loop that prompts the user for a hobby 3 times.

Save the result of each prompt in a hobby variable

append each one to hobbies.

print hobbies after your for loop

Make sure to answer the prompts in the terminal when testing your
code!
hobbies = []

# Add your code below!
for i in range(3):
  i = raw_input("Write a hobby ")
  hobbies.append(i)
print hobbies

Write a hobby swimming


Write a hobby running
Write a hobby listenin to music
[u'swimming ', u'running', u'listenin to music']

8.11 For your strings


Using a for loop, you can print out each individual character in a string.

The example in the editor is almost plain English: “for each


character c in thing, print c“.
Instructions

1.

Add a second for loop so that each character in word is printed one at a


time.
thing = "spam!"

for c in thing:
  print c

word = "eggs!"

# Your code here!
for v in word:
  print v

s
p
a
m
!
e
g
g
s
!

8.12 For your A


String manipulation is useful in for loops if you want to modify some
content in a string.

word = "Marble"
for char in word:
  print char,
The example above iterates through each character in word and, in the
end, prints out M a r b l e.

The , character after our print statement means that our


next print statement keeps printing on the same line.
Instructions

1.

Let’s filter out the letter "A" from our string.

 Do the following for each character in the phrase.


 If char is an "A" or char is an "a", print "X", instead of char. Make
sure to include the trailing comma.

 Otherwise (else:), please print char, with the trailing comma.

phrase = "A bird in the hand..."

# Add your for loop
for char in phrase:
  if char == "A" or char == "a":
    print "X",
  else:
    print char,

#Don't delete this print statement!
print

X b i r d i n t h e h X n d . . .

8.13 For your lists


Perhaps the most useful (and most common) use of for loops is to go
through a list.

On each iteration, the variable num will be the next value in the list. So,
the first time through, it will be 7, the second time it will be 9,
then 12, 54, 99, and then the loop will exit when there are no more
values in the list.
Instructions

1.

Write a second for loop that goes through the numbers list and prints


each element squared, each on its own line.

numbers  = [7, 9, 12, 54, 99]

print "This list contains: "
for num in numbers:
  print num

# Add your loop below!
for num in numbers:
  print num ** 2

This list contains:


7
9
12
54
99
49
81
144
2916
9801
8.14 Looping over a dictionary
You may be wondering how looping over a dictionary would work.
Would you get the key or the value?

The short answer is: you get the key which you can use to get the
value.

d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
  if d[key] == 10:
    print "This dictionary has the value 10!"

1. First, we create a dictionary with strings as the keys and numbers


as the values.

2. Then, we iterate through the dictionary, each time storing the key
in key.

3. Next, we check if that key’s value is equal to 10.

4. If so, we print "This dictionary has the value 10!"

Instructions
1.

On line 5, print the key, followed by a space, followed by the value


associated with that key.

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
  # Your code here!
  print key, d[key]

a apple
c cherry
b berry

8.15 Counting as you go


A weakness of using this for-each style of iteration is that you don’t
know the index of the thing you’re looking at. Generally, this isn’t an
issue, but at times it is useful to know how far into the list you are.
Thankfully the built-in enumerate function helps with this.

enumerate works by supplying a corresponding index to each element in


the list that you pass it. Each time you go through the loop, index will
be one greater, and item will be the next item in the sequence. It’s very
similar to using a normal for loop with a list, except this gives us an
easy way to count how many items we’ve seen so far.
Instructions

1.

We don’t want the user to see things listed from index 0, since this
looks unnatural. Instead, the items should appear to start at index 1.
Modify the print statement to reflect this behavior. See the Hint for
help.

Hint
Instead of just printing index, print index + 1!

choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
  print index + 1, item

Your choices are:


1 pizza
2 pasta
3 salad
4 nachos

8.16 Multiple lists


It’s also common to need to iterate over two lists at once. This is where
the built-in zip function comes in handy.

zip will
create pairs of elements when passed two lists, and will stop at
the end of the shorter list.

zip can handle three or more lists as well!


Instructions

1.

Compare each pair of elements and print the larger of the two.

Hint
a is an element from list_a and b is an element of list_b.

You have two options: Use an if/else statement to compare the two


and print whichever is larger. Alternatively, you can use the max function
that you learned in unit 4.
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):
  # Add your code here!
  if a > b:
    print a
  else:
    print b

3
9
17
15
30

8.17 For / else


Just like with while, for loops may have an else associated with them.

In this case, the else statement is executed after the for, but only if


the for ends normally—that is, not with a break. This code
will break when it hits 'tomato', so the else block won’t be executed.
Instructions

1.

Click Run to see how for and else work together.

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
  if f == 'tomato':
    print 'A tomato is not a fruit!' # (It actually is.)
    break
  print 'A', f
else:
  print 'A fine selection of fruits!'

You have...
A banana
A apple
A orange
A tomato is not a fruit!

8.18 Change it up
As mentioned, the else block won’t run in this case, since break executes
when it hits 'tomato'.
Instructions

1.

Modify the code in the editor such that the for loop’s else statement is


executed.
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
  if f == 'onion':
    print 'An onion is not a fruit!' # (It actually is.)
    break
  print 'A', f
else:
  print 'A fine selection of fruits!'

You have...
A banana
A apple
A orange
A tomato
A pear
A grape
A fine selection of fruits!

Create your own

To wrap up this lesson, let’s create our own for/else statement from


scratch.
Instructions

1.

Build your for/else statement in the editor. Execution of the else branch


is optional, but your code should print a string of your choice to the
editor regardless.

8.19 PRACTICE MAKES PERFECT

8.19.1 Practice! Practice Practice!


The best way to get good at anything is a lot of practice. This lesson is full of
practice problems for you to work on. Each exercise will contain minimal
instructions to help you solve these problems. The goal is to help you take your
programming skills and apply them to real life problems.

The more challenging programs will contain some helpful hints to nudge you in
the right direction.
8.19.2 is_even
All right! Let’s get started.

Remember how an even number is a number that is divisible by 2?


Instructions

1.

Define a function is_even that will take a number x as input.

If x is even, then return True.

Otherwise, return False.

Hint
The modulo % operation is useful for determining if one number is
divisible by another.

Make sure to return True instead of printing it!

def is_even(x):
  if x%2 == 0:
    return True
  else:
    return False

8.19.3 is_int
An integer is just a number without a decimal part (for instance, -17, 0,
and 42 are all integers, but 98.6 is not).

For the purpose of this lesson, we’ll also say that a number with a
decimal part that is all 0s is also an integer, such as 7.0.

This means that, for this lesson, you can’t just test the input to see if it’s
of type int.
If the difference between a number and that same number rounded is
greater than zero, what does that say about that particular number?
Instructions

1.

Define a function is_int that takes a number x as an input.

Have it return True if the number is an integer (as defined above)


and False otherwise.

For example:

is_int(7.0)   # True    
is_int(7.5)   # False    
is_int(-1)    # True      

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  return absolute - rounded == 0

print is_int(10)
print is_int(10.5)

True
True

8.19.4 digit_sum
Awesome! Now let’s try something a little trickier. Try summing the
digits of a number.
Instructions

1.

Write a function called digit_sum that takes a positive integer n as input


and returns the sum of all that number’s digits. For
example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume
that the number you are given will always be positive.)

Check the hint if you need help!


Hint
One way might be to convert the integer to a string with str(), iterate
over it, and turn the substrings back into integers with int() to do the
addition.

If you’re looking for a challenge, try this: to get the rightmost digit of a
number, you can modulo (%) the number by 10. To remove the
rightmost digit you can floor divide (//) the number by 10. (Don’t worry
if you’re not familiar with floor division—you can look up the
documentation here. Remember, this is a challenge!)

Try working this into a pattern to isolate all of the digits and add them
to a total.

def digit_sum(n):
  w = str(n)
  result = 0
  for i in w:
    result = result + w[int(i)]
    print result
print digit_sum(1234)

Computer response

def digit_sum(n):
  total = 0
  string_n = str(n)
  for char in string_n:
    total += int(char)
  return total

#Alternate Solution:

#def digit_sum(n):
#  total = 0
#  while n > 0:
#    total += n % 10
#    n = n // 10
#  return total
  
print digit_sum(1234)
Practice
factorial

All right! Now we’re cooking. Let’s try a factorial problem.

To calculate the factorial of a non-negative integer x, just multiply all


the integers from 1 through x. For example:

 factorial(4) would equal 4 * 3 * 2 * 1, which is 24.

 factorial(1) would equal 1.

 factorial(3) would equal 3 * 2 * 1, which is 6.

Instructions

1.

Define a function factorial that takes an integer x as input.

Calculate and return the factorial of that number.


Hint

Consider having factorial() call itself. When the input is 1, your function


could just return 1. Otherwise, it could return the number multiplied
by factorial(n - 1).

Note that mathematically, factorial(0) is 1.

def factorial(x):
  less = 1
  stnumber = str(x)
  for i in stnumber:
    total = int(i)*(int(i)-less)
  return total
print factorial(4)

Computer response

def factorial(x):
    total = 1
    while x>0:
        total *= x
        x-=1
    return total
  
print factorial(5)
Practice

8.20 is_prime
A prime number is a positive integer greater than 1 that has no
positive divisors other than 1 and itself. (That’s a mouthful!)

In other words, if you want to test if a number in a variable x is prime,


then no other number should go into x evenly besides 1 and x.
So 2 and 5 and 11 are all prime, but 4 and 18 and 21 are not.

If there is a number between 1 and x that goes in evenly, then x is not


prime.
Instructions

1.

Define a function called is_prime that takes a number x as input.

For each number n from 2 to x - 1, test if x is evenly divisible by n.

If it is, return False.

If none of them are, then return True.


Hint

Remember: all numbers less than 2 are not prime numbers!

def is_prime(x):
  for n in (2,x-1):
    if x%n == 0:
      return False
    else:
      return True

Computer response

def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        return True

print is_prime(13)
print is_prime(10)

Practice
True
False

8.21 reverse
Great work so far! Let’s practice writing some functions that work with
strings.
Instructions

1.

Define a function called reverse that takes a string textand returns that


string in reverse. For example: reverse("abcd") should return "dcba".

You may not use reversed or [::-1] to help you with this.

You may get a string containing special characters (for example, !, @,


or #).
Hint

Consider how you would loop through text starting from the last


character through the first character.
def reverse(text):
    word = ""
    l = len(text) - 1
    while l >= 0:
        word = word + text[l]
        l -= 1
    return word
  
print reverse("Hello World")
dlroW olleH

8.22 anti_vowel
Nice work. Next up: vowels!
Instructions

1.

Define a function called anti_vowel that takes one string, text, as input


and returns the text with all of the vowels removed.

For example: anti_vowel("Hey You!") should return "Hy Y!". Don’t count Y


as a vowel. Make sure to remove lowercase and uppercase vowels.
HINT

To check to see if c is a vowel, you can do: c in "aeiouAEIOU" .

def anti_vowel(text):
  for i in "aeiouAEIOU":
    text = text.replace(i,"")
  return text
print anti_vowel("Hello")

Hll
8.23 scrabble_score
Scrabble is a game where players get points by spelling words. Words
are scored by adding together the point values of each individual letter
(we’ll leave out the double and triple letter and word scores for now).

To the right is a dictionary containing all of the letters in the alphabet


with their corresponding Scrabble point values.

For example: the word "Helix" would score 15 points due to the sum of


the letters: 4 + 1 + 1 + 1 + 8.
Instructions

1.

Define a function scrabble_score that takes a string word as input and


returns the equivalent scrabble score for that word.
 Assume your input is only one word containing no spaces or
punctuation.

 As mentioned, no need to worry about score multipliers!

 Your function should work even if the letters you get are
uppercase, lowercase, or a mix.

 Assume that you’re only given non-empty strings.

Hint

Have your function loop through the word that you are given as input
and look up the score for each letter in the score dictionary. Add the
score for each letter into a total of some sort.

Remember you can use a string’s .lower() method to make your string


lower case!
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}
         
def scrabble_score(word):
  word = word.lower()
  total = 0
  for letter in word:
    for leter in score:
      if letter == leter:
        total = total + score[leter]
  return total

print scrabble_score("pizza")

8.24 censor
You’re doing great with these string function challenges. Last one!
Instructions

1.
Write a function called censor that takes two strings, text and word, as
input. It should return the text with the word you chose replaced with
asterisks. For example:

censor("this hack is wack hack", "hack") ```

should return:

```py
"this **** is wack ****"

 Assume your input strings won’t contain punctuation or upper


case letters.

 The number of asterisks you put should correspond to the


number of letters in the censored word.

Hint

You can use

string.split()
# and
" ".join(list)
to help you here.

Remember: "*" * 4 equals "****"

After splitting the string with string.split(), you can loop through the
indices in the list and replace the words you are looking for with their
asterisk equivalent. Join the list at the end to get your sentence!
def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    count = 0
    for i in words:
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

    return result
  
print censor("this hack is wack hack", "hack")

this **** is wack ****


8.25 count
Great work so far. Let’s finish up by practicing with a few functions that
take lists as arguments.
Instructions

1.

Define a function called count that has two arguments


called sequence and item.

Return the number of times the item occurs in the list.

For example: count([1, 2, 1, 1], 1) should return 3 (because 1 appears 3


times in the list).

 There is a list method in Python that you can use for this, but you
should do it the long way for practice.

 Your function should return an integer.

 The item you input may be an integer, string, float, or even


another list!

 Be careful not to use list as a variable name in your code—it’s a


reserved word in Python!

Hint

You can set a sum variable inside count. You can then iterate


over sequence and increment sum every time you find an element in the
sequence that matches item.

def count(sequence, item):
    count = 0
    for i in sequence:
        if i == item:
            count += 1
    return count
  
print count([1, 2, 1, 1], 1)

8.26 purify
Awesome! Now let’s practice filtering a list.
Instructions

1.

Define a function called purify that takes in a list of numbers, removes


all odd numbers in the list, and returns the result. For
example, purify([1,2,3]) should return [2].

Do not directly modify the list you are given as input; instead, return a
new list with only the even numbers.
Hint

Your code should share something in common with


the is_even function you defined earlier.

def purify(x):
  for i in x:
    if i%2 != 0:
      x.remove(i)
  return x
n = [2, 3, 4, 6, 7]
print purify(n)

Computer response

def purify(lst):
    res = []
    for ele in lst:
        if ele % 2 == 0:
            res.append(ele)
    return res
  
print purify([1, 2, 3, 4])
[2, 4]

8.27 product
Great! Now let’s try a little multiplication.
Instructions

1.

Define a function called product that takes a list of integers as input and


returns the product of all of the elements in the list. For
example: product([4, 5, 5]) should return 100 (because 4 * 5 * 5 is 100).

 Don’t worry about the list being empty.

 Your function should return an integer.

Hint

You can use a loop to go through the elements of the list.

It’ll probably be useful to use the *= operator.

Be careful not to start your total at 0, as this would make the overall
result of the multiplication equal to 0! (Anything multiplied by zero
equals zero.)

def product(x):
    result = 1
    for i in x:
        result *= i
    return result
n = [1, 2, 3, 4, 5]
print product(n)

120

8.28 remove_duplicates
Awesome! Now for something a bit trickier.
Instructions

1.
Write a function remove_duplicates that takes in a list and removes
elements of the list that are the same.

For example: remove_duplicates([1, 1, 2, 2])  should return [1, 2].

 Don’t remove every occurrence, since you need to keep a single


occurrence of a number.

 The order in which you present your output does not matter. So
returning [1, 2, 3] is the same as returning [3, 1, 2].

 Do not modify the list you take as input! Instead, return a new


list.

Hint

The easiest way to approach this problem is to create a new list in your
function, loop through your input list, and add items from your input
list to your new list if the current item is not already contained in your
new list. Using the a not in b syntax might help you here.

Also, note that destructively modifying a list while you are looping
through it is bad practice and will likely lead to bugs somewhere down
the line! That’s why we always make a fresh copy to work on.
def remove_duplicates(x):
  lst = []
  for i in x:
    if i not in lst:
      lst.append(i)
  return lst
n = [1, 1, 2, 3, 4, 4, 3]
print remove_duplicates(n)

[1, 2, 3, 4]

8.29 median
Great work! You’ve covered a lot in these exercises. Last but not least,
let’s write a function to find the median of a list.

The median is the middle number in a sorted sequence of numbers.


Finding the median of [7, 12, 3, 1, 6] would first consist of sorting the
sequence into [1, 3, 6, 7, 12] and then locating the middle value,
which would be 6.

If you are given a sequence with an even number of elements, you


must average the two elements surrounding the middle.

For example, the median of the sequence [7, 3, 1, 4] is 3.5, since the


middle elements after sorting the list are 3 and 4 and (3 + 4) /
(2.0) is 3.5.

You can sort the sequence using the sorted() function, like so:

sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
Instructions

1.

Write a function called median that takes a list as an input and returns


the median value of the list. For example: median([1, 1, 2]) should
return 1.

 The list can be of any size and the numbers are not guaranteed
to be in any particular order. Make sure to sort it!

 If the list contains an even number of elements, your function


should return the average of the middle two.

Hint

In order to find the median of a list with an even number of elements,


you’re going to need to find the indices of the middle two elements.

You can find the middle two elements by halving the length of the
array to find the index of the first element, and subtracting one from
the first index to find the second index.

For example, with an array of length 6 like [0, 1, 2, 3, 4, 5], the two


middle elements that need to be averaged in order find the median
would be 2 and 3. You get 3 by cutting the length of the array in half
and 2 by subtracting 1 from the previous index: 3. You can use a similar
pattern to find the middle element of an odd-length list.

Last but not least, note that (2 + 3) / 2 is not the same as (2 + 3) / 2.0!
The former is integer division, meaning Python will try to give you an
integer back. You’ll want a float, so something like (2 + 3) / 2.0 is the
way to go.

def median(lst):
    sorted_list = sorted(lst)
    if len(sorted_list) % 2 != 0:
        #odd number of elements
        index = len(sorted_list)//2 
        return sorted_list[index]
    elif len(sorted_list) % 2 == 0:
        #even no. of elements
        index_1 = len(sorted_list)/2 - 1
        index_2 = len(sorted_list)/2
        mean = (sorted_list[index_1] + sorted_list[index_2])/2.0
        return mean
   
print median([2, 4, 5, 9])

4.5

TRINKET ASSIGNMETNS

In this assignment, you will practice using loops to count up to a


number that the user inputs and then count down from that
number.  To accomplish this, you will need to use a for loop, a
while loop, and input from the user.

1. Start your program by asking the user to input a number.


2. Practice using a for loop.  Print out the numbers from 1 to
a number that the user input.  The output of your program
should look similar to this:

3. Enter a number to count to: 5


4. 1
5. 2
6. 3
7. 4

8. Practice using a while loop to count down from the user


input number.  The output of your program should look
similar to this:

9. Enter a number to count to: 5


10. 1
11. 2
12. 3
13. 4
14. 5
15. Now we will count down:
16. 5
17. 4
18. 3
19. 2

Code:
number = int(raw_input("Enter a number "))
for i in range(1, number+1):
print i
print "Now we will count down"
count = number
while count >= 1:
print count
count -= 1
9 EXAM STATISTICS
Let's look at those grades!

Creating a program to compute statistics means that you won’t have to


whip out your calculator and manually crunch numbers. All you’ll have
to do is supply a new set of numbers and our program does all of the
hard work.

This mini-project will give you some practice with functions, lists, and
translating mathematical formulae into programming statements.

In order to use the scores in our program, we’ll need them in a


container, namely a list.

On the right, you’ll see the grades listed (see what I did there). The data
is anonymous to protect the privacy of the students.
Instructions

1.

Hit Run to continue.

Print those grades

As a refresher, let’s start off by writing a function to print out the list of
grades, one element at a time.
Instructions

1.
Define a function on line 3 called print_grades with one argument, a list
called grades_input.

Inside the function, iterate through grades_input and print each item on


its own line.

After your function, call print_grades with the grades list as the parameter.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades_input):
  for i in grades_input:
    print i
print print_grades(grades)

100
100
90
40
80
100
85
70
90
65
90
85
50.5
None

Review

So far, you’ve created a helper function that will be used in the next
sections.

You also have a solid handle on the concepts that we’ll need to
continue.
The next step in the creation of our grade statistics program involves
computing the mean (average) of the grades.

Onwards.
Instructions

1.

Hit Run to continue.

The sum of scores

Now that we have a function to print the grades, let’s create another
function to compute the sum of all of the test grades.

This will be super-helpful when we need to compute the average score.

I know what you’re thinking, “let’s just use the built-in sum function!”


The built-in function would work beautifully, but it would be too easy.

Computing the sum manually involves computing a rolling sum. As you


loop through the list, add the current grade to a variable that keeps
track of the total, let’s call that variable total.
Instructions

1.

On line 3, define a function, grades_sum, that does the following:

 Takes in a list of scores, scores

 Computes the sum of the scores

 Returns the computed sum.

Call the newly created grades_sum function with the list


of grades and print the result.
Hint

To compute a rolling sum, create a variable total that’s initialized to


zero. Then, as you loop through the list of grades, add the current grade
to total.
Avoid using sum as a variable name as it has a special meaning in
Python!

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(scores):
  total = 0
  for n in scores:
    total += n
  return total
print grades_sum(grades)

1045.5

Computing the Average

The average test grade can be found by dividing the sum of the grades
by the total number of grades.

Luckily, we just created an awesome function, grades_sum to compute the


sum.
Instructions

1.

Define a function, grades_average, below the grades_sum function that does


the following:

 Has one argument, grades_input, a list

 Calls grades_sum with grades_input

 Computes the average of the grades by dividing that sum


by float(len(grades_input)).

 Returns the average.

Call the newly created grades_average function with the list


of grades and print the result.
Hint
Your grades_average function should use the built-in Python len function
and your grades_sum function to compute the average.

Remember that integer division in Python will always result in an


integer. We convert len(grades_input) is a float so that the average is a
float.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(scores):
  total = 0
  for n in scores:
    total += n
  return total 
def grades_average(grades_input):
  sum = grades_sum(grades_input)
  return sum/float(len(grades_input))

print grades_average(grades)

80.4230769231

Review

Great work creating the capability to compute the average of the test
grades.

We’re going to use the average for computing the variance. The
variance allows us to see how widespread the grades were from the
average.
Instructions

1.

Hit Run to continue.

The Variance

Let’s see how the grades varied against the average. This is called
computing the variance.
A very large variance means that the students’ grades were all over the
place, while a small variance (relatively close to the average) means
that the majority of the students had similar grades.
Instructions

1.

On line 18, define a new function called grades_variance that accepts one


argument, scores, a list.

First, create a variable average and store the result of


calling grades_average(scores).

Next, create another variable variance and set it to zero. We will use this


as a rolling sum.

for each score in scores: Compute its squared difference: (average -


score) ** 2 and add that to variance.

Divide the total variance by the number of scores.

Then, return that result.

Finally, after your function code, print grades_variance(grades).

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades_input):
  for grade in grades_input:
    print grade

def grades_sum(scores):
  total = 0
  for score in scores: 
    total += score
  return total
    
def grades_average(grades_input):
  sum_of_grades = grades_sum(grades_input)
  average = sum_of_grades / float(len(grades_input))
  return average
def grades_variance(scores):
  average= grades_average(scores)
  variance = 0
  for score in scores:
    variance += (average -score)**2
    n = variance / float(len(scores))
  return n
print grades_variance(grades)

334.071005917

Standard Deviation

Great job computing the variance! The last statistic will be much
simpler: standard deviation.

The standard deviation is the square root of the variance. You can
calculate the square root by raising the number to the one-half power.
Instructions

1.

Define a function, grades_std_deviation, that takes one argument


called variance.

return the result of variance ** 0.5

After the function, create a new variable called variance and store the


result of calling grades_variance(grades).

Finally print the result of calling grades_std_deviation(variance).


Hint

Remember, raising a number to an exponent involves using the


exponentiation ** operator.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades_input):
  for grade in grades_input:
    print grade
def grades_sum(scores):
  total = 0
  for score in scores: 
    total += score
  return total
    
def grades_average(grades_input):
  sum_of_grades = grades_sum(grades_input)
  average = sum_of_grades / float(len(grades_input))
  return average

def grades_variance(scores):
  average= grades_average(scores)
  variance = 0
  for score in scores:
    variance += (average -score)**2
    n = variance / float(len(scores))
  return n
print grades_variance(grades)

def grades_std_deviation(variance):
  return variance**0.5
variance = grades_variance(grades)
print grades_std_deviation(variance)

334.071005917
18.2776094147

Review

You’ve done a great job completing this program.

We’ve created quite a few meaningful functions. Namely, we’ve created


helper functions to print a list of grades, compute the sum, average,
variance, and standard deviation about a set of grades.

Let’s wrap up by printing out all of the statistics.

Who needs to pay for grade calculation software when you can write
your own? :)
Instructions
1.

Print out the following:

 all of the grades

 sum of grades

 average grade

 variance

 standard deviation
 grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

 def print_grades(grades_input):
   for grade in grades_input:
     print grade

 def grades_sum(scores):
   total = 0
   for score in scores: 
     total += score
   return total
     
 def grades_average(grades_input):
   sum_of_grades = grades_sum(grades_input)
   average = sum_of_grades / float(len(grades_input))
   return average

 def grades_variance(scores):
   average= grades_average(scores)
   variance = 0
   for score in scores:
     variance += (average -score)**2
     n = variance / float(len(scores))
   return n
 print grades_variance(grades)

 def grades_std_deviation(variance):
   return variance**0.5
 variance = grades_variance(grades)
 print grades_std_deviation(variance)
100
100
90
40
80
100
85
70
90
65
90
85
50.5
None
1045.5
80.4230769231
334.071005917
18.2776094147

10 ADVANCED TOPICS IN PYTHON

10.1 Iterators for Dictionaries


Let’s start with iterating over a dictionary. Recall that a dictionary is just
a collection of keys and values.

d = {
  "Name": "Guido",
  "Age": 56,
  "BDFL": True
}
print d.items()
# => [('BDFL', True), ('Age', 56), ('Name', 'Guido')]
Note that the .items() method doesn’t return key/value pairs in any
specific order.
Instructions

1.
Create your own Python dictionary, my_dict, in the editor to the right
with two or three key/value pairs.

Then, print the result of calling the my_dict.items().


Hint

You can think of dictionaries as unordered key/value pairs.

my_dict = {"Name": "Carlos", "Age": 57, "BDFL": True}
print my_dict.items()

[('BDFL', True), ('Age', 57), ('Name', 'Carlos')]

keys() and values()

While .items() returns an array of tuples with each tuple consisting of a


key/value pair from the dictionary:

 The .keys() method returns a list of the dictionary’s keys, and

 The .values() method returns a list of the dictionary’s values.

Again, these methods will not return the keys or values from the
dictionary in any specific order.

You can think of a tuple as an immutable (that is, unchangeable) list.


Tuples are surrounded by ()s and can contain any data type.
Instructions

1.

Remove your call to .items() and replace it with a call to .keys() and a


call to .values(), each on its own line. Make sure to print both!
Hint

For instance, your call to my_dict.keys() might look like:

print my_dict.keys()

10.2 The 'in' Operator


For iterating over lists, tuples, dictionaries, and strings, Python also
includes a special keyword: in. You can use in very intuitively, like so:
for number in range(5):
  print number,

d = {
  "name": "Eric",
  "age": 26
}

for key in d:
  print key, d[key],

for letter in "Eric":


  print letter,  # note the comma!

1. In the example above, first we create and iterate through a range,


printing out 0 1 2 3 4. Note that the trailing comma ensures that
we keep printing on the same line.

2. Next, we create a dictionary and iterate through, printing out age


26 name Eric. Dictionaries have no specific order.

3. Finally, we iterate through the letters of a string, printing out E r


i c.

Instructions

1.

For each key in my_dict: print out the key , then a space, then the value
stored by that key. (You should use print a, b rather than print a + " " +
b.)
Hint

You’ll want to do something like this:

for key in some_dict:


  print key, some_dict[key]

my_dict = {"Name": "Carlos", "Age": 57, "BDFL": True}
print my_dict.keys()
print my_dict.values()
for key in my_dict:
  print key, my_dict[key]

BDFL True
Age 57
Name Carlos

10.3 Building Lists


Let’s say you wanted to build a list of the numbers from 0 to 50
(inclusive). We could do this pretty easily:

my_list = range(51)
But what if we wanted to generate a list according to some logic—for
example, a list of all the even numbers from 0 to 50?

Python’s answer to this is the list comprehension. List


comprehensions are a powerful way to generate lists using
the for/in and if keywords we’ve learned.
Instructions

1.

Check out the list comprehension example in the editor. When you’re
pretty sure you know what it’ll do, click Run to see it in action.

evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,
28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]

10.4 List Comprehension Syntax


Here’s a simple example of list comprehension syntax:

new_list = [x for x in range(1, 6)]


# => [1, 2, 3, 4, 5]
This will create a new_list populated by the numbers one to five. If you
want those numbers doubled, you could use:

doubles = [x * 2 for x in range(1, 6)]


# => [2, 4, 6, 8, 10]
And if you only wanted the doubled numbers that are evenly divisible
by three:

doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3


== 0]
# => [6]
Instructions

1.

Use a list comprehension to build a list called even_squares in the editor.

Your even_squares list should include the squares of the even numbers


between 1 to 11. Your list should start [4, 16, 36...] and go from there.
Hint

You can use x ** 2 to square a number, and x % 2 == 0 to check if it’s
even.

even_squares = [x**2 for x in range(1,12) if x%2 == 0]

print even_squares

[4, 16, 36, 64, 100]

10.5 Now You Try!


Great work! Now it’s time for you to create a list comprehension all on
your own.

c = ['C' for x in range(5) if x < 3]


print c
The example above creates and prints out a list containing ['C', 'C',
'C'].
Instructions

1.

Use a list comprehension to create a list, cubes_by_four.

The comprehension should consist of the cubes of the numbers 1


through 10 only if the cube is evenly divisible by four.

Finally, print that list to the console.


Note that in this case, the cubed number should be evenly divisible by
4, not the original number.

cubes_by_four = [x**3 for x in range(1,11) if (x**3)%4 == 0]
print cubes_by_four

[8, 64, 216, 512, 1000]

10.6 List Slicing Syntax


Sometimes we only want part of a Python list. Maybe we only want the
first few elements; maybe we only want the last few. Maybe we want
every other element!

List slicing allows us to access elements of a list in a concise manner.


The syntax looks like this:

[start:end:stride]
Where start describes where the slice starts (inclusive), end is where it
ends (exclusive), and stride describes the space between items in the
sliced list. For example, a stride of 2 would select every other item from
the original list to place in the sliced list.
Instructions

1.

We’ve generated a list with a list comprehension in the editor to the


right, and we’re about to print a selection from the list using list slicing.
Can you guess what will be printed out? Click Run when you think you
know!

l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

[9, 25, 49, 81]

10.7 Omitting Indices


If you don’t pass a particular index to the list slice, Python will pick a
default.
to_five = ['A', 'B', 'C', 'D', 'E']

print to_five[3:]
# prints ['D', 'E']

print to_five[:2]
# prints ['A', 'B']

print to_five[::2]
# print ['A', 'C', 'E']

1. The default starting index is 0.

2. The default ending index is the end of the list.

3. The default stride is 1.

Instructions

1.

Use list slicing to print out every odd element of my_list from start to


finish.

Omit the start and end index. You only need to specify a stride.

Check the Hint if you need help.


Hint

Remember, the syntax for list slicing is

[start:end:stride]
Since you’re using the entire list, you should leave out
the start and end indices (but leave in the colons!) and give the slice
a stride that will select every other (that is, odd) element.

my_list = range(1, 11) # List of numbers 1 - 10

# Add your code below!
print my_list[::2]

[1, 3, 5, 7, 9]
10.8 Reversing a List
We have seen that a positive stride progresses through the list from
left to right.

A negative stride progresses through the list from right to left.

letters = ['A', 'B', 'C', 'D', 'E']


print letters[::-1]
In the example above, we print out ['E', 'D', 'C', 'B', 'A'].
Instructions

1.

Create a variable called backwards and set it equal to the reversed


version of my_list.

Make sure to reverse the list in the editor by passing your list slice a
negative stride, like in the example above.
my_list = range(1, 11)

# Add your code below!
backwards = my_list[::-1]

10.9 Stride Length


A positive stride length traverses the list from left to right, and a
negative one traverses the list from right to left.

Further, a stride length of 1 traverses the list “by ones,” a stride length
of 2 traverses the list “by twos,” and so on.
Instructions

1.

Create a variable, backwards_by_tens, and set it equal to the result of


going backwards through to_one_hundred by tens. Go ahead and print
backwards_by_tens to the console.
Hint

Remember, the syntax is:

new_list = old_list[begin:end:stride]
to_one_hundred = range(101)
# Add your code below!
backwards_by_tens = to_one_hundred[::10]
print backwards_by_tens

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

10.10 Practice Makes Perfect


Great work! See? This list slicing business is pretty straightforward.

Let’s do one more, just to prove you really know your stuff.
Instructions

1.

Create a list, to_21, that’s just the numbers from 1 to 21, inclusive.

Create a second list, odds, that contains only the odd numbers in


the to_21 list (1, 3, 5, and so on). Use list slicing for this one instead of a
list comprehension.

Finally, create a third list, middle_third, that’s equal to the middle third


of to_21, from 8 to 14, inclusive.
to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14:1]

10.10.1 Anonymous Functions


One of the more powerful aspects of Python is that it allows for a style
of programming called functional programming, which means that
you’re allowed to pass functions around just as if they were variables or
values. Sometimes we take this for granted, but not all languages allow
this!

Check out the code at the right. See the lambda bit? Typing

lambda x: x % 3 == 0
Is the same as

def by_three(x):
  return x % 3 == 0
Only we don’t need to actually give the function a name; it does its
work and returns a value without one. That’s why the function the
lambda creates is an anonymous function.

When we pass the lambda to filter, filter uses the lambda to


determine what to filter, and the second argument (my_list, which is
just the numbers 0 – 15) is the list it does the filtering on.
Instructions

1.

Can you guess what the this code will print to the console? Click Run to
see.

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)

[0, 3, 6, 9, 12, 15]

10.10.2 Lambda Syntax


Lambda functions are defined using the following syntax:

my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)
Lambdas are useful when you need a quick function to do some work
for you.

If you plan on creating a function you’ll use over and over, you’re
better off using def and giving that function a name.
Instructions

1.

Fill in the first part of the filter function with a lambda. The lambda should


ensure that only "Python" is returned by the filter.

Fill in the second part of the filter function with languages, the list to


filter.
Hint
Remember, filter() takes two arguments: the first is the function that
tells it what to filter, and the second is the object to perform the
filtering on.

languages = ["HTML", "JavaScript", "Python", "Ruby"]

# Add arguments to the filter()
print filter(lambda x: x == "Python", languages)

['Python']

10.10.3 Try It!


All right! Time to test out filter() and lambda expressions.

cubes = [x ** 3 for x in range(1, 11)]


filter(lambda x: x % 3 == 0, cubes)
The example above is just a reminder of the syntax.
Instructions

1.

Create a list, squares, that consists of the squares of the numbers 1 to


10. A list comprehension could be useful here!

Use filter() and a lambda expression to print out only the squares that


are between 30 and 70 (inclusive).
Hint

You’ll want to filter for x >= 30 and x <= 70.

squares = [x**2 for x in range(1,11)]
print filter(lambda x: x >=30 and x<= 70, squares)

[36, 49, 64]

10.10.4 Iterating Over Dictionaries


First, let’s review iterating over a dict.
Instructions

1.
Call the appropriate method on movies such that it will print out all
the items (hint, hint) in the dictionary—that is, each key and each value.
Hint

You’ll just want to print the result of calling the .items() method on


your movies. No loops necessary!

movies = {
  "Monty Python and the Holy Grail": "Great",
  "Monty Python's Life of Brian": "Good",
  "Monty Python's Meaning of Life": "Okay"
}
print movies.items()

[("Monty Python's Life of Brian", 'Good'), ("Monty


Python's Meaning of Life", 'Okay'), ('Monty Python
and the Holy Grail', 'Great')]

10.10.5 Comprehending Comprehensions


Good! Now let’s take another look at list comprehensions.

squares = [x ** 2 for x in range(5)]


Instructions

1.

Use a list comprehension to create a list, threes_and_fives, that consists


only of the numbers between 1 and 15 (inclusive) that are evenly
divisible by 3 or 5.
Hint

Remember, list comprehension syntax looks like this:

list_name = [var for var in range]


You can include an optional if statement after the range. (You’ll need
such an if statement to check whether the numbers are evenly divisible
by 3 or 5.)

Remember, modulo (%) is a good way to check if a number is evenly


divisible by another.
threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 ==0]
10.10.6 List Slicing
Great! Next up: list slicing.

str = "ABCDEFGHIJ"
start, end, stride = 1, 6, 2
str[start:end:stride]
You can think of a Python string as a list of characters.
Instructions

1.

The string in the editor is garbled in two ways:

1. Our message is backwards.

2. The letter we want is every other letter.

Use list slicing to extract the message and save it to a variable


called message.
Hint

It’s important to remember that lists are mutable (changeable) in


Python, but strings aren’t; when you slice a string, you get back a new
string. The original string is unchanged unless you purposely “save
over” it, like this:

my_string = "Monty Python"


# => Monty Python
my_string = my_string[:-7]
# => Monty   

garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]

10.10.7 Lambda Expressions


Last but not least, let’s look over some lambdas.

my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)
We’ve given you another (slightly different) garbled. Sort it out with
a filter() and a lambda.
Instructions
1.

Create a new variable called message.

Set it to the result of calling filter() with the appropriate lambda that will


filter out the "X"s. The second argument will be garbled.

Finally, print your message to the console.


Hint

Remember, a lambda expression looks like this:

lambda variable: variable expression


For example, you might have

lambda x: x != 10
Remember, filter() takes two arguments: the first is the function that
tells it what to filter (in this case, your lambda expression), and the
second is the object to perform the filtering on (the garbled string).

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXs
XaXXXXXXgXeX!XX"

I am another secret message!

11 INTRODUCTION TO BITWISE OPERATORS


11.1 Just a Little BIT
Welcome to an intro level explanation of bitwise operations in Python!

Bitwise operations might seem a little esoteric and tricky at first, but
you’ll get the hang of them pretty quickly.

Bitwise operations are operations that directly manipulate bits. In all


computers, numbers are represented with bits, a series of zeros and
ones. In fact, pretty much everything in a computer is represented by
bits. This course will introduce you to the basic bitwise operations and
then show you what you can do with them.

Bitwise operators often tend to puzzle and mystify new programmers,


so don’t worry if you are a little bit confused at first. To be honest, you
aren’t really going to see bitwise operators in everyday programming.
However, they do pop up from time to time, and when they do, you
should have a general idea of what is going on.
Instructions

1.

In the editor are the 6 basic bitwise operations. Click Run and see what
the console prints out. All of them will be explained in due time!

print 5 >> 4  # Right Shift
print 5 << 1  # Left Shift
print 8 & 5   # Bitwise AND
print 9 | 4   # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88     # Bitwise NOT

0
10
0
13
38
-89

11.2 The Base 2 Number System


When we count, we usually do it in base 10. That means that each
place in a number can hold one of ten values, 0-9. In binary we count
in base two, where each place can hold one of two values: 0 or 1. The
counting pattern is the same as in base 10 except when you carry over
to a new column, you have to carry over every time a place goes higher
than one (as opposed to higher than 9 in base 10).
For example, the numbers one and zero are the same in base 10 and
base 2. But in base 2, once you get to the number 2 you have to carry
over the one, resulting in the representation “10”. Adding one again
results in “11” (3) and adding one again results in “100” (4).

Contrary to counting in base 10, where each decimal place represents a


power of 10, each place in a binary number represents a power of two
(or a bit). The rightmost bit is the 1’s bit (two to the zero power), the
next bit is the 2’s bit (two to the first), then 4, 8, 16, 32, and so on.

The binary number ‘1010’ is 10 in base 2 because the 8’s bit and the 2’s
bit are “on”:

8's bit  4's bit  2's bit  1's bit


    1       0       1      0
    8   +   0    +  2   +  0  = 10
In Python, you can write numbers in binary format by starting the
number with 0b. When doing so, the numbers can be operated on like
any other number!
Instructions

1.

Take a look at the examples in the editor. Really try to understand this
pattern before moving on. Click Run when you’re ready to continue.

print 0b1,    #1
print 0b10,   #2
print 0b11,   #3
print 0b100,  #4
print 0b101,  #5
print 0b110,  #6
print 0b111   #7
print "******"
print 0b1 + 0b11
print 0b11 * 0b11

1 2 3 4 5 6 7
******
4
9
Binary Number
language
0b1 1
0b10 2
0b11 3
0b100 4
0b101 5
0b110 6
0b111 7
0b1000 8
0b1001 9
0b1010 10
0b1011 11
0b1100 12
0b1101 13
0b1110 14
0b1111 15
0b10000 16

The key to count in binary language is to write all the possible numbers with 1 and
0, and assign the lowest to the next number starting with one. For example, 1 is
equal to 1, the next lowest number that can be written with 1 and 0 is 10 so this
correspond or is equal to 2, the next lowest number is 11 so this correspond to 3
and so on. See the foregoing table.

11.3 I Can Count to 1100!


All right! Time to practice counting in binary.

To make sure you’ve got the hang of it, fill out the rest of the numbers
all the way up to twelve. Please do not use the str() method or any
other outside functions.

Here are a few numbers that will be good to know going forward -

2 ** 0 = 1
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
2 ** 6 = 64
2 ** 7 = 128
2 ** 8 = 256
2 ** 9 = 512
2 ** 10 = 1024
You may recognize these numbers. Do you have a 32 or 64 bit system?
Does your computer have a 256GB hard drive? Computers think in
binary!
Instructions

1.

Fill out the rest of the numbers with their corresponding binary values
up to twelve in the editor to the right, using the 0bxxx format.
Hint

Feel free to peek back at the previous exercise if you’re having trouble!

11.4 The bin() Function


Excellent! The biggest hurdle you have to jump over in order to
understand bitwise operators is learning how to count in base 2.
Hopefully the lesson should be easier for you from here on out.

There are Python functions that can aid you with bitwise operations. In
order to print a number in its binary representation, you can use
the bin() function. bin() takes an integer as input and returns the binary
representation of that integer in a string. (Keep in mind that after using
the bin function, you can no longer operate on the value like a
number.)

You can also represent numbers in base 8 and base 16 using


the oct() and hex() functions. (We won’t be dealing with those here,
however.)
Instructions

1.
We’ve provided an example of the bin function in the editor. Go ahead
and use print and bin() to print out the binary representations of the
numbers 2 through 5, each on its own line.
Hint

Use the code on line 1 as a guide! You can use a


separate print statement for each number, though a loop or range
should work just as well.
print bin(1)
print bin(2)
print bin(3)
print bin(4)
print bin(5)

0b1
0b10
0b11
0b100
0b101

11.5 int()'s Second Parameter


Python has an int() function that you’ve seen a bit of already. It can
turn non-integer input into an integer, like this:

int("42")
# ==> 42
What you might not know is that the int function actually has an
optional second parameter.

int("110", 2)
# ==> 6
When given a string containing a number and the base that number is
in, the function will return the value of that number converted to base
ten.
Instructions

1.
In the console are several different ways that you can use
the int function’s second parameter.On line 7, use int to print the base
10 equivalent of the binary number 11001001.
Hint

Use the examples on lines 1 – 4 as a guide!


print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
# Print out the decimal equivalent of the binary 11001001.
print int("11001001",2)

1
2
7
4
5
201

11.6 Slide to the Left! Slide to the Right!


The next two operations we are going to talk about are the left and
right shift bitwise operators. These operators work by shifting the bits
of a number over by a designated number of slots.

The block below shows how these operators work on the bit level. Note
that in the diagram, the shift is always a positive integer:

# Left Bit Shift (<<)  


0b000001 << 2 == 0b000100 (1 << 2 = 4)
0b000101 << 3 == 0b101000 (5 << 3 = 40)       

# Right Bit Shift (>>)


0b0010100 >> 3 == 0b000010 (20 >> 3 = 2)
0b0000010 >> 2 == 0b000000 (2 >> 2 = 0)
Shift operations are similar to rounding down after dividing and
multiplying by 2 (respectively) for every time you shift, but it’s often
easier just to think of it as shifting all the 1s and 0s left or right by the
specified number of slots.
Note that you can only do bitwise operations on an integer. Trying to
do them on strings or floats will result in nonsensical output!
Instructions

1.

Shift the variable shift_right to the right twice (>> 2) and shift the
variable shift_left to the left twice (<< 2). Try to guess what the printed
output will be!
Hint

Use the example in the instructions above as a guide.

shift_right = 0b1100 >> 2
shift_left = 0b1 << 2

# Your code here!

print bin(shift_right)
print bin(shift_left)

0b11
0b100

11.7 A BIT of This AND That


The bitwise AND (&) operator compares two numbers on a bit level and
returns a number where the bits of that number are turned on if the
corresponding bits of both numbers are 1. For example:

     a:   00101010   42
     b:   00001111   15       
===================
a & b:   00001010   10
As you can see, the 2’s bit and the 8’s bit are the only bits that are on in
both a and b, so a & b only contains those bits. Note that using
the & operator can only result in a number that is less than or equal to
the smaller of the two values.

This operator returns the less or equal number of both compared


numbers starting from the bit equal 1 that is in the same position in
both numbers.
So remember, for every given bit in a and b:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Therefore,

0b111 (7) & 0b1010 (10) = 0b10


which equals two.
Instructions

1.

print out the result of calling bin() on 0b1110 & 0b101.

See if you can guess what the output will be!

a = 0b1110 & 0b101
print bin(a)

11.8 A BIT of This OR That


The bitwise OR (|) operator compares two numbers on a bit level and
returns a number where the bits of that number are turned on
if either of the corresponding bits of either number are 1. For example:

    a:  00101010  42
    b:  00001111  15       
================
a | b:  00101111  47
Note that the bitwise | operator can only create results that are greater
than or equal to the larger of the two integer inputs.

So remember, for every given bit in a and b:

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
Meaning

110 (6) | 1010 (10) = 1110 (14)


Instructions
1.

For practice, print out the result of using | on 0b1110 and 0b101 as a


binary string. Try to do it on your own without using the | operator if
you can help it.
Hint

This is pretty similar to what you did in the previous exercise! You’re
just using | instead of &.

a= 0b1110 | 0b101
print bin(a)

0b1111

11.9 This XOR That?


The XOR (^) or exclusive or operator compares two numbers on a bit
level and returns a number where the bits of that number are turned
on if either of the corresponding bits of the two numbers are 1, but
not both.

    a:  00101010   42
    b:  00001111   15       
================
a ^ b:  00100101   37
Keep in mind that if a bit is off in both numbers, it stays off in the
result. Note that XOR-ing a number with itself will always result in 0.

So remember, for every given bit in a and b:

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
Therefore:

111 (7) ^ 1010 (10) = 1101 (13)


Instructions

1.
For practice, print the result of using ^ on 0b1110 and 0b101 as a binary
string. Try to do it on your own without using the ^ operator.
Hint

This is pretty similar to what you did in the previous exercise! You’re
just using ^ instead of |.

print "0b1011"

0b1011

11.10 See? This is NOT That Hard!


The bitwise NOT operator (~) just flips all of the bits in a single number.
What this actually means to the computer is actually very complicated,
so we’re not going to get into it. Just know that mathematically, this is
equivalent to adding one to the number and then making it negative.

And with that, you’ve seen all of the basic bitwise operators! We’ll see
what we can do with these in the next section.
Instructions

1.

Click Run and observe what the console prints out.

print ~1
print ~2
print ~3
print ~42
print ~123

-2
-3
-4
-43
-124
11.11 The Man Behind the Bit Mask
A bit mask is just a variable that aids you with bitwise operations. A bit
mask can help you turn specific bits on, turn others off, or just collect
data from an integer about which bits are on or off.

num  = 0b1100
mask = 0b0100
desired = num & mask
if desired > 0:
  print "Bit was on"
In the example above, we want to see if the third bit from the right is
on.

1. First, we first create a variable num containing the number 12,


or 0b1100.

2. Next, we create a mask with the third bit on.

3. Then, we use a bitwise-and operation to see if the third bit from


the right of num is on.

4. If desired is greater than zero, then the third bit of num must have
been one.

Instructions

1.

Define a function, check_bit4, with one argument, input, an integer.

It should check to see if the fourth bit from the right is on.

If the bit is on, return "on" (not print!)

If the bit is off, return "off".

Check the Hint for some examples!


Hint

Here are some examples:

check_bit4(0b1) # ==> "off"


check_bit4(0b11011) # ==> "on"
check_bit4(0b1010) # ==> "on"
You’ll need to use a mask where all bits are off except for the fourth bit
from the right.
def check_bit4(int(input())):
  mask = 0b1000
  desired = int(input()) & mask
  if desired > 0:
    return "on"
  else:
    return "off"

def check_bit4(input):
  mask = 0b1000
  desired = input & mask
  if desired > 0:
    return "on"
  else:
    return "off"

11.12 Turn It On
You can also use masks to turn a bit in a number on using |. For
example, let’s say I want to make sure the rightmost bit of number a is
turned on. I could do this:

a = 0b110 # 6
mask = 0b1 # 1
desired =  a | mask # 0b111, or 7
Using the bitwise | operator will turn a corresponding bit on if it is off
and leave it on if it is already on.
Instructions

1.

In the editor is a variable, a. Use a bitmask and the value a in order to


achieve a result where the third bit from the right of a is turned on. Be
sure to print your answer as a bin() string!
Hint

You should use | and the variable a with a mask where the third bit
from the right, and only the third bit from the right, is on.

a = 0b10111011
mask = 0b100
desired = a | mask
print bin(desired)
0b10111111
11.13 Just Flip Out
Using the XOR (^) operator is very useful for flipping bits. Using ^ on a
bit with the number one will return a result where that bit is flipped.

For example, let’s say I want to flip all of the bits in a. I might do this:

a = 0b110 # 6
mask = 0b111 # 7
desired =  a ^ mask # 0b1
Instructions

1.

In the editor is the 8 bit variable a. Use a bitmask and the value a in
order to achieve a result where all of the bits in a are flipped. Be sure to
print your answer as a bin() string!
Hint

You’ll need a mask the same length as a in which all of the bits are
turned on (all set to 1).

a = 0b11101110

mask = 0b11111111
desired = a ^ mask

print bin(desired)

0b1

11.14 Slip and Slide


Finally, you can also use the left shift ( <<) and right shift (>>) operators
to slide masks into place.

a = 0b101
# Tenth bit mask
mask = (0b1 << 9)  # One less than ten
desired = a ^ mask
Let’s say that I want to turn on the 10th bit from the right of the
integer a.
Instead of writing out the entire number, we slide a bit over using
the << operator.

We use 9 because we only need to slide the mask nine places over
from the first bit to reach the tenth bit.
Instructions

1.

Define a function called flip_bit that takes the inputs (number, n).

Flip the nth bit (with the ones bit being the first bit) and store it
in result.

Return the result of calling bin(result).

Hint
Use the << operator to move your mask into place and the ^ operator to
flip your desired bit.

def flip_bit(number, n):
  bit_to_flip = 0b1 << (n -1)
  result = number ^ bit_to_flip
  return bin(result)
12 INTRODUCTION TO CLASSES
Why Use Classes?

Python is an object-oriented programming language, which means it


manipulates programming constructs called objects. You can think of
an object as a single data structure that contains data as well as
functions; the functions of an object are called its methods. For
example, any time you call

len("Eric")
Python is checking to see whether the string object you passed it has a
length, and if it does, it returns the value associated with that attribute.
When you call

my_dict.items()
Python checks to see if my_dict has an items() method (which all
dictionaries have) and executes that method if it finds it.

But what makes "Eric" a string and my_dict a dictionary? The fact that


they’re instances of the str and dict classes, respectively. A class is just
a way of organizing and producing objects with similar attributes and
methods.
Instructions

1.

Check out the code in the editor to the right. We’ve defined our own
class, Fruit, and created a lemon instance.When you’re ready, click Run to
get started creating classes and objects of your own.

class Fruit(object):
  """A class that makes various tasty fruits."""
  def __init__(self, name, color, flavor, poisonous):
    self.name = name
    self.color = color
    self.flavor = flavor
    self.poisonous = poisonous
  def description(self):
    print "I'm a %s %s and I taste %s." % (self.color, self.name, self.fl
avor)

  def is_edible(self):
    if not self.poisonous:
      print "Yep! I'm edible."
    else:
      print "Don't eat me! I am super poisonous."

I'm a yellow lemon and I taste sour.


Yep! I'm edible.

12.1 Class Syntax


A basic class consists only of the class keyword, the name of the class,
and the class from which the new class inherits in parentheses. (We’ll
get to inheritance soon.) For now, our classes will inherit from
the object class, like so:

class NewClass(object):
  # Class magic here
This gives them the powers and abilities of a Python object. By
convention, user-defined Python class names start with a capital letter.
Instructions

1.

Create a class called Animal in the editor. For now, in the body of your
class, use the pass keyword. (pass doesn’t do anything, but it’s useful as
a placeholder in areas of your code where Python expects an
expression.)
Hint

Use the example in the instructions as a guide!

class Animal(object):
  pass
12.2 Classier Classes
We’d like our classes to do more than… well, nothing, so we’ll have to
replace our pass with something else.

You may have noticed in our example back in the first exercise that we
started our class definition off with an odd-looking function: __init__().
This function is required for classes, and it’s used to initialize the
objects it creates. __init__() always takes at least one argument, self,
that refers to the object being created. You can think of __init__() as
the function that “boots up” each object the class creates.
Instructions

1.

Remove the pass statement in your class definition, then go ahead


and define an __init__() function for your Animal class. Pass it the
argument self for now; we’ll explain how this works in greater detail in
the next section. Finally, put the pass into the body of
the __init__() definition, since it will expect an indented block.
Hint

Your __init__() function should look something like this:

def __init__(self):
  pass

class Animal(object):
  def __init__(self):
    pass

12.3 Let's Not Get Too Selfish


Excellent! Let’s make one more tweak to our class definition, then go
ahead and instantiate (create) our first object.

So far, __init__() only takes one parameter: self. This is a Python


convention; there’s nothing magic about the word self. However, it’s
overwhelmingly common to use self as the first parameter in __init__(),
so you should do this so that other people will understand your code.

The part that is magic is the fact that self is the first parameter passed


to __init__(). Python will use the first parameter that __init__() receives
to refer to the object being created; this is why it’s often called self,
since this parameter gives the object being created its identity.
Instructions

1.

Let’s do two things in the editor:

 Pass __init__() a second parameter, name.

 In the body of __init__(), let the function know that name refers to


the created object’s name by typing self.name = name. (This will
become crystal clear in the next section.)

Hint

Your syntax should look like this:

class Animal(object):
  def __init__(self, name):
    # Set the name parameter here!

class Animal(object):
  def __init__(self, name):
    self.name = name
    pass

12.4 Instantiating Your First Object


Perfect! Now we’re ready to start creating objects.

We can access attributes of our objects using dot notation. Here’s how


it works:

class Square(object):
  def __init__(self):
    self.sides = 4

my_shape = Square()
print my_shape.sides

1. First we create a class named Square with an attribute sides.


2. Outside the class definition, we create a new instance
of Square named my_shape and access that attribute
using my_shape.sides.

Instructions

1.

Outside the Animal class definition, create a variable named zebra and set


it equal to Animal("Jeffrey").

Then print out zebra‘s name.
Hint

You can create a new Animal object named "Jeffrey" like this:

zebra = Animal("Jeffrey")
You can print out "Jeffrey"‘s name like this:

print zebra.name

class Animal(object):
  def __init__(self, name):
    self.name = name
    pass
zebra = Animal("Jeffrey")
print zebra.name

Jeffrey
12.5 More on __init__() and self
Now that you’re starting to understand how classes and objects work,
it’s worth delving a bit more into __init__() and self. They can be
confusing!

As mentioned, you can think of __init__() as the method that “boots


up” a class’ instance object: the init bit is short for “initialize.”

The first argument __init__() gets is used to refer to the instance


object, and by convention, that argument is called self. If you add
additional arguments—for instance, a name and age for your animal—
setting each of those equal to self.name and self.age in the body
of __init__() will make it so that when you create an instance object of
your Animal class, you need to give each instance a name and an age,
and those will be associated with the particular instance you create.
Instructions

1.

Check out the examples in the editor. See how __init__() “boots up”


each object to expect a name and an age, then
uses self.name and self.age to assign those names and ages to each
object? Add a third attribute, is_hungry to __init__(), and click Run to see
the results.
Hint

Your code should look something like this:

def __init__(self, name, age, is_hungry)


  self.name = name
  self.age = age
  self.is_hungry = is_hungry

# Class definition
class Animal(object):
  """Makes cute animals."""
  # For initializing our instance objects
  def __init__(self, name, age, is_hungry):
    self.name = name
    self.age = age
    self.is_hungry = is_hungry

# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.

zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)

print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry
Jeffrey 2 True
Bruce 1 False
Chad 7 True

12.6 Class Scope


Another important aspect of Python classes is scope. The scope of a
variable is the context in which it’s visible to the program.

It may surprise you to learn that not all variables are accessible to all
parts of a Python program at all times. When dealing with classes, you
can have variables that are available everywhere (global variables),
variables that are only available to members of a certain class (member
variables), and variables that are only available to particular instances
of a class (instance variables).

The same goes for functions: some are available everywhere, some are
only available to members of a certain class, and still others are only
available to particular instance objects.
Instructions

1.

Check out the code in the editor. Note that each individual animal gets
its own name and age (since they’re all initialized individually), but they all
have access to the member variable is_alive, since they’re all members
of the Animal class. Click Run to see the output!

class Animal(object):
  """Makes cute animals."""
  is_alive = True
  def __init__(self, name, age):
    self.name = name
    self.age = age

zebra = Animal("Jeffrey", 2)
giraffe = Animal("Bruce", 1)
panda = Animal("Chad", 7)

print zebra.name, zebra.age, zebra.is_alive
print giraffe.name, giraffe.age, giraffe.is_alive
print panda.name, panda.age, panda.is_alive
Jeffrey 2 True
Bruce 1 True
Chad 7 True

12.7 A Methodical Approach


When a class has its own functions, those functions are called methods.
You’ve already seen one such method: __init__(). But you can also
define your own methods!
Instructions

1.

Add a method, description, to your Animal class. Using two


separate print statements, it should print out the name and age of the
animal it’s called on. Then, create an instance of Animal, hippo (with
whatever name and age you like), and call its description method.
Hint

Remember to pass self as an argument to description. Otherwise,


printing self.name and self.age won’t work, since Python won’t know
which self (that is, which object) you’re talking about!

Your method should look something like this:

def description(self):
  print self.name
  print self.age
After that, all you need to do is create a hippo and call its description
method with hippo.description()!

class Animal(object):
  """Makes cute animals."""
  is_alive = True
  def __init__(self, name, age):
    self.name = name
    self.age = age
  # Add your method here!
  def description(self):
    print self.name
    print self.age
    
hippo = Animal("Anderson", 36)
hippo.description()

Anderson
36

12.8 They're Multiplying!


A class can have any number of member variables. These are variables
that are available to all members of a class.

hippo = Animal("Jake", 12)


cat = Animal("Boots", 3)
print hippo.is_alive
hippo.is_alive = False
print hippo.is_alive
print cat.is_alive

1. In the example above, we create two instances of an Animal.

2. Then we print out True, the default value stored in


hippo’s is_alive member variable.

3. Next, we set that to False and print it out to make sure.

4. Finally, we print out True, the value stored in


cat’s is_alive member variable. We only changed the variable in
hippo, not in cat.

Let’s add another member variable to Animal.


Instructions

1.

After line 3, add a second member variable called health that contains


the string "good".

Then, create two new Animals: sloth and ocelot. (Give them whatever


names and ages you like.)

Finally, on three separate lines, print out the health of your hippo, sloth,


and ocelot.
Hint

You can add your member variable right under is_alive, like so:
is_alive = True
health   = "good"
You can print out your hippo‘s health with

print hippo.health

class Animal(object):
  """Makes cute animals."""
  is_alive = True
  health = "good"
  def __init__(self, name, age):
    self.name = name
    self.age = age
  # Add your method here!
  def description(self):
    print self.name
    print self.age
    
hippo = Animal("Anderson", 36)
sloth = Animal("Gerardo", 7)
ocelot = Animal("Patricio", 6)
hippo.description()
print hippo.health
sloth.description()
print sloth.health
ocelot.description()
print ocelot.health

Anderson
36
good
Gerardo
7
good
Patricio
6
good
12.9 It's Not All Animals and Fruit
Classes like Animal and Fruit make it easy to understand the concepts of
classes and instances, but you probably won’t see many zebras or
lemons in real-world programs.

However, classes and objects are often used to model real-world


objects. The code in the editor is a more realistic demonstration of the
kind of classes and objects you might find in commercial software.
Here we have a basic ShoppingCart class for creating shopping cart
objects for website customers; though basic, it’s similar to what you’d
see in a real program.
Instructions

1.

Create an instance of ShoppingCart called my_cart. Initialize it with any


values you like, then use the add_item method to add an item to your
cart.
Hint

Since the ShoppingCart class has an __init__() method that takes a


customer name, I’d create my cart like so:

my_cart = ShoppingCart("Eric")
Calling the add_item() method might then be:

my_cart.add_item("Ukelele", 10)
Concept Review

class ShoppingCart(object):
  """Creates shopping cart objects
  for users of our fine website."""
  items_in_cart = {}
  def __init__(self, customer_name):
    self.customer_name = customer_name

  def add_item(self, product, price):
    """Add product to the cart."""
    if not product in self.items_in_cart:
      self.items_in_cart[product] = price
      print product + " added."
    else:
      print product + " is already in the cart."

  def remove_item(self, product):
    """Remove product from the cart."""
    if product in self.items_in_cart:
      del self.items_in_cart[product]
      print product + " removed."
    else:
      print product + " is not in the cart."
my_cart = ShoppingCart("Carlos")
my_cart.add_item("glasses", 40)

glasses added.

12.10 Warning: Here Be Dragons


Inheritance is a tricky concept, so let’s go through it step by step.

Inheritance is the process by which one class takes on the attributes


and methods of another, and it’s used to express an is-a relationship.
For example, a Panda is a bear, so a Panda class could inherit from a
Bear class. However, a Toyota is not a Tractor, so it shouldn’t inherit
from the Tractor class (even if they have a lot of attributes and
methods in common). Instead, both Toyota and Tractor could
ultimately inherit from the same Vehicle class.
Instructions

1.

Check out the code in the editor. We’ve defined a class, Customer, as well
as a ReturningCustomer class that inherits from Customer. Note that we
don’t define the display_cart method in the body of ReturningCustomer,
but it will still have access to that method via inheritance. Click Run to
see for yourself!

class Customer(object):
  """Produces objects that represent customers."""
  def __init__(self, customer_id):
    self.customer_id = customer_id

  def display_cart(self):
    print "I'm a string that stands in for the contents of your shopping 
cart!"

class ReturningCustomer(Customer):
  """For customers of the repeat variety."""
  def display_order_history(self):
    print "I'm a string that stands in for your order history!"

monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()

I'm a string that stands in for the contents of your


shopping cart!
I'm a string that stands in for your order history!

12.10.1 Inheritance Syntax


In Python, inheritance works like this:

class DerivedClass(BaseClass):
  # code goes here
where DerivedClass is the new class you’re making and BaseClass is the
class from which that new class inherits.
Instructions

1.

On lines 1-4, we’ve created a class named Shape.

 Create your own class, Triangle, that inherits from Shape, like this:

class Triangle(Shape):
# code goes here

 Inside the Triangle class, write an __init__() function that takes


four arguments: self, side1, side2, and side3.

 Inside the __init__() function, set self.side1 = side1, self.side2 =


side2, and self.side3 = side3.

Click “Stuck? Get a hint!” for an example.


Hint
Your code should look something like this:

class Triangle(Shape):
  def __init__(self, side1, side2, side3):
   self.side1 = side1
   self.side2 = side2
   self.side3 = side3

class Shape(object):
  """Makes shapes!"""
  def __init__(self, number_of_sides):
    self.number_of_sides = number_of_sides

# Add your Triangle class below!
class Triangle(Shape):
  def __init__(self, side1, side2, side3):
    self.side1 = side1
    self.side2 = side2
    self.side3 = side3

12.10.2 Override!
Sometimes you’ll want one class that inherits from another to not only
take on the methods and attributes of its parent, but to override one or
more of them.

class Employee(object):
  def __init__(self, name):
    self.name = name
  def greet(self, other):
    print "Hello, %s" % other.name

class CEO(Employee):
  def greet(self, other):
    print "Get back to work, %s!" % other.name

ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
# Hello, Emily
ceo.greet(emp)
# Get back to work, Steve!
Rather than have a separate greet_underling method for our CEO, we
override (or re-create) the greet method on top of the
base Employee.greet method. This way, we don’t need to know what type
of Employee we have before we greet another Employee.
Instructions

1.

Create a new class, PartTimeEmployee, that inherits from Employee.

Give your derived class a calculate_wage method that overrides Employee‘s.


It should take self and hours as arguments.

Because PartTimeEmployee.calculate_wage overrides Employee.calculate_wage,
it still needs to set self.hours = hours.

It should return the part-time employee’s number of hours worked


multiplied by 12.00 (that is, they get $12.00 per hour instead of $20.00).
Hint

In the example code above, we created an overriding CEO.greet method.


It had the same arguments as Employee.greet. You’ll want to add
a calculate_wage() method to your PartTimeEmployee class, and it should
also take self and hours as arguments. Instead of returning hours * 20.00,
though, it should return hours * 12.00.

class Employee(object):
  """Models real-life employees!"""
  def __init__(self, employee_name):
    self.employee_name = employee_name

  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 12
12.10.3 This Looks Like a Job For...
On the flip side, sometimes you’ll be working with a derived class
(or subclass) and realize that you’ve overwritten a method or attribute
defined in that class’ base class (also called a parent or superclass) that
you actually need. Have no fear! You can directly access the attributes
or methods of a superclass with Python’s built-in super call.

The syntax looks like this:

class Derived(Base):
  def m(self):
    return super(Derived, self).m()
Where m() is a method from the base class.
Instructions

1.

First, inside your PartTimeEmployee class:

 Add a new method called full_time_wage with the


arguments self and hours.

 That method should return the result of a super call to


the calculate_wage method of PartTimeEmployee‘s parent class. Use
the example above for help.

Then, after your class:

 Create an instance of the PartTimeEmployee class called milton. Don’t


forget to give it a name.

 Finally, print out the result of calling his full_time_wage method.


You should see his wage printed out at $20.00 per hour! (That is,
for 10 hours, the result should be 200.00.)

Hint

You super call should look something like this:

def full_time_wage(self, hours):


  return super(PartTimeEmployee, self).method(args)
Where method is the method you want (calculate_wage) and args are the
arguments that method takes.
def full_time_wage(self, hours):
    return super(PartTimeEmployye, self, hours).calculate_wage(12) 
milton = PartTimeEmployee("Carlos")
print milton.full_time_wage()

class Employee(object):
  """Models real-life employees!"""
  def __init__(self, employee_name):
    self.employee_name = employee_name

  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 12.00
  
  def full_time_wage(self, hours):
    return super(PartTimeEmployee, self).calculate_wage(hours)

milton = PartTimeEmployee('Milton')
print milton.full_time_wage(10)

200.0

12.10.4 Class Basics


First things first: let’s create a class to work with.
Instructions

1.

Create a class, Triangle. Its __init__() method should


take self, angle1, angle2, and angle3 as arguments. Make sure to set these
appropriately in the body of the __init__() method (see the Hint for
more).
Hint
Make sure your Triangle inherits from object. Remember, class syntax
looks like this:

class ClassName(object):
  def __init__(args):
    # Set self.args = args

class Triangle(object):
  def __init__(self, angle1, angle2, angle3):
    self.angle1 = angle1
    self.angle2 = angle2
    self.angle3 = angle3

12.10.5 Class It Up
Great! Now let’s add a member variable and a method to our class.
Instructions

1.

Inside the Triangle class:

 Create a variable named number_of_sides and set it equal to 3.

 Create a method named check_angles. The sum of a triangle’s


three angles should return True if the sum
of self.angle1, self.angle2, and self.angle3 is equal 180,
and False otherwise.

Hint

The check_angles method should look something like this:

def check_angles(self):
  if (self.angle1 + self.angle2 + self.angle3 == 180):
    return True
  else:
    return False

class Triangle(object):
  def __init__(self, angle1, angle2, angle3):
    self.angle1 = angle1
    self.angle2 = angle2
    self.angle3 = angle3
  number_of_sides = 3
  def check_angles(self):
    if (self.angle1 + self.angle2 + self.angle3 == 180):
      return True
    else:
      return False

12.10.6 Instantiate an Object


Let’s go ahead and create an instance of our Triangle class.
Instructions

1.

Create a variable named my_triangle and set it equal to a new instance


of your Triangle class. Pass it three angles that sum to 180 (e.g. 90, 30,
60).

Print out my_triangle.number_of_sides

Print out my_triangle.check_angles()
Hint

Remember, we can instantiate an object like so:

instance = Class(args)
Where args are the arguments __init__() takes, not including self.

class Triangle(object):
  def __init__(self, angle1, angle2, angle3):
    self.angle1 = angle1
    self.angle2 = angle2
    self.angle3 = angle3
  number_of_sides = 3
  def check_angles(self):
    if (self.angle1 + self.angle2 + self.angle3 == 180):
      return True
    else:
      return False
my_triangle = Triangle(90, 30, 60)

print my_triangle.number_of_sides
print my_triangle.check_angles()

3
True
12.10.7 Inheritance
Finally, let’s create an Equilateral class that inherits from
our Triangle class. (An equilateral triangle is a triangle whose angles are
all 60˚, which also means that its three sides are equal in length.)
Instructions

1.

Create a class named Equilateral that inherits from Triangle.

Inside Equilateral, create a member variable named angle and set it


equal to 60.

Create an __init__() function with only the parameter self, and


set self.angle1, self.angle2, and self.angle3 equal to self.angle (since an
equilateral triangle’s angles will always be 60˚).
Hint

Remember, inheritance looks like this:

class DerivedClass(BaseClass):
  # Your code here
where DerivedClass is the new class you’re making, and BaseClass is the
class it inherits from.

class Triangle(object):
  number_of_sides = 3
  def __init__(self, angle1, angle2, angle3):
    self.angle1 = angle1
    self.angle2 = angle2
    self.angle3 = angle3
    
  def check_angles(self):
    if (self.angle1 + self.angle2 + self.angle3) == 180:
      return True
    else:
      return False
    
class Equilateral(Triangle):
  angle = 60
  def __init__(self):
    self.angle1 = self.angle
    self.angle2 = self.angle
    self.angle3 = self.angle

12.11 CLASSES
12.11.1 Class basics
Classes can be very useful for storing complicated objects with their
own methods and variables. Defining a class is much like defining a
function, but we use the class keyword instead. We also use the
word object in parentheses because we want our classes
to inherit the object class. This means that our class has all the
properties of an object, which is the simplest, most basic class. Later
we’ll see that classes can inherit other, more complicated classes. An
empty class would look like this:

class ClassName(object):
  # class statements go here
Instructions

1.

Define a new class named “Car”. For now, since we have to put
something inside the class, use the pass keyword.

class Car(object):
  pass

12.11.2 Create an instance of a class


We can use classes to create new objects, which we say
are instances of those classes.

Creating a new instance of a class is as easy as saying:

newObject = ClassName()
Instructions

1.
Below your Car class, create a new object named my_car that is an
instance of Car.

class Car(object):
  pass
my_car = Car()

12.11.3 Class member variables


Classes can have member variables that store information about each
class object. We call them member variables since they are information
that belongs to the class object.

Creating member variables and assigning them initial values is as easy


as creating any other variable:

class ClassName(object):
  memberVariable = "initialValue"
Instructions
1.

Inside your Car class, replace the pass statement with a new member


variable named condition and give it an initial value of the string "new".

class Car(object):
  condition = "new"
my_car = Car()

12.12 Calling class member variables


Each class object we create has its own set of member variables. Since
we’ve created an object my_car that is an instance of
the Car class, my_car should already have a member variable
named condition. This attribute gets assigned a value as soon as my_car is
created.
Instructions
1.

At the end of your code, use a print statement to display


the condition of my_car.
Hint
Since the attribute condition belongs to the object my_car, you’ll need to
use dot notation to access the object’s member
variable: my_car.condition.

class Car(object):
  condition = "new"
my_car = Car()
print my_car.condition

new

12.13 Initializing a class


There is a special function named __init__() that gets called whenever
we create a new instance of a class. It exists by default, even though we
don’t see it. However, we can define our own __init__() function inside
the class, overwriting the default version. We might want to do this in
order to provide more input variables, just like we would with any other
function.

The first argument passed to __init__() must always be the


keyword self - this is how the object keeps track of itself internally -
but we can pass additional variables after that.

In order to assign a variable to the class (creating a member variable),


we use dot notation. For instance, if we passed newVariable into our class,
inside the __init__() function we would say:

self.new_variable = new_variable
Instructions

1.

Define the __init__() function of the Car class to take four inputs: self,


model, color, and mpg. Assign the last three inputs to member
variables of the same name by using the self keyword.

Then, modify the object my_car to provide the following inputs at


initialization:
model = "DeLorean"
color = "silver"
mpg = 88
You don’t need to include the self keyword when you create an
instance of a class, because self gets added to the beginning of your
list of inputs automatically by the class definition.
Stuck? Get a hint

Creating an instance of a class with many initialization


variables looks the same as calling a function with many
inputs; put all the values in parentheses, separated by
commas.

In the body of __init__(), you’d set the model like this:

def __init__(self, model, color, mpg):


  self.model = model

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg

my_car = Car("DeLorean", "silver", 88)

12.14 Referring to member variables


Calling class member variables works the same whether those values
are created within the class (like our car’s condition) or values are passed
into the new object at initialization. We use dot notation to access the
member variables of classes since those variables belong to the object.

For instance, if we had created a member variable named new_variable, a


new instance of the class named new_object could access this variable by
saying:

new_object.new_variable
Instructions
1.

Now that you’ve created my_car print its member variables:

 First print the model of my_car. Click “Stuck? Get a hint!” for an


example.

 Then print out the color of my_car.

 Then print out the mpg of my_car.

Hint

To print my_car‘s model, you’d type:

print my_car.model

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg

my_car = Car("DeLorean", "silver", 88)
print my_car.model
print my_car.color
print my_car.mpg

DeLorean
silver
88

12.15 Creating class methods


Besides member variables, classes can also have their own methods.
For example:

class Square(object):
  def __init__(self, side):
    self.side = side
  def perimeter(self):
    return self.side * 4
The perimeter() class method is identical to defining any other function,
except that it is written inside of the Square class definition.

Just like when we defined __init__(), you need to provide self as the


first argument of any class method.
Instructions

1.

Inside the Car class, add a method named display_car to Car that will


reference the Car’s member variables to return the string, "This is a
[color] [model] with [mpg] MPG."  You can use the str() function to turn
your mpg into a string when creating the display string.

Replace the individual print statements with a single print command


that displays the result of calling my_car.display_car()
Hint

Remember, in order to access member variables of a class (even while


inside of that class), we have to use the self keyword and dot notation
to specify that we mean the member variable that belongs to the class.
Concept Review

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg
  def display_car(self):
    print "This is a %s %i with %j MPG" % (self.color, self.model, self.m
pg)

my_car = Car("DeLorean", "silver", str(88))

print my_car.display_car()

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg
   
  def display_car(self):
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(s
elf.mpg))

my_car = Car("DeLorean", "silver", 88)

my_car.display_car()

This is a silver DeLorean with 88 MPG.


12.16 Modifying member variables
We can modify variables that belong to a class the same way that we
initialize those member variables. This can be useful when we want to
change the value a variable takes on based on something that happens
inside of a class method.
Instructions

1.

Inside the Car class, add a method drive_car that sets self.condition to


the string "used".

Remove the call to my_car.display_car() and instead print only


the condition of your car.

Then drive your car by calling the drive_car method.

Finally, print the condition of your car again to see how its value


changes.

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg
   
  def display_car(self):
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(s
elf.mpg))
  def drive_car(self):
    self.condition = "used"

my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition

new
used

12.17 Inheritance
One of the benefits of classes is that we can create more complicated
classes that inherit variables or methods from their parent classes. This
saves us time and helps us build more complicated objects, since
these child classes can also include additional variables or methods.

We define a “child” class that inherits all of the variables and functions
from its “parent” class like so:

class ChildClass(ParentClass):
  # new variables and functions go here
Normally we use object as the parent class because it is the most basic
type of class, but by specifying a different class, we can inherit more
complicated functionality.
Instructions

1.

Create a class ElectricCar that inherits from Car. Give your new class


an __init__() method of that includes a battery_type member variable in
addition to the model, color and mpg.

Then, create an electric car named my_car with a "molten


salt" battery_type. Supply values of your choice for the other three
inputs (model, color and mpg).
Hint
Redefining a method of a “child” class is as simple as including a
definition for that function inside the “child” class; this version will take
precedence over the inherited version.

Remember to include the self keyword as the first input when you


define the __init__() method!

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg
   
  def display_car(self):
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(s
elf.mpg))
    
  def drive_car(self):
    self.condition = "used"
    
class ElectricCar(Car):
  def __init__(self, model, color, mpg, battery_type):
    self.model = model
    self.color = color
    self.mpg   = mpg
    self.battery_type = battery_type

my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")

12.18 Overriding methods


Since our ElectricCar is a more specialized type of Car, we can give the
ElectricCar its own drive_car() method that has different functionality
than the original Car class’s.
Instructions

1.
Inside ElectricCar add a new method drive_car that changes the
car’s condition to the string "like new".

Then, outside of ElectricCar, print the condition of my_car

Next, drive my_car by calling the drive_car function

Finally, print the condition of my_car again


Hint

This should be very similar to what you did in the second exercise of
this section.
class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg
   
  def display_car(self):
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(s
elf.mpg))
    
  def drive_car(self):
    self.condition = "used"
    
class ElectricCar(Car):
  def __init__(self, model, color, mpg, battery_type):
    self.model = model
    self.color = color
    self.mpg   = mpg
    self.battery_type = battery_type
    
  def drive_car(self):
    self.condition = "like new"

my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")

print my_car.condition
my_car.drive_car()
print my_car.condition
new
like new

12.19 Building useful classes


Chances are, you won’t be designing Car classes in the real world
anytime soon. Usually, classes are most useful for holding and
accessing abstract collections of data.

One useful class method to override is the built-in __repr__() method,


which is short for representation; by providing a return value in this
method, we can tell Python how to represent an object of our class (for
instance, when using a print statement).
Instructions

1.

Define a Point3D class that inherits from object

Inside the Point3D class, define an __init__() function that


accepts self, x, y, and z, and assigns these numbers to the member
variables self.x, self.y, self.z

Define a __repr__() method that returns "(%d, %d, %d)" % (self.x, self.y,


self.z). This tells Python to represent this object in the following
format: (x, y, z).

Outside the class definition, create a variable named my_point containing


a new instance of Point3D with x=1, y=2, and z=3.

Finally, print my_point.
Hint

When defining a new __repr__(), return a string value that uses the


member variables of the class to display the 3D point properly. You can
use the str() function to put these numbers in the proper string.

For advanced users: For more information on __repr__ and other


special methods see this Python documentation. Note the slight
difference between the __repr__ and __str__ methods.
Concept Review

class Point3D(object):
  def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z
    
  def __repr__(self):
    return "(%d, %d, %d)" % (self.x, self.y, self.z)
    
my_point = Point3D(1, 2, 3)
print my_point

13 FILE INPUT/OUTPUT
13.1 See It to Believe It
Until now, the Python code you’ve been writing comes from one
source and only goes to one place: you type it in at the keyboard and
its results are displayed in the console. But what if you want to read
information from a file on your computer, and/or write that
information to another file?

This process is called file I/O (the “I/O” stands for “input/output”), and


Python has a number of built-in functions that handle this for you.

Check out the code in the editor to the right.


Instructions

1.

Click Run! You just wrote all the contents of my_list to a text file
called output.txt.

my_list = [i ** 2 for i in range(1, 11)]
# Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w")

for item in my_list:
  f.write(str(item) + "\n")

f.close()

13.2 The open() Function


Let’s walk through the process of writing to a file one step at a time.

The first code that you saw executed in the previous exercise was this:

f = open("output.txt", "w")
This told Python to open output.txt in "w" mode (“w” stands for “write”).
We stored the result of this operation in a file object, f.

Doing this opens the file in write-mode and prepares Python to send
data into the file.
Instructions

1.

Create a variable, my_file, and set it equal to calling the open() function


on output.txt. In this case, pass "r+" as a second argument to the
function so the file will allow you to read and write to it! (See the Hint
for details.)
Hint

You can open files in any of the following modes:

 write-only mode ("w")

 read-only mode ("r")

 read and write mode ("r+")

 append mode ("a"), which adds any new data you write to the file
to the end of the file.
 my_file =  open("output.txt","r+")
13.3 Writing
Good work! Now it’s time to write some data to a new .txt file.

We added the list comprehension from the first exercise to the code in
the editor. Our goal in this exercise will be to write each element of
that list to a file called output.txt. The output.txt file that you write to will
be created in your current folder - for simplicity, the folder has been
hidden. output.txt will list each number on its own line.

We can write to a Python file like so:

my_file.write("Data to be written")
The .write() method takes a string argument, so we’ll need to do a few
things here:

You must close the file. You do this simply by calling my_file.close() (we


did this for you in the last exercise). If you don’t close your file,
Python won’t write to it properly. From here on out, you gotta close
your files!
Instructions

1.

Iterate over my_list to get each value.

Use my_file.write() to write each value to a text file called, output.txt.

Make sure to call str() on the iterating data so .write() will accept it.


Make sure to add a newline (+ "\n") after each element to ensure each
will appear on its own line.

Use my_file.close() to close the file when you’re done.

Passing the exercise means that you successfully


wrote my_list to output.txt!
Hint

Remember, the syntax for iterating over a list looks like this:

for item in list:


  # Do something
You should write to the file inside your iterator, but you should close
the file outside your iterator—otherwise, you’ll attempt to close the file
after you write each line!

And the syntax for calling str() looks like this:

str(42)
# => "42"

my_list = [i ** 2 for i in range(1, 11)]

my_file = open("output.txt", "w")

# Add your code below!
for item in my_list:
  my_file.write(str(item) + "\n")
my_file.close()

Reading
Excellent! You’re a pro.

Finally, we want to know how to read from our output.txt file. As you might expect,
we do this with the read() function, like so:

print my_file.read()
Instructions
1.
Declare a variable, my_file, and set it equal to the file object returned by
calling open() with both "output.txt" and "r".

Next, print the result of using .read() on my_file, like the example above.

Make sure to .close() your file when you’re done with it! All kinds of doom will
happen if you don’t.
Hint
Remember, the syntax for opening a file looks like this:

variable = open("filename", "mode")

my_file = open("output.txt","r")
print my_file.read()
my_file.close()

1
4
9
16
25
36
49
64
81
100

13.4 Reading Between the Lines


What if we want to read from a file line by line, rather than pulling the
entire file in at once. Thankfully, Python includes a .readline() method
that does exactly that.

If you open a file and call .readline() on the file object, you’ll get the
first line of the file; subsequent calls to .readline() will return successive
lines.
Instructions

1.

Declare a new variable my_file and store the result of calling open() on


the "text.txt" file in "r"ead-only mode.
On three separate lines, print out the result of calling my_file.readline().
See how it gets the next line each time?

Don’t forget to .close() your file when you’re done with it!


Hint

Remember, to open a file:

variable = open("filename", "mode")


To read from the file, you can just call variable.readline(). Make sure to
close your file once you’re done reading from it!

my_file = open("text.txt", "r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()

I'm the first line of the file!

I'm the second line.

Third line here, boss.

13.5 PSA: Buffering Data


We keep telling you that you always need to close your files after
you’re done writing to them. Here’s why!

During the I/O process, data is buffered: this means that it is held in a
temporary location before being written to the file.

Python doesn’t flush the buffer—that is, write data to the file—until it’s
sure you’re done writing. One way to do this is to close the file. If you
write to a file without closing, the data won’t make it to the target file.

Instructions

1.

Check out our extremely bad code in the editor. Click Run—you’ll note


that our read_file.read() didn’t read any data back!
 Add a write_file.close() call after writing to the file but before
reading it.

 Add a read_file.close() call after the print read_file.read() line

 Run the code again.

 This time, you’ll see the data come through!


 # Use a file handler to open a file for writing
 write_file = open("text.txt", "w")

 # Open the file for reading
 read_file = open("text.txt", "r")

 # Write to the file
 write_file.write("Not closing files is VERY BAD.")
 write_file.close()

 # Try to read from the file
 print read_file.read()
 read_file.close()

Not closing files is VERY BAD.

13.6 The 'with' and 'as' Keywords


Programming is all about getting the computer to do the work. Is there
a way to get Python to automatically close our files for us?

Of course there is. This is Python.

You may not know this, but file objects contain a special pair of built-in
methods: __enter__() and __exit__(). The details aren’t important, but
what is important is that when a file object’s __exit__() method is
invoked, it automatically closes the file. How do we invoke this
method? With with and as.

The syntax looks like this:

with open("file", "mode") as variable:


  # Read or write to the file
Instructions
1.

Check out the example in the editor. Note that we don’t


explicitly close() our file, and remember that if we don’t close a file, our
data will get stuck in the buffer. Click Run!

Success! is written to a file called text.txt.

with open("text.txt", "w") as textfile:
  textfile.write("Success!")

Try It Yourself
It worked! Our Python program successfully wrote to text.txt.
Instructions
1.
Now you try: write any data you like to a file called text.txt using with…as. Give
your file object the usual name: my_file.
Hint
Remember your syntax:

with open("file","mode") as variable:


  # Read or write to the file

with open("text.txt", "w") as my_file: 
  my_file.write("Does is work really")

13.7 Case Closed?


Finally, we’ll want a way to test whether a file we’ve opened is closed.
Sometimes we’ll have a lot of file objects open, and if we’re not careful,
they won’t all be closed. How can we test this?

f = open("bg.txt")
f.closed
# False
f.close()
f.closed
# True
Python file objects have a closed attribute which is True when the file is
closed and False otherwise.
By checking file_object.closed, we’ll know whether our file is closed and
can call close() on it if it’s still open.
Instructions

1.

Below your with…as code, do two things:

 Check if the file is not closed.

 If that’s the case, call .close() on it.

 (You don’t need an else here, since your if statement should do


nothing if closed is True.)

 After your if statement, print out the value of my_file.closed to


make sure your file is really closed.

Hint

Remember, if statements look like this:

if expression:
  # Do something

with open("text.txt", "w") as my_file:
  my_file.write("My Data!")
  
if not file.closed:
  file.close()

print my_file.closed

True

You might also like