0% found this document useful (0 votes)
7 views

Week 4 Lab (1)

The document is a lab guide for an Introduction to Algorithms & Programming course at the University of the Witwatersrand. It covers prerequisites, basic programming concepts in Python, error message debugging, conditional statements, and provides several programming exercises including finding the minimum of three numbers, grading based on input marks, determining leap years, and implementing the Rock-Paper-Scissors game. Students are encouraged to refer to previous labs and lecture notes for additional guidance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week 4 Lab (1)

The document is a lab guide for an Introduction to Algorithms & Programming course at the University of the Witwatersrand. It covers prerequisites, basic programming concepts in Python, error message debugging, conditional statements, and provides several programming exercises including finding the minimum of three numbers, grading based on input marks, determining leap years, and implementing the Rock-Paper-Scissors game. Students are encouraged to refer to previous labs and lecture notes for additional guidance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

U NIVERSITY OF THE W ITWATERSRAND , J OHANNESBURG

School of Computer Science & Applied Mathematics

Introduction to Algorithms & Programming

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)

File "a.py", line 4


print("The number you entered was" x)
^
SyntaxError: invalid syntax

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.

Example Input-Output Pairs


Sample Input #1
1000
1.9
2.7

Sample Output #1
1.9

4
4 Examples

Here are some more examples of if-statements:

4.1 If-else

1 # Calculate min and max of 2 numbers


2
3 x = float(input())
4 y = float(input())
5 if x < y:
6 smaller = x
7 larger = y
8 else:
9 smaller = y
10 larger = x
11 print("The smaller number is", smaller, "and the larger number is", larger)

4.2 Multi-way Decisions

1 # Display whether x is positive or negative


2
3 x = float(input())
4 if x < 0:
5 print("x is negative")
6 elif x > 0:
7 print("x is positive")
8 else:
9 print("x is zero")

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.

Example Input-Output Pairs


Sample Input #1
70

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 # Calculate max of three numbers


2
3 x = float(input())
4 y = float(input())
5 z = float(input())
6
7 if x > y:
8 if x > z:
9 max = x
10 else:
11 max = z
12 else:
13 if y > z:
14 max = y
15 else:
16 max = z
17 print("The largest number is", max)

Question: Are the following three programs the same?

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

• No other years 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.

Example Input-Output Pairs


Sample Input #1
2017

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

Example Input-Output Pairs


Sample Input #1 Sample Input #2 Sample Input #3
rock scissors paper
paper paper paper

Sample Output #1 Sample Output #2 Sample Output #3


Player 2 wins Player 1 wins Tie

You might also like