The two buildings blocks of programming are data and functions. Data can consists of numbers, texts, a bunch of numbers, or a bunch of texts, or even images or video (although we won’t discuss the latter two in this class much). Basically any kind of information that we can store on a computer - that’s data.
When working with data in Python, two things have to happen. First, the data must be stored somewhere on the computer. Second, we must be able to refer to that piece of data by a name. Without a name, we won’t be able to differentiate between different pieces of data like for example different companies’ stocks and that could be bad.
In Python we refer to “data that has a name and is stored in computer memory” as a variable. We can create a variable in Python via the =
sign. To the left of the equal sign we write the variable’s name, and to the right we specify the value that the name should refer to.
For example, we can write tesla_stock = 240.83
which creates a variable in Python called tesla_stock
. If we print this variable,print(tesla_stock)
, we see the value $240.83$ appear on our screen. Note - print is a function that comes with Python that shows us the value associated with a variable.
<aside>
Data, as we mentioned, can be numbers and but it can also be text. So we can create variables which refer to text. For example, we can create a variable called first_amendment
which refers to the following line of text.
first_amendment = "Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances."
Variables in Python can be changed (mutable). When we write tesla_stock=240.83
were not declaring that for the rest of our code that tesla_stock
will point to the value $240.83$. Python runs (or executes) the lines sequentially. So later on in our code, we can set telsa_stock
to a new value, and then when we print it, and python will print the new value on the screen.
tesla_stock = 240.83
tesla_stock = 251.17
print(tesla_stock) # == 251.17
<aside>
We wouldn’t get vary far in this class without functions. In some sense this class is all about functions, deciding which functions we want to create and how to create them in Python.
At their essence, Functions transform data. That is, we pass in some value to a function and it returns a value. More formally, functions map from the set of possible inputs (domain) into the set of possible outputs (codomain). Consider, for example, the following function which takes a number and squares it. We can denote this using mathematical notation as follows. The notation that some value $x$ gets transformed by $f$ into $x^2$. $x$ is a placeholder for an arbitary input. For instance, if we called this function on $2$, we would get back $4$.