Lab 2
Lab 2
1 Introduction
Before beginning, please make sure you have completed last week’s lab. You should be able to
submit your programs to the automatic marker on Moodle, and be comfortable with the basic
terminal commands.
You will also need to know how to create a source code file (a .py file), and execute it (using
the python3). Briefly, if we create a new file called input.py and we wish to run the program,
we execute it in the terminal by typing
python3 input.py
Refer back to the previous lab if you are unsure of how to do any of the above.
Please read this lab (and all labs) very carefully. They will contain information about
how to successfully complete a given exercise, as well as some content that may not be
covered during lectures.
2 A Look Back
Let’s have a quick look at the program you submitted to the marker. Here it is again:
2.1 Comments
We have added comments to the program. 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. For more information about comments, see
https://docs.python.org/3/tutorial/introduction.html.
1
2.2 Printing
When we run our code, the text Hello, world! is displayed on screen. Outputting values to
the screen is known as printing. The print function will display whatever is inside the brackets
(in this case, a string) and a new line, which will position the cursor at the beginning of the
next line. We can see this if we modify the code to add another print statement. Change your
code to look like this:
1 print("Hello, world!")
2 print("I'm on the next line!")
When you run it, you’ll see that the two strings are printed on different lines. If we do not
want a new line to be printed, we use use the end parameter. For example, the following will
print everything on the same line
1 print("Hello, world!", end="") # instead of a new line, end with empty string
2 print("I'm on the same line!")
3 The Interpreter
So far, we have been using the interpreter in batch mode. That is, we write all our code at
once in a text file, and then run all of it an once at the end. The Python interpreter also has
an interactive mode, where we can directly execute code one line at a time. To open the
interpreter in interactive mode, open a terminal, type python3 and hit enter. You should see
this:
2
Note the Python version we are running — it starts with a 3. If we by mistake just typed
python, it would start a Python 2 interpreter, and the version would start with a 2. That would
be bad. Don’t do that!
We can use the interactive mode to try out things quickly. For example, you can use it
like a calculator! Type the following commands, hitting enter after each one. Make sure you
understand how the answers are produced.
1 2 + 5
2 2 - 2.5
3 5 / 7
4 6 // 7 # what is this again?
5 abs(-4)
6 pow(2 ,6) # what does this do?
7 2 ** 6 # what does this do?
For submissions though, we will be using batch mode. That is, we’ll be writing our code in
full, and then executing it all at once.
4 Variables
4.1 Name
A variable is identified by its name, which consists of a series of one or more of letters, digits or
underscores. Variables should be given meaningful names to aid in readability — short names
3
can indeed be meaningful, while overly long names can annoy. There are certain keywords
which cannot be used as variable names, and are listed here: https://www.w3schools.com/
python/python_ref_keywords.asp
4.2 Type
In Python, the type of a depends on the value it is referring to. Unlike languages such as C++,
Python variables can change their type dynamically. The default data types in Python are int
(integer), float (real number), str (a string/piece of text) and bool (a boolean: either true or
false). Note that strings are specified in either single or double quotes. We can query the type
of a variable using the type function. Try out the following code in interactive mode:
1 x = 10
2 type(x)
3 name = "Bob" # can use single quotes too
4 type(name)
5 z = 2 / 4
6 type(z)
7 x = False
8 type(x) # x was an integer, but now it's ???
5 Output
In interactive mode, any expression that produces a result is displayed on screen. However, in
batch mode (where all of our programming will be done), we must explicitly use the print
function to display something to screen. We can use print to display any value or any variable,
regardless of type.
6 Input
In order to accept input from the user, we first need to declare an appropriate variable and then
use the input function to read the user-entered value into the variable. Note that the value read
in is by default a string, so if we want an integer or some other type, we must cast the input to
the required data type.
As an example, the following code asks the user to enter their name and outputs an appro-
priate greeting. Write the following code into a file and then execute it. Type your name and
age, hitting Enter after each.
1 name = input("Enter your name:") # read in a line of text and store in name
2 age = int(input("Enter your age:")) # we cast the input to an integer
3 print("Hello", name) # print on the same line. A comma adds a space between them
4 print("You are", age)
4
7 Basic Operators
Now that we have variables, we can begin to perform operations on them. Python 3 offers the
following arithmetic operations that can be performed on numeric variables:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
// Integer division
% Modulo (remainder)
The operators all adhere to the BODMAS principal in terms of precedence, and brackets can be
used just as they would in regular mathematical expressions.
Additionally, the Python offers some additional mathematical functions, such as absolute
values and exponentiation. We can also import the math module to gain access to even more
mathematical functions (see a list of all functions available here: https://docs.python.org/
3/library/math.html).
The following code illustrates some basic usage. Again, try predict the output of the code
and then run it to see what happens.
5
8 Submissions
This section details the tasks you are required to perform and submit to the online marker.
Again, please bear in mind the strict rules regarding plagiarism. For each task, you will be given
some input and asked to produce some output. Examples of input and corresponding output
will be given, but your program must be able to output the correct answer for all possible
inputs in order to receive the marks.
For each task, create an appropriate .py file and write the necessary code. Once you’ve
run and tested the code to ensure that it is correct, submit the .py file to the online marker.
You may submit as many times as you wish without penalty. As your submissions are marked
automatically, your program should output only what is asked for. Nothing more and nothing
less. You may submit them in any order you wish.
When you submit a Python program on Moodle, you should expect one of the following
outcomes:
• Error: Your program encountered an error while it was running. Make sure your program
handles handles the input as it is described in the submission instructions.
• Wrong Answer: Your program returns the wrong answer when tested on the hidden input
data. Make sure your program doesn’t print out anything that is not required. Make sure
your program handles special cases.
• Presentation Error: Either you have not used the correct capitalizations, or you don’t
have the correct spacing.
6
Submission 1: Doubling
The following code reads in an integer from input and outputs the number with 5 added to it.
1 x = int(input())
2 y = x + 5
3 print(y)
Modify the code so that your program reads from input a single integer, and outputs twice its
value.
Input
Input consists of a single integer N .
Output
Output 2N .
Sample Output #1
24
Submission 2: Difference
Write a program that reads from input two real numbers and outputs their difference.
Input
Input consists of two real-valued numbers x and y, each on their own line.
Output
Output x − y.
Sample Output #1
-0.5
7
Submission 3: Statistics
Write a program that computes and displays the mean, variance and standard deviation of four
real numbers entered by a user. To compute the mean, variance, and standard deviation of
numbers a, b, c, d entered by a user, use the following three equations:
a+b+c+d
mean = (1)
4
Input
Input consists of four real-valued numbers a, b, c, d, each on their own line.
Output
Output the mean, variance and standard deviation of the numbers, each on a new line.
Sample Output #1
2.25
9.1875
3.031088913245535