Python (Notes, Ch. 1-7)
Python (Notes, Ch. 1-7)
Python (Notes, Ch. 1-7)
The # sign will only comment out a single line. While you could write a multi-line
comment, starting each line with #, that can be a pain.Instead, for multi-line comments,
you can include the whole block in a set of triple quotation marks:
you can combine math with other data types (e.g. booleans) and commands
to create useful programs.
o use ** for ^
Our final operator is modulo. Modulo returns the remainder from a division.
o In computing, the modulo operation finds the remainder after division of one
number by another (sometimes called modulus).
o Given two positive numbers, a (the dividend) and n (the divisor), a modulo n
(abbreviated as a mod n) is the remainder of the Euclidean division of a by n. For
instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2
leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0
because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0
Recap:
Tip Calculator:
Another useful data type is the string. A string can contain letters, numbers,
and symbols.
Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to
fix the problem, like this:
Printing Strings:
The area where we've been writing our code is called the editor.
The console (the window in the upper right) is where the results of your code is shown.
'add' them together, one after the other. Notice that there are spaces inside
the quotation marks
o Ex; print "Life " + "of " + "Brian". You have to make sure there is
space between Life and .so its life and not life
The % operator after a string is used to combine a string with variables. The %
operator will replace a %s in the string with the string variable that comes
after it.
o string_1 = "Camelot"
o string_2 = "place"
o
o print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
The \ character on line 5 is a continuation marker. It simply tells Python that line 5
continues onto line 6.
String methods
len("Charlie")
"Delta".upper()
"Echo".lower()
Printing a string
print "Foxtrot"
o The second line will print out the current date and time.
To change format:
o
o
o
o
o
o
Control flow gives us this ability to choose among outcomes based off what
else is happening in the program.
Let's start with the simplest aspect of control flow: comparators. There are six:
1. Equal to (==)
2. Not equal to (!=)
3. Less than (<)
4. Less than or equal to (<=)
5. Greater than (>)
6. Greater than or equal to (>=)
o
Note that == compares whether two things are equal, and = assigns a
value to a variable.
Boolean operators compare statements and result in boolean values. There are three
boolean operators:
Just like with arithmetic operators, there's an order of operations for boolean operators:
1. not is evaluated first;
2. and is evaluated next;
3. or is evaluated last.
o For example, True or not False and False returns True
o
o
o
is a conditional statement that executes some specified code after checking if its
expression is True.
o Here's an example of if statement syntax:
if
if 8 < 9:
print "Eight is less than nine!"
The else statement complements the if statement.
"Elif" is short for "else if." It means exactly what it sounds like: "otherwise, if
the following expression is true, do this!"
In python the indentation is very important !!!
o
return True
PigLatin:
o if and else do NOT need to be indented.
o Let's make sure the word the user enters contains only alphabetical
characters. You can use isalpha() to check this!
o Advanced Tip! When slicing until the end of the string, instead of providing
len(new_word), you can also not supply the second index:
Functions:
o Instead of rewriting the whole code, it's much cleaner to define a function,
which can then be used repeatedly.
o Universal import can handle this for you. The syntax for this is:
Function:
o
print type(42)
print type(4.2)
print type('spam')
<type 'int'>
<type 'float'>
<type 'str'>
def fruit_color(fruit):
if fruit == "apple":
return "red"
elif fruit == "banana":
return "yellow"
elif fruit == "pear":
return "green"
1. The example above defines the function fruit_color that accepts a string as the
argument fruit.
2. The function returns a string if it knows the color of that fruit.
Lists and Dictionaries:
o Lists are a datatype you can use to store a collection of different pieces of
zoo_animals[2] = "hyena"
# Changes "sloth" to "hyena"
You can add to your list later on by doing ____.append()
o .append only can add one at a time
o Len(____) will do the list length
o You can slice a string exactly like a list! In fact, you can think of strings as lists of
characters: each character is a sequential item in the list, starting from index 0.
o
o
o
o
o
o
my_list[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last items
If your list slice includes the very first or last item in a list
(or a string), the index for that item doesn't have to be
included.
If you want to do something with every item in the list, you can
use a for loop.
A variable name follows the for keyword; it will be assigned
the value of each list item in turn.
Then in list_name designates list_name as the list the loop
will work on. The line ends with a colon (:) and the
indented code that follows it will be executed once per item
in the list.
.sort() modifies the list rather than returning a new list.
o Key
o A dictionary is similar to a list, but you access values by looking up a key instead of an
index. A key can be any string or number. Dictionaries are enclosed in curly braces, like
so:
o
residents['Puffin']
# Gets the value 104
o Like Lists, Dictionaries are "mutable". This means they can be changed after they are
created. One advantage of this is that we can add new key/value pairs to the dictionary
after it is created like so:
o
dict_name[new_key] = new_value
o An empty pair of curly braces {} is an empty dictionary, just like an empty pair of
[] is an empty list.
o
o
o
del dict_name[key_name]
<- this deletes
dict_name[key] = new_value <- this adds a new value
removing a new item is
.remove(item)
o for loops allow us to iterate through all of the elements in a list from the left-most (or
zeroth element) to the right-most element. A sample loop would be structured as follows:
o
o
o
o This loop will run all of the code in the indented block under the for x in a:
statement.
o You can also use a for loop on a dictionary to loop through its keys with the following:
o
o
o
o
o
# A simple dictionary
d = {"foo" : "bar"}
for key in d:
print d[key]
# prints "bar"
o 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.
o Create a new dictionary called prices using {} format like the example above.
o Put these values in your prices dictionary, in between the {}:
Remember to use square brackets for a list: [].
5 / 2
# 2
5.0 / 2
# 2.5
float(5) / 2
# 2.5
1. n.pop(index) will remove the item at index from the list and return it to you:
n = [1, 3, 5]
n.pop(1)
1. del(n[1]) is like .pop in that it will remove the item at the given index, but it won't
return it:
del(n[1])
# Doesn't return anything
print n
# prints [1, 5]
Method 1 is useful to loop through the list, but it's not possible to modify the list this way.
Method 2 uses indexes to loop through the list, making it possible to also modify the list if
needed. Since we aren't modifying the list, feel free to use either one on this lesson!
1M*(1+x-2*x^2)