Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Python
# “Python syntax”
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
...
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
...
Print Statements
There are two different Python versions
...
The most significant difference between the two is how you write
a print statement
...
print("Hello World!")
print("Deep into distant woodlands winds a mazy way, reaching to overlapping spurs of
mountains bathed in their hill-side blue
...
If you go on to write Python 3 it will be useful to
note this key difference
...
Text in Python is considered a specific type of data called a string
...
Strings can be defined in different ways:
print "This is a good string"
print 'You can use single quotes or double quotes for a string'
Above we printed two things that are strings and then attempted to print two things that
are not strings
...
We can combine multiple strings using +, like so:
print "This is " + "a good string"
This code will print out "This is a good string"
...
These are complaints that Python makes when it doesn't understand what
you want it to do
...
Here are some common errors that we might run into when printing
strings:
print "Mismatched quotes will cause a SyntaxError'
print Without quotes will cause a NameError
If the quotes are mismatched Python will notice this and inform you that your code has
an error in its syntax because the line ended (called an EOL) before the double-quote
that was supposed to close the string appeared
...
Another issue you might run into is attempting to create a string without quotes at all
...
If it fails to
recognize these words as defined (in Python or by your program elsewhere) Python will
complain the code has a NameError
...
Variables
In Python, and when programming in general, we need to build systems for dealing with
data that changes over time
...
The only important thing is that it
may be different at different times
...
greeting_message = "Welcome to Codecademy!"
current_excercise = 5
In the above example, we defined a variable called greeting_message and set it equal
to the string "Welcome to Codecademy!"
...
Arithmetic
One thing computers are capable of doing exceptionally well is performing arithmetic
...
Some examples:
mirthful_addition = 12381 + 91817
amazing_subtraction = 981 - 312
trippy_multiplication = 38 * 902
happy_division = 540 / 45
sassy_combinations = 129 * 1345 + 120 / 6 - 12
Above are a number of arithmetic operations, each assigned to a variable
...
Combinations of arithmetical operators follow
the usual order of operations
...
The modulo
operator is indicated by % and returns the remainder after division is performed
...
Since 15 is an odd number the remainder is 1
...
Since 133 divided by 7 has no remainder,
133 % 7evaluates to 0
...
As the flow of a
program progresses, data should be updated to reflect changes that have happened
...
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
...
Updating a variable by adding or subtracting a number to the original contents of the
variable has its own shorthand to make it faster and easier to read
...
50
sales_tax =
...
After
calculating the tax we add it to the total price of the sandwich
...
Comments
Most of the time, code should be written in such a way that it is easy to understand on
its own
...
A line of text preceded by a # is called a comment
...
When you look back at
your code later, comments may help you figure out what it was intended to do
...
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
...
0
float2 = 10
...
5
You can also define a float using scientific notation, with e indicating the power of 10:
# this evaluates to 150:
float4 = 1
...
When the
quotient is a whole number, this works fine:
quotient = 6/2
# the value of quotient is now 3, which makes sense
However, if the numbers do not divide evenly, the result of the division is truncated into
an integer
...
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
...
/2
# the value of quotient1 is 3
...
# the value of quotient2 is 3
...
/2
...
5
Multi-line Strings
We have seen how to define a string with single quotes and with double quotes
...
When a string like this is not assigned to a variable, it works as a multi-line comment
...
"
"""
...
This datatype,
which can only ever take one of two values, is called a boolean
...
A value of True corresponds to an
integer value of 1, and will behave the same
...
ValueError
Python automatically assigns a variable the appropriate datatype based on the value it
is given
...
is a float, "7" is a string
...
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 this using int():
number1 = "100"
number2 = "10"
string_addition = number1 + number2
#string_addition now has a value of "10010"
int_addition = int(number1) + int(number2)
#int_addition has a value of 110
If you use int() on a floating point number, it will round the number down
...
5"
print int(string_num)
print float(string_num)
>>> 7
>>> 7
...
A string can contain letters, numbers, and
symbols
...
In the above example, we create a variable name and set it to the
string value "Ryan"
...
We also set age to "19" and food to "cheese"
...
Escaping characters
There are some characters that cause problems
...
We can use the backslash to fix the problem, like this:
'There\'s a snake in my boot!'
Access by Index
Great work!
Each character in a string is assigned a number
...
Check out the diagram in the editor
...
In the above example, we create a new variable called c and set it to
"c", the character at index zero of the string "cats"
...
Next, we create a new variable called n and set it to "n", the character
at index three of the string "Ryan"
...
This is because in Python indices begin counting at 0
...
String methods
Great work! Now that we know how to store strings, let's see how we can change
them using string methods
...
We'll focus on four string methods:
1
...
lower()
3
...
str()
Let's start with len(), which gets the length (the number of characters) of a string!
lower()
Well done!
You can use the lower() method to get rid of all the capitalization in your strings
...
lower()
which will return "ryan"
...
str()
Now let's look at str(), which is a little less straightforward
...
Dot Notation
Let's take a closer look at why you use len(string) and str(object), but dot
notation (such as "String"
...
lion = "roar"
len(lion)
lion
...
On the other hand, len() and str() can work on other data types
...
The console (the window to the right of the editor) is where the results of your
code is shown
...
String Concatenation
You know about strings, and you know about arithmetic operators
...
The + operator between strings will 'add' them together, one after the other
...
Combining strings together like this is called concatenation
...
In
order to do that, you have to convert the non-string into a string
...
The str() method converts non-strings into strings
...
String Formatting with %, Part 1
When you want to print a variable with a string, there is a better method than
concatenating strings together
...
The %
operator will replace the %s in the string with the string variable that comes after
it
...
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)
...
name = "Mike"
print "Hello %s" % (name)
You need the same number of %s terms in a string as the number of variables in
parentheses:
print "The %s who %s %s!" % ("Knights", "say", "Ni")
# This will print "The Knights who say Ni!"
And Now, For Something Completely Familiar
Great job! You've learned a lot in this unit, including:
Three ways to create strings
'Alpha'
"Bravo"
str(3)
String methods
len("Charlie")
"Delta"
...
lower()
Printing a string
print "Foxtrot"
Advanced printing techniques
g = "Golf"
h = "Hotel"
print "%s, %s" % (g, h)
DATE AND TIME
The datetime Library
A lot of times you want to keep track of when something happened
...
Here we'll use datetime to print the date and time in a nice format
...
now() to retrieve the current date and time
...
now()
The first line imports the datetime library so that we can use it
...
Extracting Information
Notice how the output looks like 2013-11-25 23:45:14
...
What if you don't
want the entire date and time?
from datetime import datetime
now = datetime
...
year
current_month = now
...
day
You already have the first two lines
...
In the fourth and fifth lines, we store the month and day from now
...
Let's use
string substitution again!
from datetime import datetime
now = datetime
...
month, now
...
year)
# will print the current date as mm-dd-yyyy
Remember that the standalone % operator after the string will fill the %02d and %04d
placeholders in the string on the left with the numbers and strings in the parentheses on
the right
...
This is one way dates are commonly displayed
...
from datetime import datetime
now = datetime
...
hour
print now
...
second
In the above example, we just printed the current hour, then the current minute, then the
current second
...
Grand Finale
We've managed to print the date and time separately in a very pretty fashion
...
now()
print '%02d/%02d/%04d' % (now
...
day, now
...
hour, now
...
second)
The example above will print out the date, then on a separate line it will print the time
...
The Python programs we've written so far have had one-track minds: they can
add two numbers or print something, but they don't have the ability to pick one
of these outcomes over the other
...
Compare Closely!
Let's start with the simplest aspect of control flow: comparators
...
Note that == compares whether two things are equal, and = assigns a value to a
variable
...
Closelier!
Excellent! It looks like you're comfortable with basic expressions and
comparators
...
# Make me true!
bool_one = 3 < 5
Let's switch it up: we'll give the boolean, and you'll write the expression, just like
the example above
...
There are
three boolean operators:
1
...
or, which checks if at least one of the statements is True;
3
...
We'll go through the operators one by one
...
For instance:
● 1 < 2 and 2 < 3 is True;
● 1 < 2 and 2 > 3 is False
...
For example:
● 1 < 2 or 2 > 3 is True;
● 1 > 2 or 2 > 3 is False
...
For example:
● not False will evaluate to True, while not 41 > 40 will return False
...
Just like with arithmetic
operators, there's an order of operations for boolean operators:
1
...
and is evaluated next;
3
...
For example, True or not False and Falsereturns True
...
Parentheses () ensure your expressions are evaluated in the order you want
...
Mix 'n' Match
Great work! We're almost done with boolean operators
...
Here's an example of if statement syntax:
if 8 < 9:
print "Eight is less than nine!"
In this example, 8 < 9 is the checked expression and print "Eight is less than
nine!" is the specified code
...
This space, called
white space, is how Python knows we are entering a new block of code
...
In this lesson, we
use four spaces but elsewhere you might encounter two-space indentation or
tabs (which Python will see as different from spaces)
...
These errors could mean, for example, that one line had two
spaces but the next one had three
...
If You're Having
...
Remember, the syntax looks like this:
if some_function():
# block line one
# block line two
# et cetera
Looking at the example above, in the event that some_function() returns True,
then the indented block of code after it will be executed
...
Also, make sure you notice the colons at the end of the if statement
...
Else Problems, I Feel Bad for You, Son
...
An if/else pair says: "If this
expression is true, run this indented code block; otherwise, run this code after
the else statement
...
For example:
if 8 > 9:
print "I don't printed!"
else:
print "I get printed!"
I Got 99 Problems, But a Switch Ain't One
elif is short for "else if
...
The Big If
Really great work! Here's what you've learned in this unit:
Comparators
3<4
5 >= 5
10 == 10
12 != 13
Boolean operators
True or False
(3 < 4) and (5 >= 5)
this() and not that()
Conditional statements
if this_might_be_true():
print "This really is true
...
"
else:
print "None of the above
...
PYGLATIN
Break It Down
Now let's take what we've learned so far and write a Pig Latin translator
...
" So "Python" becomes "ythonpay
...
Ask the user to input a word in English
...
Make sure the user entered a valid word
...
Convert the word from English to Pig Latin
...
Display the translation result
...
Input!
Next, we need to ask the user for input
...
In the interpreter, Python will ask:
What's your name?
Once you type in your name and hit Enter, it will be stored in name
...
empty_string = ""
if len(empty_string) > 0:
# Run this block
...
We can check that the user's string actually has characters!
Consider the following code:
x = "J123"
x
...
The second line then runs the method
...
You can use
...
Example: python -> ythonpay
Let's create a variable to hold our translation suffix
...
the_string = "Hello"
the_string = the_string
...
lower() function does not modify the string itself, it simply returns a lowercaseversion
...
We also need to grab the first letter of the word
...
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
...
e
...
Y
...
s = "Charlie"
print s[0]
# will print "C"
print s[1:4]
# will print "har"
1
...
Next we access the first letter of "Charlie"using s[0]
...
3
...
This returns everything
from the letter at position 1 up till position 4
...
isalpha():
word = original
...
Instead of rewriting the whole code, it's much cleaner to
define a function, which can then be used repeatedly
...
"""
bill *= 1
...
"""
bill *= 1
...
The header, which includes the def keyword, the name of the function, and
any parametersthe function requires
...
def hello_world(): # There are no parameters
3
...
4
...
"""
5
...
The body
is indented, just like conditional statements
...
print "Hello World!"
Here's the full function pieced together:
def hello_world():
"""Prints 'Hello World!' to the console
...
In the previous exercise,
spam() in the last line told the program to look for the function called spam and
execute the code inside it
...
A parameter is a variable that is an input to a
function
...
" A function can have any number of
parameters
...
Recall in the previous example, we called:
square(10)
Here, the function square was called with the parameter n set to the argument 10
...
To summarize:
● When defining a function, placeholder variables are called parameters
...
Functions Calling Functions
We've seen functions that can print text or do simple arithmetic, but functions can be
much more powerful than that
...
def shout(phrase):
if phrase == phrase
...
Don't forget the colon at the end of your function definition!
Generic Imports
Did you see that? Python said: NameError: name 'sqrt' is not defined
...
There is a Python module named math that includes a number of useful variables and
functions, and sqrt() is one of those functions
...
When you simply import a module this way, it's called a generic
import
...
However, we only really needed the sqrt function, and it can be frustrating to have to
keep typing math
...
It's possible to import only certain variables or functions from a given module
...
sqrt()!
Universal Imports
Great! We've found a way to handpick the variables and functions we want from
modules
...
?
Universal import can handle this for you
...
If you have a function of your very own named sqrtand you import math, your function
is safe: there is your sqrt and there is math
...
If you do from math import *,
however, you have a problem: namely, two different functions with the exact same
name
...
For these reasons, it's best to stick with either import module and type module
...
import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print everything # Prints 'em all!
On Beyond Strings
Now that you understand what functions are and how to import modules, let's look at
some of the functions that are built in to Python (no modules required!)
...
upper(),
...
These are great for doing work with strings, but
what about something a little more analytic?
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)
max()
The max() function takes any number of arguments and returns the largest one
...
)
For example, max(1,2,3) will return 3 (the largest number in the set of arguments)
...
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
...
The abs() function always returns a positive
value, and unlike max() and min(), it only takes a single number
...
If
you ask Python to do the following:
print type(42)
print type(4
...
def speak(message):
return message
if happy():
speak("I'm happy!")
elif sad():
speak("I'm sad
...
")
Again, the example code above is just there for your reference!
Review: Built-In Functions
Perfect! Last but not least, let's review the built-in functions you've learned about in this
lesson
...
def bigger(first, second):
print max(first, second)
return True
In the example above:
1
...
2
...
3
...
Now try creating a function yourself!
Instructions
1
...
Even without arguments, you will still need parentheses
...
def wages(hours):
# If I make $8
...
return 8
...
Let's use functions to calculate your trip's costs
...
Define a function called hotel_cost with one argument nights as input
...
So, the function hotel_cost should return 140
* nights
...
def fruit_color(fruit):
if fruit == "apple":
return "red"
elif fruit == "banana":
return "yellow"
elif fruit == "pear":
return "green"
1
...
2
...
1
...
The function should return a different price depending on the location, similar to
the code example above
...
● "Charlotte": 183
● "Tampa": 220
● "Pittsburgh": 222
● "Los Angeles": 475
Transportation
You're also going to need a rental car in order for you to get around
...
Then, we check the value of score multiple times
...
First, we check if score is greater than or equal to 10
...
2
...
3
...
Remember that an elif statement is only checked if all preceding if/elif statements fail
...
Below your existing code, define a function called rental_car_cost with an
argument called days
...
● if you rent the car for 7 or more days, you get $50 off your total
...
● You cannot get both of the above discounts
...
Just like in the example above, this check becomes simpler if you make the 7day check an if statement and the 3-day check an elif statement
...
def double(n):
return 2 * n
def triple(p):
return 3 * p
def add(a, b):
return double(a) + triple(b)
1
...
Notice that they have n and p as their arguments
2
...
Notice that even
though the names of the parameters for add(a, b) are different than the
names of the parameters for double(n) and triple(p) we can still pass them
into those functions as arguments
1
...
Notice that we changed the argument of hotel_costs() from nights to days - 1
...
If you are going to be staying somewhere, the
number of nights you stay there is one less than the number of days you were
there (imagine a weekend trip to visit family, you leave Saturday and return
Sunday, so you visit for two days, but only stay for one night)
...
There also needs to be room for additional costs like fancy food or
souvenirs
...
Modify your trip_cost function definition
...
Modify what the trip_cost function does
...
Plan Your Trip!
Nice work! Now that you have it all together, let's take a trip
...
After your previous code, print out the trip_cost( to "Los Angeles" for 5days
with an extra 600 dollars of spending money