Python 2 Lessons
Python 2 Lessons
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.
1.
1.
1.
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).
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
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
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"
1.13 Review
Great! So far we’ve looked at:
Print statements
Instructions
1.
Let’s apply all of the concepts you have learned one more time!
5.
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!")
name = "Ryan"
age = "19"
food = "cheese"
c = "cats"[0]
n = "Ryan"[3]
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.
1. len()
2. lower()
3. upper()
4. str()
Let’s start with len(), which gets the length (the number of characters) of a
string!
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.
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".
lion = "roar"
len(lion)
lion.upper()
Methods that use dot notation only work with strings.
ministry = "The Ministry of Silly Walks"
print len(ministry)
print ministry.upper()
The console (the window to the right of the editor) is where the results of your
code is shown.
the_machine_goes= "Ping!"
print the_machine_goes
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.
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"
# Turn 3.14 into a string on line 3!
print "The value of pi is around " + str(3.14)
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.
1.
Now it’s your turn! We have ___ in the code to show you what you need
to change!
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:
1.
Here we’ll use datetime to print the date and time in a nice format.
Instructions
1.
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.
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.
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
%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.
from datetime import datetime
now = datetime.now()
print "%02d/%02d/%04d" % (now.month, now.day, now.year)
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.
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)
1.
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()
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.
1.
1.
1.
For each boolean value in the editor, write an expression that evaluates
to that value. Remember, comparators are: ==, !=, >, >=, <, and <=.
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.
Instructions
1.
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:
Instructions
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:
Instructions
1.
1.
1.
This time we’ll give the expected result, and you’ll use some
combination of boolean operators to achieve that result.
# 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)
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.
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.
def using_control_again():
if 100 != 10**10:
return "Success #2"
print using_control_once()
print using_control_again()
1.
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
1.
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)
1.
1.
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).
1.
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!
1.
# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0:
print original
else:
print "empty"
You can use .isalpha() to check that a string doesn’t contain any non-
letter characters! For example:
Instructions
1.
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
1.
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.
1.
Inside your if statement:
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
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"
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'
When you’re sure your translator is working just the way you want it,
click Run Code to finish this project.
1.
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.
1.
def spam():
"""Prints 'Eggs!' to the console."""
print "Eggs!"
1.
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)
Typically, when you call a function, you should pass in the same
number of arguments as there are parameters.
To summarize:
Instructions
1.
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.
Instructions
1.
First, def a function called cube that takes an argument called number.
Don’t forget the parentheses and the colon!
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False
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.
Instructions
1.
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
Universal import can handle this for you. The syntax for this is:
from module import *
Instructions
1.
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.
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!
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.)
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.
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.
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.
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
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)
max(2, 3, 4) # 4
min(2, 3, 4) # 2
abs(2) # 2
abs(-2) # 2
Instructions
1.
1.
def answer():
return 42
1.
ef hotel_cost(nights):
return 140*nights
Instructions
1.
"Charlotte": 183
"Tampa": 220
"Pittsburgh": 222
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.
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.
def triple(p):
return 3 * p
1.
def trip_cost(city,days):
return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(c
ity)
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.
def trip_cost(city,days,spendig_money):
return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(c
ity) + spendig_money
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.
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.)
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]
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]
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"
Instructions
1.
# 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
1.
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]
1.
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:]
2. Then, we print the first index that contains the string "bat", which
will print 1.
Instructions
1.
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
1.
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
3. Then, for each item in animals, we print that item out as "ant",
"bat", "cat" on their own line each.
Instructions
1.
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
1.
# 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
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}
1.
# 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
1.
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')
print backpack
Instructions
1.
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
1.
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
print name
Adam
Alex
Mariah
Martine
Columbus
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.
# 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]
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.
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
Instructions
1.
for each item in x:, if that
item is equal to the string "fizz" then
increment the count variable.
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
1.
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
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.
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
1.
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]
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.
Like the example above, for each key, print out the key along with its
price and stock information.
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
1.
Let’s determine how much money you would make if you sold all of
your food.
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
1.
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.
Instructions
1.
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
1.
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:
1.
1.
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" : []
}
1.
Make sure to include the decimal points so your grades are stored
as floats! This will be important later.
1.
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]
1.
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
5.0 / 2
# 2.5
float(5) / 2
# 2.5
The above example is a reminder of how division works in Python.
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.
def average(numbers):
total = sum(numbers)
total = float(total)
return total / len(numbers)
PRACTICAR
1.
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
1.
Otherwise: return "F"
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.
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
1.
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]
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
1.
n = [1, 3, 5]
# Append the number 4 here
n.append(4)
print n
[1, 3, 5, 4]
1.
n = [1, 3, 5]
# Remove the first item in the list here
n.pop(0)
print n
[3, 5]
1.
number = 5
def my_function(x):
return x * 3
print my_function(number)
1.
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
1.
n = "Hello"
# Your function here!
def string_function(s):
return s + "world"
print string_function(n)
1.
def list_function(x):
return x
n = [3, 5, 7]
print list_function(n)
[3, 5, 7]
numbers = [2, 7, 9]
first_item(numbers)
Instructions
1.
def list_function(x):
return x[1]
n = [3, 5, 7]
print list_function(n)
numbers = [1, 2, 3, 4]
double_first(numbers)
print numbers
1.
Change list_function to:
def list_function(x):
x[1]=x[1]+3
return x
n = [3, 5, 7]
print list_function(n)
[3, 8, 7]
1.
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.
1.
Inside that function, print out each element one by one. Use the
existing code as a scaffold.
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
1.
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)
1. range(stop)
2. range(start, stop)
1.
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]
1.
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
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.
Finally, return the result.
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.
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]
3. For each of the two inner lists (as lst), we iterate through the
numbers (as item) and print them out.
1.
Iterate through numbers.
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.
1.
Use range() to loop 5 times.
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)
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.
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.
1.
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.
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)
1.
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: "))
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.
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:
1.
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.
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)
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)
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.
If that is the case, print out "Oops, that's not even in the ocean."
1.
Add an elif to see if the guessed location already has an ‘X’ in it.
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)
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.
1.
Add a for loop that repeats the guessing and checking part of your
game for 4 turns, like the example above.
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)
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.
2. We’ll want to print the message no matter what the cause of the
miss
Instructions
1.
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
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)
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!
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.
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
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.
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
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.
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
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: ")
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.
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.
1.
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!"
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.
Ask the user for their guess, just like the second example above.
Decrement guesses_left by one.
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!"
1.
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.
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
1.
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
!
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.
1.
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 . . .
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.
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
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!"
2. Then, we iterate through the dictionary, each time storing the key
in key.
Instructions
1.
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
# Your code here!
print key, d[key]
a apple
c cherry
b berry
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
zip will
create pairs of elements when passed two lists, and will stop at
the end of the shorter list.
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.
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
1.
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.
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!
1.
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.
1.
Otherwise, return False.
Hint
The modulo % operation is useful for determining if one number is
divisible by another.
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.
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.
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
factorial(1) would equal 1.
Instructions
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!)
1.
If it is, return False.
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.
8.22 anti_vowel
Nice work. Next up: vowels!
Instructions
1.
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).
1.
Your function should work even if the letters you get are
uppercase, lowercase, or a mix.
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.
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:
should return:
```py
"this **** is wack ****"
Hint
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")
1.
There is a list method in Python that you can use for this, but you
should do it the long way for practice.
Hint
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.
Do not directly modify the list you are given as input; instead, return a
new list with only the even numbers.
Hint
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.
Hint
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.
The order in which you present your output does not matter. So
returning [1, 2, 3] is the same as returning [3, 1, 2].
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.
sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
Instructions
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!
Hint
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.
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
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!
This mini-project will give you some practice with functions, lists, and
translating mathematical formulae into programming statements.
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.
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.
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.
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.
1.
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
The average test grade can be found by dividing the sum of the grades
by the total number of grades.
1.
Calls grades_sum with grades_input
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.
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.
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.
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
Who needs to pay for grade calculation software when you can write
your own? :)
Instructions
1.
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
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.
my_dict = {"Name": "Carlos", "Age": 57, "BDFL": True}
print my_dict.items()
Again, these methods will not return the keys or values from the
dictionary in any specific order.
1.
print my_dict.keys()
d = {
"name": "Eric",
"age": 26
}
for key in d:
print key, d[key],
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
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
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?
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]
1.
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
1.
cubes_by_four = [x**3 for x in range(1,11) if (x**3)%4 == 0]
print cubes_by_four
[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.
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]
print to_five[3:]
# prints ['D', 'E']
print to_five[:2]
# prints ['A', 'B']
print to_five[::2]
# print ['A', 'C', 'E']
Instructions
1.
Omit the start and end index. You only need to specify a stride.
[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.
1.
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]
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.
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]
Let’s do one more, just to prove you really know your stuff.
Instructions
1.
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.
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)
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.
languages = ["HTML", "JavaScript", "Python", "Ruby"]
# Add arguments to the filter()
print filter(lambda x: x == "Python", languages)
['Python']
1.
squares = [x**2 for x in range(1,11)]
print filter(lambda x: x >=30 and x<= 70, squares)
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
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()
1.
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.
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]
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.
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"
Bitwise operations might seem a little esoteric and tricky at first, but
you’ll get the hang of them pretty quickly.
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
The binary number ‘1010’ is 10 in base 2 because the 8’s bit and the 2’s
bit are “on”:
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.
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!
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.)
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
0b1
0b10
0b11
0b100
0b101
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
1
2
7
4
5
201
The block below shows how these operators work on the bit level. Note
that in the diagram, the shift is always a positive integer:
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
shift_right = 0b1100 >> 2
shift_left = 0b1 << 2
# Your code here!
print bin(shift_right)
print bin(shift_left)
0b11
0b100
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.
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Therefore,
1.
a = 0b1110 & 0b101
print bin(a)
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.
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
Meaning
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
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.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
Therefore:
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
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.
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.
4. If desired is greater than zero, then the third bit of num must have
been one.
Instructions
1.
It should check to see if the fourth bit from the right is on.
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.
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
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.
Flip the nth bit (with the ones bit being the first bit) and store it
in 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?
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.
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."
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
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.
def __init__(self):
pass
class Animal(object):
def __init__(self):
pass
1.
Hint
class Animal(object):
def __init__(self, name):
# Set the name parameter here!
class Animal(object):
def __init__(self, name):
self.name = name
pass
class Square(object):
def __init__(self):
self.sides = 4
my_shape = Square()
print my_shape.sides
Instructions
1.
Then print out zebra‘s name.
Hint
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!
1.
# 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
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
1.
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
1.
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.
1.
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.
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()
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.
class Triangle(Shape):
# code goes here
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.
Because PartTimeEmployee.calculate_wage overrides Employee.calculate_wage,
it still needs to set self.hours = hours.
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.
class Derived(Base):
def m(self):
return super(Derived, self).m()
Where m() is a method from the base class.
Instructions
1.
Hint
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
1.
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:
Hint
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
1.
Print out my_triangle.number_of_sides
Print out my_triangle.check_angles()
Hint
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.
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
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()
class ClassName(object):
memberVariable = "initialValue"
Instructions
1.
class Car(object):
condition = "new"
my_car = Car()
class Car(object):
condition = "new"
my_car = Car()
print my_car.condition
new
self.new_variable = new_variable
Instructions
1.
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)
new_object.new_variable
Instructions
1.
Hint
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
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.
1.
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()
1.
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.
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")
1.
Inside ElectricCar add a new method drive_car that changes the
car’s condition to the string "like new".
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
1.
Finally, print my_point.
Hint
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?
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()
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.
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.
my_file.write("Data to be written")
The .write() method takes a string argument, so we’ll need to do a few
things here:
1.
Remember, the syntax for iterating over a list 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".
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:
my_file = open("output.txt","r")
print my_file.read()
my_file.close()
1
4
9
16
25
36
49
64
81
100
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.
my_file = open("text.txt", "r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()
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.
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.
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("text.txt", "w") as my_file:
my_file.write("Does is work really")
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.
Hint
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