2. Python Fundamentals
There are some exercises here. Each exercise will ask you to write a program. The solution is often on the following page - do not turn the page until you have attempted your own solution! Save each program in a separate file.
2.1. The REPL
REPL stands for Read Evaluate Print Loop. In Mu you access it via the
REPL
button. It appears at the bottom of the window. It’s a special
mode in which you type an instruction to Python and Python executes it
immediately (no need to click RUN
) and displays the result (no need
to type print()
). It’s useful for doing calculations and trying
things out, but it won’t save what you type, so you will only want to
use it for very short programs.
2.2. Arithmetic operators
Python understands several operators from maths. You can use them in your programs, or just enter these examples at the REPL to use Python as a calculator, as in the screenshot above.
Operator |
Symbol |
Example |
Result |
---|---|---|---|
Addition |
+ |
20 + 10 |
30 |
Subtraction |
- |
20 - 10 |
10 |
Multiplication |
* |
20 * 10 |
200 |
Division |
/ |
20 / 10 |
2 |
There are some more advanced operators in Program 2.18.
2.3. Variables
A variable is a place in the computer’s memory where data is stored. You can name a variable whatever you like; you should try to make the name descriptive. There are many types of variable but Python sets the type for us automatically when we store data in the variable. (Unlike in many other languages, we do not need to specify the type.) The types we will see most often are whole numbers (integers) and strings of text.
We create a variable and assign a value to it using the =
operator.
Note this is different from the ==
operator which is used for
comparisons.
We use the print()
function to print the value of our variables. It
will print any type of data (numbers, strings, both literals and
variables) provided each item is separated with a comma (,
).
my_number = 7
my_string = "hello"
print(my_string, my_number)
We can use a variable anywhere we would use a literal number or string. The value of the variable will be retrieved from the computer’s memory and substituted for the variable in any expression.
apples = 27
pears = 33
fruits = apples + pears
print("Number of fruits:", fruits)
Exercise
Copy Program 2.2, but also add 17 bananas to the calculation of fruits.
We can store a new value in the same variable. The old value will be forgotten.
apples = 27
apples = 40
print("Number of apples:", apples)
Question
What do you think Program 2.3 will print? If you aren’t sure, type it in.
More usefully, we can take the old value, modify it, then store it back in the same variable.
x = 5
x = x * 10
x = x + 7
print(x)
Exercise
What do you think Program 2.4 will print? Run it and see if your prediction is correct.
Exercise
Change the numbers in the program. Use a division / operation on the variable. Then ask your friend to predict what the new program will print. Was he right?
You will often see this used for counting:
total = 0
total = total + 1
total = total + 1
total = total + 1
print(total)
Question
What is the total count of Program 2.5 ?
See Program 2.18 for a quicker way of writing this.
2.4. Input
Program 2.2 is not very useful if the number
of apples changes. This would require the programmer to change the
program. We can improve it by allowing the user of the program to
change the numbers. The input()
function allows the user to type a
string which can be different every time the program is run.
my_string = input()
print(my_string)
Sometimes we want the user to type in a number rather than a string. We
can combine the int()
function with the input()
function to
convert the string to a number.
print("Enter a number")
my_number = int(input())
print("Double your number is", my_number * 2)
Exercise
Copy Program 2.2 but use input() to ask the user to enter the number of apples and pears.
2.5. Booleans
A boolean is another type of variable that is not a string or a
number. It can have only two possible values: True
or False
. In
some languages and in electronics you may see these represented as 0
and 1
.
Booleans are used by keywords such as if
and while
. In an if
statement, the indented code block is only run if the boolean is
True
.
sunny = True
if sunny:
print("Let's go to the park")
You could write it like this:
sunny = True
if sunny == True:
print("Let's go to the park")
but that would be redundant because if
always tests if the boolean
is True
.
If the boolean is not true, and if you write an else
clause, the
indented code block under else
is run instead.
sunny = False
if sunny:
print("Let's go to the park")
else:
print("We must stay at home")
2.6. Comparison operators
A comparison operator takes two things (e.g. numbers, strings, variables),
compares them, and then returns a boolean True
or False
.
Operator |
Symbol |
---|---|
Equal |
== |
Not equal |
!= |
Less than |
< |
Less than or equal |
<= |
Greater than |
> |
Greater than or equal |
>= |
1if 7 < 9:
2 print("7 is less than 9")
3
4a = 10
5b = 5
6
7if a == b:
8 print("a is equal to b")
9
10if a < b:
11 print("a is less than b")
12
13if a > b:
14 print("a is greater than b")
2.7. Boolean logic
The and
, or
and not
operators operate on booleans and return
new boolean values.
1a = True
2b = False
3
4if a:
5 print("a is true")
6
7if a and b:
8 print("a and b are both true")
9
10if a or b:
11 print("either a or b is true")
Change the values of a and b in Program 2.8 and see what output is printed by different combinations of True and False.
2.7.1. Or
Only people older than 12 or taller than 150cm are allowed to ride the rollercoaster. This program checks whether people are allowed to ride.
print("How old are you?")
age = int(input())
print("How tall are you?")
height = int(input())
if age > 12:
print("You can ride")
elif height > 150:
print("You can ride")
else:
print("YOU MAY NOT RIDE, GO AWAY!")
Boolean operators combine two truth values together. The or
operator
is True
if either of its operands is true. Try this example:
a = True
b = False
print(a or b)
Exercise
Use the or operator to make the rollercoaster program shorter by combining the two tests into one test.
A possible solution:
print("How old are you?")
age = int(input())
print("How tall are you?")
height = int(input())
if age > 12 or height > 150:
print("You can ride")
else:
print("YOU MAY NOT RIDE, GO AWAY!")
2.7.2. And
The and
operator is True
if both of its operands is true. Try
this example:
a = True
b = False
print(a and b)
Exercise
The rollercoaster is only allowed to run on days when the temperature is less than 30 degrees. Extend the program to ask the temperature and use the and operator to only allow riding when less than 30 degrees.
A possible solution:
print("How old are you?")
age = int(input())
print("How tall are you?")
height = int(input())
print("What is the temperature?")
temp = int(input())
if (age > 12 or height > 150) and temp < 30:
print("You can ride")
else:
print("YOU MAY NOT RIDE, GO AWAY!")
Note that we have put brackets around the or
expression. This
ensures it is calculated first and the result of that calculation is
then used in the and
expression. This is the same way you use the
BODMAS rule to decide the order of operations in maths.
2.7.3. Not
The not
operator is True
if its operand is False
. If its
operand is False
then it is True
. Try this example:
a = True
b = False
print(not a)
print(not b)
We can get a user input and convert it to a boolean like this:
print("Is it raining? Y/N")
if input() == "Y":
raining = True
else:
raining = False
Exercise
Change the program so that you can only ride the rollercoaster if it is not raining.
Possible solution:
print("Is it raining? Y/N")
if input() == "Y":
raining = True
else:
raining = False
print("How old are you?")
age = int(input())
print("How tall are you?")
height = int(input())
print("What is the temperature?")
temp = int(input())
if (age > 12 or height > 150) and temp < 30 and not raining:
print("You can ride")
else:
print("YOU MAY NOT RIDE, GO AWAY!")
2.8. For loops
A for
loop repeats a block of code a number of times. A variable is
created which we can use to find the current number within the loop.
Here the variable is called x
but you can name it whatever you like.
Run this program:
for x in range(0, 11):
print(x)
You can also change the step of the loop. Run this program:
for x in range(0, 11, 2):
print(x)
2.8.1. Nested loops
It is often useful to put one loop inside another loop.
1for a in range(0, 6):
2 for b in range(0, 6):
3 print(a, "times", b, "is", a * b)
Exercise
Write a program which prints out the 12 times table.
2.8.2. Incrementing a variable in a loop
A baker has three customers. He asks them each how many cakes they want so he knows how many he must bake. He writes this program.
total = 0
print("Customer", 1, "how many cakes do you want?")
cakes = int(input())
total = total + cakes
print("Customer", 2, "how many cakes do you want?")
cakes = int(input())
total = total + cakes
print("Customer", 3, "how many cakes do you want?")
cakes = int(input())
total = total + cakes
print("I will bake", total, "cakes!")
Exercise
This program is longer than it needs to be. Write your own program that does the same thing using a for loop. It should be only 6 (or fewer) lines long.
1 total=0
2 for x in range(1, 4):
3 print("Customer", x, "how many cakes do you want?")
4 cakes = int(input())
5 total = total + cakes
6 print("I will bake", total, "cakes!")
Exercise
The baker gets a fourth customer. Change Program 2.10 so it works for 4 customers.
Exercise
The baker has a different number of customers every day. Change the program so it asks how many customers there are. Store the number typed by the user in a variable called c. Change the loop so it works for c customers rather than 4 customers.
1 print("How many customers are there today?")
2 c = int(input())
3 total=0
4 for x in range(1, c+1):
5 print("Customer", x, "how many cakes do you want?")
6 cakes = int(input())
7 total = total + cakes
8 print("I will bake", total, "cakes!")
Exercise
If a customer orders 12 cakes, he gets an extra cake for free. Use an if statement to check cakes > 12. If so, add one more cake.
2.9. Array lists
Variables can be stored together in a list. Most languages call this an array so try to remember that word also. 1
1# a is a list of integers
2
3a = [74, 53, 21]
4
5# b is a list of strings
6
7b = ["hello", "goodbye"]
8
9# You can take a single element from the list.
10print(a[2])
11
12# You can use a for loop to print every element.
13for x in a:
14 print(x)
2.9.1. Looping over lists
Rather than the user typing in data, your program might be supplied with data in a list. Here is a list of prices - a shopping list. Note we don’t use a currency symbol except when we print the price.
prices = [3.49, 9.99, 2.50, 20.00]
for x in range(0, 4):
print("item costs £", prices[x])
In this program x
is used an index for the array. Note that
indices begin at 0
rather than 1
. If the array contains 4
elements then the final element will have index 3
, nor 4
.
However, for
can directly give you all the array values without the
need for an index or to specify the size of the range:
1prices = [3.49, 9.99, 2.50, 20.00]
2for price in prices:
3 print("item costs £", price)
Exercise
Change the Program 2.13 so that it prints the total price of all the items added together.
1prices = [3.49, 9.99, 2.50, 20.00]
2total = 0
3for price in prices:
4 print("item costs £", price)
5 total = total + price
6print("shopping total", total)
There is a problem with solution, can you see what it is when you run it?
The problem is that we are using floating point numbers for the prices
and floating point maths in the computer is not entirely accurate, so
the answer will be very slightly wrong. One way to fix this is to round
the result to two decimal places using the round()
function:
print("shopping total", round(total,2))
This works for a short list, but if the list was millions of items long it might not give the right result. Can you think of a better way?
Instead of storing the number of pounds, store the the number of pennies. Britain no longer has a half-penny, so the numbers will always be whole numbers - integers - and no floating points will be needed for the addition.
1prices = [349, 999, 250, 2000]
2total = 0
3for price in prices:
4 print("item costs £", price/100)
5 total = total + price
6print("shopping total", total/100)
Exercise
Conditional discount. Any item that costs more than £10 will be discounted by 20 percent. Use an if statement to check if the price is more than 1000 pennies. If it is, multiply the price by 0.8 to reduce it before you add it to the total.
1prices = [349, 999, 250, 2000]
2total = 0
3for price in prices:
4 print("item costs £", price/100)
5 if price > 1000:
6 price = price * 0.8
7 print(" item discounted to", price/100)
8 total = total + price
9print("shopping total", total/100)
2.10. Functions
You will meet specially named functions that are called by RLZero such as
draw()
and update()
. However, you can define a function named
whatever you like and call it yourself.
Functions are useful for many reasons. The simplest is that they make your program look more organized. They also enable you to re-use code without needing to copy it and risk making mistakes. When your programs get longer they enable you to create abstractions so you only have to think about what function you want to call and don’t need to remember the details of the code inside the function.
1
2
3def my_func():
4 print("This is my function")
5 print("Imagine there was lots of code here"
6 " that you didnt want to type 3 times")
7
8
9my_func()
10my_func()
11my_func()
2.11. Shortcuts
Here are quicker ways of doing basic things. You may have noticed some of these being used already.
1# f is an easy way to insert variables into strings
2score = 56
3name = "Richard"
4message = f"{name} scored {score} points"
5print(message)
6
7# += is an easy way to increase the value of a variable
8score = score + 10 # hard way
9score += 10 # easy way
10print(score)
11
12# double / means whole number division, no decimals
13x = 76 // 10
14# MODULO is the percent sign %. It means do division and take the remainder.
15remainder = 76 % 10
16print(f"76 divided by 10 is {x} and the remainder is {remainder}")
17
18WIDTH = 500
19a = 502
20b = 502
21# Modulo is often used as a shortcut to reset a number back
22# to zero if it gets too big. So instead of:
23if a > WIDTH:
24 a = a - WIDTH
25# You could simply do:
26b = b % WIDTH
27print(a, b)
28
29# input() takes a string argument which it prints out.
30# Instead of:
31print("Enter a number")
32num = input()
33# You can have a single line:
34num = input("Enter a number")
2.12. Indentation
Code is arranged in blocks. For example, a function consists of a
one line declaration followed by a block of several lines of code.
Similarly, all the lines of a loop form one block. A conditional has a
block of code following the if
statement (and optionally blocks
after the elif
and else
. )
Many languages use {}
or ()
to delimit a block. However Python
is unusual: each block begins with a colon :
and then all the lines of the
block are indented by the same amount of whitespace (tabs or spaces).
The block ends when the indentation ends.
Blocks can be nested inside other blocks.
1def test():
2 print("entering function block")
3 for i in range(0,10):
4 print("entering for loop block")
5 if i == 5:
6 print("in if block")
7 print("leaving for loop block")
8 print("leaving function block")
9print("not in any block")
10test()
2.13. Global variables
A variable defined inside a function has local scope: it cannot be used outside of the function. If you want to use the same variable in different functions then you must define it outside the functions, in the global scope. However, if you attempt to modify the value of the global variable inside a function you will get an error, or - even worse - you will create a local variable with the same name as the global variable and your changes to the global variable will be silently lost.
You must explicitly tell Python that you want to use a global variable
with the global
keyword.
1a = 10
2def my_function():
3 global a
4 a=20
5my_function()
6print(a)
2.14. Dictionaries
A dictionary (called a HashMap in some languages) stores pairs of values. You can use the first value to look-up the second, just like how you look-up a word in a dictionary to find its meaning. Here is a dictionary of the ages of my friends:
friends = {'richard': 96, 'john': 12, 'paul': 8}
print("What is your name?")
name = input()
age = friends[name]
print("Your age is", age)
Exercise
Change the program so it contains 5 of your friends’ ages.
2.14.1. Counting
Here is a loop that prints out all the ages:
friends = {'richard': 96, 'john': 12, 'paul': 8}
for name, age in friends.items():
print(name, "is age", age)
Exercise
Can you add an if statement to only print the ages of friends older than 10?
Possible solution:
friends = {'richard': 96, 'john': 12, 'paul': 8}
for name, age in friends.items():
if age > 10:
print(name, "is age", age)
Exercise
Now add a count variable that counts how many of the friends are older than 10. Print the number at the end.
Possible solution:
friends = {'richard': 96, 'john': 12, 'paul': 8}
count = 0
for name, age in friends.items():
if age > 10:
count = count + 1
print("friends older than 10:",count)
2.14.2. Combining tests
Exercise
Use the and operator together with the < and > operators to only count friends between the ages of 11 to 13.
Possible solution:
friends = {'richard': 96, 'john': 12, 'paul': 8}
count = 0
for name, age in friends.items():
if age > 10 and age < 14:
count = count + 1
print("friends age 11 to 13 :",count)
2.14.3. Finding
We make a variable oldest
that will contain the oldest age in the
list.
friends = {'richard': 96, 'john': 12, 'paul': 8}
oldest = 0
for name, age in friends.items():
if age > oldest:
oldest = age
print("oldest age", oldest)
Exercise
Make a variable youngest that will contain the youngest age in the list. Print the youngest at the end.
Possible solution:
friends = {'richard': 96, 'john': 12, 'paul': 8}
oldest = 0
youngest = 100
for name, age in friends.items():
if age > oldest:
oldest = age
if age < youngest:
youngest = age
print("oldest age", oldest)
print("youngest age", youngest)
2.14.4. Finding names
Exercise
As well as the ages, print the names of the youngest and oldest friends.
Possible solution:
friends = {'richard': 96, 'john': 12, 'paul': 8}
oldest = 0
youngest = 100
for name, age in friends.items():
if age > oldest:
oldest = age
oldname = name
if age < youngest:
youngest = age
youngname = name
print("oldest friend", oldname)
print("youngest friend", youngname)
2.14.5. Find the average
Exercise
Create a total variable. Add each age to the total. At the end, calculate the average by dividing the total by the number of friends.
Possible solution:
friends = {'richard': 96, 'john': 12, 'paul': 8}
total = 0
for name, age in friends.items():
total = total + age
average = total / 3
print("average age is ", average)
2.15. Bugs
Fixing bugs can feel frustrating but all programmers must wrestle with them. The simplest (but still annoying!) are syntax errors. The computer is not very intelligent and is unable to guess what you mean, so you must type the programs in this book exactly as they appear. A single wrong letter or space will prevent them from working.
A particular issue in Python is that indentation must be correct.
1x = 10
2 y = 11
3z = 12
4print(x,y,z)
Exercise
Can you spot and fix the bug in Program 2.21?
1def myfunction:
2 print "hello"
3
4myfunction()
Exercise
Program 2.22 has two bugs to fix.
- 1
There are other kinds of list that are not arrays but this need not concern the beginner.