Python
Lists
Lists are an ordered collection of "things". In programming parlance, we call these "things" elements. In the example below, my_list is just a list of numbers, arranged in order. Each number is a seperate element of the list.
You may want to create a list yourself. For small lists, it is easy to just write them down yourself. For longer lists, it can be very tedious to do so. In this case, you should use the srange
function. Its syntax is like this:
start is the number to start counting at.
stop is the number to stop counting at. The list will increment up until one before this number.
step_size is the increment to increase by.
Zip
Frequently, you'll need to join two or more lists together. (This happens a lot when making lists of coordinates for list_plot) You can use the zip
function to do this.
See how the people and ages got matched up together? That's how to use zip. Very commonly, you'll use this to help plot lists of data to make a timeseries or a trajectory. For example, we'll plot the function for the values
if/else/elif
This is a way of making decisions. The if
keyword evaluates a boolean statement and returns either True
or False
. If the statement returns True
the body of the if statement is evaluated. Otherwise (else
) the program moves on to the next block.
Boolean operators
<
less than>
greater than<=
less than or equal to>=
greater than or equal to==
equivalent!=
not equivalentand
logical ANDor
logical ORnot
changesFalse
toTrue
and vice versa
For/While Loops
for
relationship with srange/range
use of zip to iterate through multiple arguments
while
break
A common idiom in programming languages instructs the computer to do something repeatedly, for a specific number of times. In plain english, an instruction to do this might look like the following:
In Python, we do this with a for
loop. Here is its syntax:
As always, examples are often the most instructive.
Here's how this for loop works:
The for loop begins on line 1. It will iterate through (go through) a list that contains the elements 1,2 and 3.
i
is set to 1, the first element of the list.The body of the for loop is executed. The value of
i
(1) is printed. (note that it is indented)i
is set to 2, the second element of the list.The body of the for loop is executed. The value of
i
(2) is printed.i
is set to 3, the third element of the list.The body of the for loop is executed. The value of
i
(3) is printed.We're at the end of the list, so the for loop ends and we continue execution at line 3.
"loop finished"
is printed.
Notice that line 2 is indented to denote the code that will be repeated during the for loop and line 3 is not indented, indicating that it is not part of the for loop.
It is really common to want to iterate through a list of numbers, but it would take a really long time to create a list that long. Let's use the function srange
, which can create that list for us. srange(3)
returns the list
[0,1,2]
(three elements)
There's times when you will want to iterate through multiple variables at the same time. You can do this by iterating
through a list of tuples
. You can use the zip
function to help you do this. This example shows how to use the rainbow
function to color each plot with a different color.
Working on data by looping through it and appending it to another list is a very common task, common enough for its own recipe.
Nested for loops
It's common to need to iterate through a particular list while also going through a separate list in order to get all of the combinations of the elements of those two (or more lists). Here's an example of that that will print out the multiplication tables for all of the numbers from 1-5:
Notice how i
is incremented in the outer loop while j
is incremented in the inner loop. Try keeping track of the variables and tracing through the code to see how this works.
While
Loops
while
loops are closely related to for loops. They allow you to do something repeatedly while a condition is met. The syntax is relatively simple:
In the example below, we use a while loop to print out the numbers 0-2 by incrementing a variable each time we go through the loop.
Functions
Functions are typically used when you have some code that you either
want to use repeatedly in multiple places
want to use similar code with very slight modifications
Functions can help make your code more readable and split it up into sections that are convenient to use, test and reason about. In python, functions are defined with the def
keyword and are followed by the name of the function and then its arguments. Here is an example of a function named say
that takes one argument, something_to_say
, and prints out whatever is given to it. Note that just like if/else statements and for/while loops, functions use indented blocks to delineate what code is part of the function.
How to write a function
When considering how to write a function, it often helps to follow a series of steps.
Think about what your function's purpose is. Decide on a name for the function that describes its purpose.
Think about what inputs (if any) your function requires and what outputs (if any) it should return.
Consider how you expect to use your function. Write that expected use case down.
In plain english, write down a step-by-step recipe for what your function should do. Programmers often call this pseudocode. Try tracing through it by hand and confirm that it *probably* does what you expect it to do. This will help you catch logic errors.
Fill out the pseduocode that you wrote down before with actual code, testing the intermediate results along the way if possible.
Use the expected use case that you wrote before to test your function. Does it produce the expected result?
For example, I want to write a function called multiply
that will multiply the two numbers a
and b
.
Its inputs should be two numbers a
and b
and it should return their product, a*b.
I expect to use my function like this:
Its inputs and outputs will probably look something like this:
Use the test case that you wrote earlier to examine the output of your function for errors.
From Script to Function (from Jane Shevtsov)
Despite all the abbreviation, iterating a function using the code you developed often means copying and modifying a hefty chunk of code. The kind of program you have, which consists of a series of commands for performing a particular task, is called a script. It’s often useful to turn a script into a function that can work for different inputs.
Here are some steps meant to be used as a guide for turning your own scripts into functions.
Make sure you know exactly what you want the function to accomplish. Write this as a comment at the top of your code.
Identify the output the function will need to return. Write this as a comment.
Identify the inputs that the function will need. These will be the arguments that the function takes. Write them as another comment.
Come up with a name for the function that briefly describes what it does. Write the function header. This is the
def my_function_name(input1, input2, ...):
line that goes at the beginning of the function.Copy and paste your script below the function header, as the body of the function, and indent it as necessary.
Copy your comment describing the function output and paste it near the end of the function, where you expect to put the return statement.
Put in the return statement to output whatever the function needs to output.
Delete any statements in the body of the function that explicitly supply data that will now be given as an input (argument) to the function. Change any references to this data so that they now refer to the correct function input (argument).
Go through your code and find any places where you used particular features of an example, such as the length of a list or the number of times a process should be repeated. Change them so they either (1) use the appropriate function inputs (arguments), or (2) calculate the necessary value as the function runs.
Test your function on the original example. When that works correctly, test your function on other examples by calling it with different inputs. Remember, the whole point of a function is that it should give the correct output for any inputs you give it, without you having to change the actual function code each time. All you should have to do is change the inputs when you “call” the function.
Remember, mistakes are expected, and programmers at all levels make them. The skills you learn in finding and fixing your mistakes should serve you well in other fields.
Immutable and Mutable objects in python
Integers, floats, strings, booleans and tuples are immutable objects. list
, dict
and matrices (among other things) are mutable objects. In python, unlike many other programming languages (like C), assigning a variable to an object (ie var = 5) simply assigns the name var
to represent that object instead of copying it. For immutable objects, there is usually no confusion.
However, mutable objects like lists and matrices often just change the referenced object instead of copying. This can lead to some really unexpected behavior. Thus, assigning a list/matrix to a variable name just makes that name a reference to that list/matrix instead of actually copying the object.
To get around this, you should use the copy()
function to make a copy of the object that will not reference the original.
Matrices are also mutable objects.