Markdown cell demo
This is a markdown (text) cell!
Code cell demo
Python basics
File "<ipython-input-2-a2f0334f2607>", line 1
print "hello, world!"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello, world!")?
Notice that when you use print
, there is no Out[]
prompt, but if you just have number on a line by itself, there is:
The difference is that you can use print
anywhere, but having something on a line by itself must be the last line in the cell:
Math operations
You can use Python just like a calculator! Just write math how you'd write it normally:
One exception is exponents. If I want to do , I need to use double asterisks **
:
Order of operations
If you're doing multiple operations, be careful about the order! Operations take precedence in this order:
Negation (e.g.
-4
)Exponents (e.g.
3 ** 2
)Multiplication and division (e.g.
4 * 5
or4 + 5
)Addition and subtraction (e.g.
8 + 3
or8 - 3
)
It is a good rule of thumb to always use parentheses to group things in the way you want them:
If you leave off the parentheses, you might get a different answer!
This is equivalent to the version without parentheses:
Variables
Variables in Python can store any value:
Once defined, they can be used just like the values we had above:
However, if a variable is not defined, you will get an error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-9063a9f0e032> in <module>
----> 1 y
NameError: name 'y' is not defined
A variable is "defined" the first time you give it a value, not the first time you use it. To give y
a value, we just need to put something to the right of the equals sign:
Then we can look at its value:
Datatypes
Numbers
This is an integer:
Numbers that have a decimal are floats:
Using type can be espcially useful if you have a variable:
Booleans
Booleans are true/false values. They get special symbols (note that the case matters):
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-295-74d9a83219ca> in <module>()
----> 1 true
NameError: name 'true' is not defined
Strings
Strings get wrapped in quotes, like this:
If you forget the quotes, you'll get an error (in this case, a SyntaxError
, because it expects there to be operators between the symbols I
, am
, a
, and string
):
File "<ipython-input-298-4cb504e04f59>", line 1
I am a string
^
SyntaxError: invalid syntax
We can have multline strings as well:
File "<ipython-input-13-5a80c8e0251e>", line 1
"I am a
^
SyntaxError: EOL while scanning string literal
You can do addition and multiplication with strings!
You can also turn other things into strings with str
:
Be careful, though, because if you are doing addition and want it to be numerical addition, but you have strings, you won't get what you want:
Lists
Lists are ways that we can group variables together:
Adding and removing items
We can add items to the list with append
:
Or insert items elsewhere with insert
:
You can remove items with remove
:
Looking up items
You can check if an item is in a list using the in
keyword:
To retrieve an item, you can use square brackets, and then the index of the item:
There is a special syntax for getting the las element of the list, which is to use an index of -1
:
You can also slice a range of elements using slice syntax, which is:
[i]
-- get the element at indexi
[:j]
-- get all elements up to (and excluding) indexj
[i:j]
-- get all elements between indexi
and indexj
(includingi
, excludingj
)[i:j:k]
-- get everyk
th element between indexi
and indexj
(includingi
, excludingj
)[:j:k]
-- get everyk
th element up to (and excluding) indexj
[::k]
-- get everyk
th element in the entire list
We can create a list of numbers using a similar syntax:
range(i)
-- all integers from 0 toi
(excludingi
)range(i, j)
-- all integers betweeni
andj
(includingi
, excludingj
)range(i, j, k)
-- everyk
th integer betweeni
andj
(includingi
, excludingj
)
Modifying list items
Using this same notation, we can also set elements:
Unlike in MATLAB, if you try to set an element that doesn't exist, Python will complain at you:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-21-df80e8b1657e> in <module>
----> 1 list_of_fruits[4] = 'grape'
IndexError: list assignment index out of range
Gotcha: lists are passed by reference
If you have one list, and want to create a copy of that list, you can't just assign it to a new variable:
Instead, you have to copy the list by using .copy()
:
Tuples
Tuples act exactly the same as lists, except that they are denoted with parentheses (instead of square brackets) and you can't modify them:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-30-1972f4654a5f> in <module>
----> 1 tuple_of_fruits.append("pear")
AttributeError: 'tuple' object has no attribute 'append'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-a3e3c942490d> in <module>
----> 1 tuple_of_fruits[2] = 'pineapple'
TypeError: 'tuple' object does not support item assignment
Tuple unpacking!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-36-cb888c77e4ea> in <module>
----> 1 (b0, b1) = berries
ValueError: too many values to unpack (expected 2)
Dictionaries
Dictionaries allow you to store values associated with some key. For example:
Then, to access the values, you use square brackets (kind of like with lists):
You can add something to a dictionary just by assigning to it:
Modifying dictionaries works similarly to lists:
Control flow
For loops
For loops have the following syntax:
where iterable
is a list, tuple, dictionary, etc. that can be iterated over. On each iteration of the loop, variable
will hold a different element of the iterable. On the first iteration, it will hold the first element of iterable
, on the second iteration, it will hold the second element, and so on.
Printing out the numbers from 1 to 10:
Squaring the numbers from 1 to 10:
What if we want to construct a list of squares?
We can also do this with list comprehensions, which are a shorthand for writing for loops:
While loops
While loops aren't used as frequently in Python as they are in other languages, but they do exist. They have the form:
where condition
is an expression or variable that evaluates to a boolean (True
or False
).
If statements
We don't want to always operate on every element of a list. Sometimes, we'd like to do different things, depending on the value of the item.
For example, this squares all even numbers and cubes all odd numbers:
Functions
Almost all the code you write for this class will be in functions -- this makes it easier for you to check your own work, and for us to grade it! Functions have the following form:
where function_name
is the name you want to call your function, and the variables inside the parentheses are the arguments to the function (you can have any number of arguments, including zero). The something
that is returned should be defined within the function.
For example, here's a function that takes a list of numbers and squares it:
Recursive functions
Functions can call themselves! This is a concept called recursion. For example, we can use recursion to compute the Fibonacci sequence:
We can use functions in loops, too! For example, to get the first 10 Fibonacci numbers: