Week 4 Lab (1)
Week 4 Lab (1)
1 Prerequisites
This lab assumes certain knowledge on your part. Ensure that you are comfortable with creating
source code files and running them in the terminal, as well as submitting them to the online
marker. Knowledge of the basic terminal commands is also assumed.
You should be familiar with the concept of variables — the notion of type, how to declare
variables, and how to assign values to them.
If you are unsure of any of the above, please refer to the lecture notes or consult one of the
previous labs for explanations/examples.
Again, 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 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
python3 ). Briefly, if we create a new file called in put.py and we wish to execute the code,
we’d run 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.
1
2.1 Reading Error Messages
Oftentimes, there will be some error in the source code causes some error to occur. In this
case, it will produce messages that indicate the nature of the error. Becoming an excellent
programmer means being able to understand error messages and where the issue in your code
is. This is called debugging. Below is a sample program and the error message it produces:
1 # File: faulty.py
2 print("Enter a number:")
3 x = int(input())
4 print("The number you entered was" x)
This message indicates that at line 4, the interpreter encountered some unexpected syntax.
In other words, it saw a symbol that it did not expect to see. And indeed, on line 4, we can see
we left out a comma between the string and the variable!
Before asking someone for help, please check the error output to see if it offers information
on how to fix your problem.
2
3 If-Else
In th enotes, we looked at conditional (if) statements. As an example, the code algorithm can
be used to calculate the minimum of two numbers entered by a user. Please run and test the
code to make sure it works.
1 x = int(input())
2 y = int(input())
3
4 if x <= y:
5 min = x
6 else:
7 min = y
8
9 print(min)
Note that the statements within the if and else sections are indented. In Python, whites-
pace (tabs and spaces) are important! If you do not have the right indentation, your program
will fail to run, or run in unexpected ways! The indentations here let the interpreter know
which statements form the body of the if and else blocks. You can use either a single tab, or 4
spaces to indent. Whatever you choose, just be consistent.
We can also combine several if-else structures together if we wish to test a range of con-
ditions. For instance, we may wish to check whether a number is positive, negative or zero. We
would then have:
1 if x == 0:
2 print("x is zero")
3 elif x > 0: # elif means else if
4 print("x is positive")
5 else:
6 print("x is negative") # the only other option
NB: We use two equal signs when we want to test if one thing is equal in value to
another. We use a single equals for assignment only.
3
Submission 1: 3-Min
Write a program for finding and displaying the minimum of three real-valued numbers entered
by a user. To ease your task, pseudocode is given below.
input x
input y
input z
if x <= y
minimum = x
else
minimum = y
if z < minimum:
minimum = z
display minimum
Input
Input consists of a three real-valued numbers (of type float), each on a new line.
Output
Output the smallest of the three numbers.
Sample Output #1
1.9
4
4 Examples
4.1 If-else
4.3 Comparisons
1 x = int(input())
2 y = float(input())
3
4 if x > y:
5 print("x is greater than y")
6 if x < y:
7 print("x is less than y")
8 if x >= y:
9 print("x is greater than or equal to y")
10 if x <= y:
11 print("x is less than or equal to y")
12 if x == y:
13 print("x is equal to y")
5
14 if x != y:
15 print("x is not equal to y")
16 if x % 2 == 0:
17 print("x is even")
18 if x % 2 != 0:
19 print("x is odd")
20 if x < 0 or y < 0:
21 print("Either x or y is negative (or both are)")
22 if 9 < x < 100:
23 print("x is a 2 digit integer")
Submission 2: Grading
Write a program that accepts an integer in the range [0, 100] and outputs the corresponding
grade. Use the table below to match the mark with the correct grade. Be sure to output your
answer exactly as it is written in the table.
Grade Mark
First 75+
Upper second 70 − 74
Lower second 60 − 69
Third 50 − 59
Fail < 50
Input
Input consists of a single integer specifying the mark.
Output
Output the corresponding grade.
Sample Output #1
Upper second
6
4.4 Nested if-statements
Note that we can also “nest” if-statements; that is, if-statements within if-statements. Pay at-
tention to the indentation — it determines which statements belong to which if statements!
Convince yourself that the code does what it says it will.
1 # Program 1
2 x = float(input())
3 if 0 < x < 20:
4 print("x is between 0 and 20")
1 # Program 2
2 x = float(input())
3 if x > 0 and x < 20:
4 print("x is between 0 and 20")
1 # Program 3
2 x = float(input())
3 if x > 0:
4 if x < 20:
5 print("x is between 0 and 20")
7
Submission 3: Leap Year
A leap year is a calendar year that contains one extra day.a Write a program that accepts a year
and outputs whether that year is a leap year or not. The following rules determine leap years:
• Years that are exactly divisible by 100 are only leap years if they are also divisible by 400
• Years that are not divisible by 100 but are divisible by 4 are leap years
To accomplish this, you need to define what we mean by “divisible”. [Hint: You might need the
modulus operator]
Input
The input consists of a single year (a non-negative integer) y read from the user.
Output
If the given year y is a leap year, output [y] is a leap year; otherwise, output
[y] is not a leap year
See the example output below if this is unclear.
Sample Output #1
2017 is not a leap year
Sample Input #2
1900
Sample Output #2
1900 is not a leap year
Sample Input #3
2016
Sample Output #3
2016 is a leap year
a
We are fans of leap years, as they give us one extra day to do some more programming!
8
Submission 4: Rock-Paper-Scissors
In the popular game Rock-Paper-Scissors (RPS) two players compete against one another by
simultaneously making one of three hand symbols: rock, paper or scissors. The outcome of
the game depends on the symbols both players have chosen: a player who decides to play rock
beats another player who has chosen scissors (“rock crushes scissors”) but will lose to one who
has played paper (“paper covers rock”); a play of paper will lose to a play of scissors (“scissors
cuts paper”). If both players choose the same shape, the game is tied.
Your task is to write a program that takes as input the choices made by two players (Player 1
and Player 2), and outputs the result.
Input
Your program will receive 2 lines of input: the first line is Player 1’s choice (either rock, paper,
or scissors), while the second line is Player 2’s choice.
Output
Given the above input, you should output the result of the game. There are only three possible
outcomes:
1. Player 1 wins
2. Player 2 wins
3. Tie