Chapter 2 Programming Fundamentals
In this chapter, we will look at the basics of programming using the Python language. These basics include the ability to calculate mathematical expressions, just as you would on a calculator. While the content here is specific to Python, it’s important to remember that these concepts transfer to all other programming languages as well.
Before we begin, however, we should address an obvious question that non-computer scientists always ask. Why do you need to code in a special language? Why can’t you just tell the computer what to do in plain words? Instead of answering this question, let’s look at an example of what trying to instruct a computer would look like if we used English instead.
User: Okay computer, please sum the numbers from 1 to 10.
Computer: What do you mean by "all the numbers"?
User: Okay computer, please sum the integers from 1 to 10.
Computer: Is that inclusive or exclusive?
User: Okay computer, please sum the integers from 1 to 10, inclusive of
both 1 and 10.
Computer: All the integers?
User: Okay computer, please sum every single integer from 1 to 10,
inclusive of both 1 and 10.
Computer: Okay sure! Why didn't you say so in the first place?
In our made-up example, the final command we issued to the computer was: Sum every single integer from 1 to 10, inclusive of both 1 and 10. This was necessary because a) a computer is just a big dumb calculator, and b) programming is about implementing algorithms, which have precisely-defined instructions. In our example, we took pity on the user, but you could imagine the computer saying, *I know addition and subtraction, but what does “sum” mean?" The user would then need to provide a precise definition of “sum.” In any case, you can see how wordy it is to encode our instructions in English. By contrast, the code to achieve this in Python is:
sum(range(1, 11))
So when asked why we need programming languages, the answer is: because it is much, much easier!
2.1 Code Snippets
Throughout this book, we will be using snippets of code to illustrate the concepts we’re referring to. These snippets consist of a number of lines, and are executed in order:
First line is executed
Then second line is executed
Then third line is executed
...
These code snippets may contain comments. Comments are annotations that can be made to the code to explain exactly what’s going on, or to help with readability. They are ignored when the code is executed, and so do not affect the functionality of the program in any way. It is good practice to comment your code, but there is no need to comment every single line — use them only when they help in understanding the code. In Python, comments are indicated by the hash symbol as follows
# This is a comment! :)
2.2 Variables
The most fundamental aspect of programming is a variable, which is used to store (“remember”)
a particular value in the computer’s memory which can later be used to perform a calculation.
A variable is identified by its symbolic name and the value associated with it.
A variable is closely related to the mathematical notion of a variable, but differs in that the
value associated with it over time may change (hence the name “variable”).
For example, in programming we may start off with the variable x
having the value \(2\), but by the end
of it all, x
’s value has been changed to \(3\).
2.2.1 Names
Each variable in a program has a unique name. The rules determining what constitutes a valid name
vary from language to language, but in Python, names may only consist of any number of letters, digits and underscores. Furthermore, a name may not start with a digit.
In Python, variable names are case-sensitive, so the variable name total
is different from the variable name Total
.
It is good programming practice to pick variable names that are readable and easy to understand.
This will help others read your code and understand what is happening, but will also be helpful for you
if you return weeks later to look at your code. By convention (hence, it is only a suggestion, not a firm rule), variables should be all lowercase, and if your variable name is composed of multiple words, then each word should be separated by an underscore (e.g., total_amount
).
Each language also has certain keywords that have special meaning. These words are reserved, and so cannot be used as variable names. In Python, these keywords are:
False | class | from | or |
None | continue | global | pass |
True | def | if | raise |
and | del | import | return |
as | elif | in | try |
assert | else | is | while |
async | except | lambda | with |
await | finally | nonlocal | yield |
break | for | not |
Question! Which of the following names are valid Python variable names? For invalid names, why are they invalid?
x
number_of_people
total-amount
NAME
class
2pac
pac2
FroggyFresh
return
FalsE
Music side quest! Learn about the rapper Froggy Fresh.
2.2.2 Types
A variable is used to store a particular value. But what kinds of values can be stored?
Every variable has an associated type, indicating the kind of value it can hold; examples of types include integers and real-valued numbers.
Programming languages can be divided into two categories: statically-typed and
dynamically-typed languages. In statically-typed languages, once a variable has a given type, it
can never be changed. So if variable x
is used to store integers, it will only ever be allowed to store
integers.
By contrast, dynamically-typed languages have variables that can change their type whenever they like.
So a variable x
might initially be used to store integers, but then later on change to storing decimal
numbers, and then back to integers.
Python is a dynamically-typed language, and so a single Python variable can hold any kind of data!
To see this in action, let’s look at the following code:
= 0
x print(type(x)) # display the type of x
= 1.4
x print(type(x)) # display the type of x
If we were to execute this code using our Python interpreter (please go ahead and try it), we would see the output is
<class 'int'>
<class 'float'>
This output shows that our variable was initially an integer (the type is int
) but then became
a decimal later (in programming, decimals or real-valued numbers are referred to as floating-point numbers or floats
).
Python provides a set of pre-defined types. These are:
int
(integer)float
(real number)string
(text)bool
(True or False values)
The table below lists these types, as well as literals, which are fixed constants of the various types.
Name | Values Allowed | Example Literals |
---|---|---|
Integer | Any integer of any size! | 0, -1, 2145 |
Float | Real-valued numbers within some range and to some precision (roughly 15 decimal places) | 1.2, -0.6, .3, 1.4e10 |
Boolean | True or false values only | True, False |
String | Any sequence of characters | “T-Pain sucks” , ‘Jeff’ |
Note that in Python, we can use either single or double quotes to represent a string (but we may not mix them).
Numbers side quest! Let’s think about large numbers!
- What’s the largest number you can think of? (Infinity is not a number, it’s a concept.)
- What is the smallest strictly-positive real number that Python can represent?
- What is the largest positive real number that Python can represent?
- From your knowledge of basic arithmetic, you’ll know that we have operators such as addition, then multiplication (which is repeated addition), then exponentiation (which is repeated multiplication). But what comes next?!
- Use the internet to learn about Graham’s number.
2.2.3 Assignment
So far we have spoken about variables that have names, types and associated values. But
how do we actually associate a variable with a value?
In Python, we do this using the assignment operator =
.
Let’s say we have a variable called y
. In order to assign y
a value, we simply write:
= 2.45824406892 y
Other examples of assignment are as follows:
= 42
meaning_of_life = "Pogba's Haircuts" some_name
The assignment operator here is not to be confused with the “equals” operator you’re familiar with in mathematics. Rather, think of the assignment operator as saying: “the left hand side is now the name for the value on the right hand side.” Alternatively, we could think of it as “the variable on the left hand side is now storing the result of the expression on the right hand side.”
You may wonder why we are trying to be very precise about the =
here. To illustrate where confusion might arise, consider the following assignments:
= 42
x = 23
y = y # What happens here?
x = 17 y
The question here is: what is the value of x
?
Recall that programming languages are executed one line at a time, in order.
So to start, we execute the first line and the value of x
is \(42\).
Then the next line sets the value of y
to \(23\).
Now it gets a bit tricky. What happens on the third line?
Remember that the assignment operator is not mathematical equals. The third line does not say that x
and y
are “tied together” and will always have the same value. Rather, it simply says that the
value of x
is the value on the right hand side. The value on the right hand side is 23
, and so
the third line is equivalent to saying x=23
. Finally, the last line sets y
to \(17\).
It is vital to note that this only sets the value of y
; x
remains unchanged.
Therefore, when all is said and done, x
has a value of \(23\) and y
has a value of \(17\).
Before moving on, make sure you understand the above and how assignment operates.
Question! Consider the sequence of assignment operations below. What are the final values of each variable mentioned? And what are their types?
= 7
a = 9
b = "?"
c = 1.2
x = a
d = 1.2
a = "Hello world"
s1 = a + b
d = "1.2"
s2 = 91 s1
As a final note, recall that Python statements are executed one at a time, starting from the top down. It is therefore important that we declare a variable (i.e. create it) before we actually use it. For example, the following code is invalid:
= y + 2 # What is y?!
x = 20 # Too late! y
Notice that on the first line, x
is supposed to take the value of the computation y + 2
. But the interpreter doesn’t know what y
even is (it’s only declared on the following line, but we haven’t got there yet)! The following error will result:
NameError: name 'y' is not defined
2.2.4 Casting
We have said that each variable holds a value with an associated type. If we wish to, we can convert data types from one to another using casting. This allows us to convert the value of a variable to a different type, but it doesn’t affect the original variable’s type. To cast a variable, we use the type we wish to convert it to, and then wrap the variable in round brackets. Some examples of casting are below:
= 1 # x is an integer with value 1
x = float(x) # x is cast to a decimal. y has a value of 1.0
y = "2" # note that a is a string i.e. it is the character 2, not the number!
a = int(a) # now z is the integer 2
z = 2.6
q = int(q) # q is cast to an integer. r now has a value of 2 (the decimal part is dropped) r
2.3 Operators
Operators in Python allow us to perform the standard arithmetic operations on variables and literals (constants). These operators are:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Exponentiation (
**
) - Modulus (
%
)
The only operator you may be unfamiliar with here is the modulus operator. This operator computes the
remainder when one number is divided by another. So because \(9 / 2 = 4 \text{ remainder } 1\), we would see that 9 % 2
(you would say this as “9 modulo 2”) gives us \(1\).
Question! The modulus operator is a strange one! If this is your first time programming, you probably haven’t thought about remainders in many years! Can you think of some reasons why remainders would be useful?
Mathematics side quest! The statement that the modulus operator computes the remainder was not quite correct. In fact, the modulus operator computes the remainder only when both numbers have the same sign! What happens when the numbers have different signs? What happens when one or both are zero?
A word of warning when it comes to division: certain programming languages treat division differently, depending on the variable types. For example in Python 3 (the language we are using) 9 / 2
produces \(4.5\). However, in Python 2 and C++, 9 / 2
produces \(4\). This is known as integer division: when the two numbers are both integers, the result of the division is also an integer! If this behaviour is
desirable, then in Python 3 we can achieve this as follows: 9 // 2
which will produce \(4\).
Question! Predict the result of evaluating each of the following lines:
= 7
a = 9
b 20 + 3
- b
a 5 * b
/ a
b // a
b 14 % 2
2**3
2.3.1 Mathematical Functions
Python also provides a set of pre-defined mathematical functions. These include the absolute operator and a rounding operator:
abs(-10) # produces 10
round(2.543434) # produces 3 (rounds to the nearest whole)
round(2.543434, 1) # 2.5 (round to 1 decimal place)
max(10, 20) # returns the max, 20
max(10, 20) # returns the max, 20
min(10, 20, 1) # returns the min, 1
For more functions, see here.
2.4 Rules of Precedence
As with regular arithmetic, programming operators also follow rules of precedence (e.g. BODMAS/PEDMAS). When there is more than one operator on a line, the calculation is done according to the standard ordering: first, brackets are evaluated. Then exponentiation, followed by unary negation (unary negation refers to a negative number like \(-3\)), then multiplication, division and modulus, and finally addition and subtraction. This is summarised in the table below. Note that if two operators have the same precedence level, then which one is evaluated first depends on the “direction of evaluation” (which is normally left-to-right).
Precedence Level | Operator/Symbol | Operation | Evaluation Direction |
---|---|---|---|
0 (first) | () | parentheses | Inner ones evaluated first. Left-to-right |
1 | ** | exponentiation | Groups right-to-left |
2 | (unary) - | negation (unary minus) | Right-to-left |
3 | *, /, % | product, division,modulus | Left-to-right |
4 | +, - | addition, subtraction | Left-to-right |
Question! According to these rules of precedence, what is the value of the following statement? Do it by hand and then use the Python interpreter to double check your answer.
6 // 4+ -9 % 3 * 2 / -100 * -3 - -(17*5)
2.5 Input and Output
So far, our small programs we’ve used haven’t been very useful — we saw how to perform mathematical operations and assign values to variables, but that’s about it. What we really want is for our programs to be flexible and useful to the person using them. For example, if I want to look up a student’s marks given their student number, I want a program that can do that for any student, not just one in particular. To achieve this, we need our programs to be able to accept input from the user, and display the results (output). We will now see how input and output are managed in Python.
2.5.1 Input
In Python, we can accept input from the user using the input()
function.
When we do this, the user will be able to enter some input through the keyboard, hit Enter, and our program will receive whatever they have typed. We can then assign their input to a variable, as in the example below:
= input() user_input
In Python, the input()
function always return a string (see Section 2.2.2 if you’ve forgotten what a string is). But what if we don’t want a string? What if we want an integer, for example? In that case, we must cast (Section 2.2.4) the input to the type we want. Some examples of this are below:
= int(input())
points_total = float(input()) average_score
2.5.2 Output
It is no good writing a program and doing all this computation if the user cannot even see the final results!
In order to display results to the user, in Python we use the print()
function.
Despite its name, the function does not print something out on paper — rather, it displays the result as text on the screen, and will appear on your terminal when you run the program. We can print variables or constant values of any type using this function, as in the example below.
print("Hello, world!") # prints a piece of text
= 23
x print(x) # prints an integer variable
print() # displays a blank, empty line
History side quest! The function that displays text on the screen is called print
, not just in Python, but also in many, many languages. This is a bit strange, isn’t it? Surely a better name would be display
or show
? Try do some research to find out why the name print
has been used instead.
The default print()
function will display whatever is in brackets, and then add a new line. If we wish to display multiple things on the same line, we can do this by separating them with a comma. For example:
print("The best number is", 42)
2.6 Auto-marked Code*
When submitting code in computer science modules, they will be automatically marked. This is done by running your submitted code and providing it certain input. The marker then evaluates the output, and if it matches what was expected, marks it correctly. However, if the output does not match exactly, it will be marked incorrectly. Please watch the short video below to clarify some common issues where, even if everything is correct, you might still be marked wrong.