Learning objectives
Now that we have written our first program, we are ready to start seeing how Python implements variables, functions, if statements, loops, and other topics that we introduced on the level of pseudocode in the prologue. Once we have learned these fundamentals, we will be ready to implement Euclid’s GCD algorithm and Eratosthenes’ prime finding algorithm and then time these two algorithms to see if they’re really as fast as we claimed.t
In our first lesson on fundamentals, we will introduce types and numeric variables in Python.
Code along summary
Setup
Create a folder called variables
within your python/src
directory and create a text file called main.py
in the python/src/variables
folder. We will edit main.py
in this lesson.
We are going to write code that we will execute. Therefore, as in the previous code along, we need to do two things:
- Include the code we will run inside a
function inmain()
main.py
. For now, let’s include a simple indentedprint()
statement. - Add a line
if __name__ == "__main__
“:, followed by themain()
command on its own indented line. These two lines tell the Python interpreter that we want the
function to be run when we execute this script. (For brevity’s sake, we will exclude these lines from subsequent code snippets in what follows.)main()
def main(): print("Variables in Python.") if __name__ == "__main__": main()
Note: At the top right of each code block, you will see icons allowing you to copy the code in the code block as well as download a text file containing the code block. Please use these how you like, although we strongly suggest typing them yourself!
Comments are not executed by Python
First, we introduce comments. Comments are “notes” to ourselves or someone else reviewing our code. Beginner programmers often don’t appreciate how valuable comments can be for their own learning; we suggest that you comment your code frequently!
In Python, anything occurring on a line after the #
symbol is not read as code. A text editor will often automatically color a comment gray. Let’s type our first comment, which should be written in a complete sentence starting with a capital letter.
def main(): print("Variables in Python.") # Python won't read this line!
STOP: Let’s run this code. Open a command line terminal and navigate into the folder containing your code by using the command. Then, run the code by executing the command
cd python/src/variables
(macOS/Linux) or
python3 main.py
python main.py
(Windows). You should seeVariables in Python.
printed to the console.
We also can add an in-line comment to the end of a line, without affecting everything to the left of the comment. Python does have a stylistic convention to ensure that we add at least two spaces to the right of any code before an in-line comment.
def main(): print("Variables in Python.") # everything here won't be executed. # Python won't read this line!
Variables and four built-in Python variable types
A variable is a location in the computer’s memory that stores a value. The type of the variable indicates what type of data it will store, such as a number, a word, or a moon of Jupiter. In this code along, we will introduce four of Python’s built-in variable types.
: an integer, which can be positive, negative, or zero;int
bool
: a “Boolean” variable that can have one of the two valuesTrue
orFalse
.
: a decimal number.float
str
: a contiguous “string” of symbols (i.e., a word or text). In the next chapter, when we work with the sequences of DNA making up the genetic blueprint of all life on Earth, we will work heavily with strings.
Declaring variables
In what follows, we will edit def main()
in main.py
. First, we will declare four variables, one for each of the types introduced above. By declaring a variable, we assign a name to the variable, and Python allocates memory to store its value behind the scenes. In Python, we declare a variable by using the name of the variable, followed by an equals sign, then the value of the variable.
Here are our declarations of variables named j
, x
, yo_world
, and statement
; these variables have the respective values 14
, -2.3
, "Hi"
, and True
.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool
You will note that we have added some comments after the variable declarations above. These comments indicate that each variable that we declared has a type, which indicates the collection of values that the variable can hold. To summarize:
j
has typeint
, meaning that it can take integer values;x
has typefloat
, meaning that it can take decimal numeric values;yo_world
has typestr
, meaning that it can take values that are strings, or sequences of symbols;statement
has typebool
, meaning that it can take boolean values, which are always eitherTrue
orFalse
.
We will say more about variable types soon. For now, we will point out that it is good practice to know the type of a variable when you declare it.
Note: Python variables can have any name that isn’t a reserved keyword of the language, likedef
,while
, orif
. However, we also follow the commonly used PEP 8 style guide for Python in this course, which dictates that variables should start with a lowercase letter as well as that variables with multiword names follow snake_case, meaning that we use underscores to separate the words in the variable name. Note that we have followed snake_case convention in naming a variableyo_world
.
We then call print()
to print our variables to the console and confirm that they have the values that we assigned them.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool # Let's print our variables print(j) print(x) print(yo_world) print(statement)
STOP: Let’s run this code by using the terminal command(macOS/Linux) or
python3 main.py
python main.py
(Windows), which results in the value of each variable being printed on its own line by theprint()
command.
If we would instead like for the values of these variables to be printed on a single line, we can add the variable names in one print statement, separated by commas.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool # Let's print our variables print(j, x, yo_world, statement)
STOP: Once again, run this code by executing the terminal command(macOS/Linux) or
python3 main.py
python main.py
(Windows).
In Python, indentation matters (way too much)
Python demands that every line of code within a “block” be indented. In our case, the block of code that we are currently working with is the function def main()
.
Python will halt the program and invoke an IndentationError
if any line has more or less indentation than any other line. Let’s see this by running the following program, where we have added one additional space to the line where j
is declared.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool # Let's print our variables print(j, x, yo_world, statement)
The PEP8 suggested standard is to use four spaces as the standard indentation. We could use a different number of spaces in a single block of code, as long as we are consistent. We could even use tabs as our indentation method, as long as we always use only tabs as our indentation method within the same function. However, we will follow PEP8 standards and use four spaces.
Consider the following version of our code, which on most browsers will look as if each line has been indented at the same level. Yet we have placed a single tab at the start of some lines and four spaces at the start of others. When we run this code, Python flips out and produces an IndentationError
. Although Python will allow us to do some powerful work throughout this course, Python’s fragility with indentation is one of the most infuriating aspects of any programming language.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool # Let's print our variables print(j, x, yo_world, statement)
The choice between tabs and spaces is ultimately an important one, and as the following educational video shows, it can destroy relationships. Regardless of which side of the indentation war you find yourself on, consistency is key.
Accessing and changing the type of a variable
We can determine the type of a variable by passing this variable as input to Python’s built-in function type()
. Let’s do so.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool # Let's print our variables print(j, x, yo_world, statement) # Let's print the variables' types print(type(j), type(x), type(yo_world), type(statement))
We make this point because Python employs a feature called dynamic typing, which allows the type of variable to change during the life of a program. For example, let’s change yo_world
from a string into a decimal having the value 2.718. The following code will show that it changes from having type str
to having type float
.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float yo_world = "Hi" # type: str statement = True # type: bool # Let's print our variables print(j, x, yo_world, statement) # Let's print the variables' types print(type(j), type(x), type(yo_world), type(statement)) # Changing the value of yo_world to a decimal yo_world = 2.718 print("yo_world now has type:", type(yo_world))
Arithmetic on numeric variables
After we have declared numeric variables (of type int
or float
), we can perform arithmetic on them, following the standard arithmetic order of operations. For example, the following two new lines will print the values represented by the expressions 2 * (j+5)
and x/4 + 3.16
, which are equal to 38 and 2.585, respectively.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float # (some intermediate lines omitted for clarity) print(2 * (j+5)) print(x/4 + 3.16)
Note: A common programming error is writing an expression like2(j+5)
. Although this expression looks perfectly reasonable to a human reader, Python is unable to parse it, as it is missing the multiplication symbol; make sure that you remember your multiplication symbols!
Not all languages allow you to perform arithmetic on variables of different types, but Python does. For example, we can multiply x
and j
together, obtaining the result -32.2. When this operation occurs, the value of j
is briefly converted into a float
for the purpose of the operation, but the type of j
does not change, as the following code indicates.
def main(): print("Variables in Python.") # Python won't read this line # Let's declare some variables j = 14 # type: int x = -2.3 # type: float # (some intermediate lines omitted for clarity) print(2 * (j+5)) print(x/4 + 3.16) print(x*j) print(type(j))
Note: On some computers, you may see-32.199999999999996
printed instead of-32.2
. Python has not made a mistake in calculation, and to understand why sometimes we will see small round-off issues like this in any programming language, you will need to stay with us until the end of the course.
Two more operators: the power operator and integer division
As we conclude this section, we will point out three additional built-in Python arithmetic operators that we will find useful in our work with implementing ancient Greek algorithms and beyond. In the below notation, x
and y
could represent variables, numbers, or expressions involving both.
- Power operator: the expression
x ** y
represents takingx
to the power ofy
. - Integer division operator: when
x
andy
are integers,x//y
represents the integer division ofx
byy
, in which we ignore the remainder. - Modulo operator: when
x
andy
are integers,x%y
represents the remainder after dividingx
byy
.
We will conclude by printing the result of these three operations below. Note that if we would like to divide two integers and obtain a result that is a float
, we can use the single /
operator.
def main(): # (some lines omitted for clarity) print(14 / 3) # prints 4.666666666666667 print(14 // 3) # integer division, prints 4 print(14 % 3) # remainder operator, prints 2 print(14 ** 3) # power operator, prints 14^3 = 2744
Looking ahead
Now that we know more about working with variables, we are ready to integrate them into functions other than just def main()
. By splitting our code into functions, we will be able to perform more complicated tasks, starting with implementing our ancient Greek mathematical algorithms.