Lab 2
Lab 2
Abstract—In this lab you will practice with simple while loops, and at the same time you will use formal software development methods
such TDD to solve problems. Input/Output redirection is introduced as a method for automatic testing on functions that include
standard input.
Figure 2. inputs_testcases_P1.txt
Figure 1. New plain text file in PyCharm.
Examine this file, and make sure you understand why
• Name your new file as each of this numbers are in their current positions. Here a
inputs_testcases_P1.txt. ( Notice the txt short explanation for this case:
extension, NOT py). • On test1 your input needs to be the correct PIN in
• Then, inside your new plain text file, write down the the first try. This is line 1 in figure 2.
inputs for all your test cases in the same order, one • On test2 your input needs to be an incorrect PIN first
line per input. In this case, for example, the new file and then the correct one. These are lines 2 and 3 in
will look as shown in figure 2. figure 2.
3
• On test3 your input needs to be two incorrect PINs If you attempt to run this python script from the Py-
followed by the correct one. These are lines 4 to 6 in Charm run utility, you will have to type input values in the
figure 2. PyCharm run console.
• On test4 your input needs to be three incorrect PINs. However, the main idea in creating a input file is to avoid
These are lines 7 to 9 in figure 2. typing anything during the test. This can be done by stdin
redirection. In a command line, you can use operator < to
Since the test cases were layout in this particular order, this
redirect the stdin or > to redirect the stdout.
input file should follow that order too.
To run this program:
3.1.4 Step 4. Flowchart proposal 1) Open the PyCharm Terminal.
Figure 3 shows a proposal. Remember this is the design part CAREFUL: Do not confuse Terminal with Python
of the problem. Here you are thinking what should be the Console. A Terminal is an OS command prompt.
behavior of your algorithm. In general, every person will The PyCharm Terminal has the advantage of be-
create a slightly different solution. ing inside the PyCharm GUI. Remember, command
dir will show you the content of the current folder.
2) In the Terminal, execute your program with this
pinvalidw command:
(Integer maxtries)
accepted = False
What this command is telling the OS is: Using python
as interpreter, execute script Lab2_P1.py and send the
True
tries < maxtries and not
accepted
content of file input_testcases_P1.txt to stdin.
False
Input pin
3.1.6 Step 6. Using your function in some other python
False True
script
pin ==
CORRECTPIN
If you ever need your new function somewhere else, just
import it using any of the import method you know.
tries = tries + 1 accepted = True
False True
Output "Your PIN is Correct" Algorithm 3 Function called from another program.
tries ==
maxtries
1 """
Output "Your PIN is Output "Your Card has been 2 Program that uses a function to validate
incorrect, Try again" blocked. Call your Bank"
3 a PIN in an ATM.
4 """
5
6 from Lab2_P1 import validatepin
7
Return Boolean accepted
8 accepted = validatepin(3)
• The result is the total sum divided by the number of Algorithm 4 Template for Lab2_P2.py
grades.
1 """
2 Program to compute average over an undetermined
– What if the first input is −1? 3 number of grades in the range 0 to 100.
– A division by zero must be prevented. 4 """
5
6 def gradesaverage():
• We need to write a function such: 7 """
8 Function to solve the given problem.
– Function arguments: None 9 :return: final. A float.
10 """
– Function return: The final average grade. 11 pass # your code goes here
12 return final
• Test cases must include different input sizes and 13
14 def testreport(testnumber, testresult):
values. 15 """
16 Function to print the result of a test case
– Testing for (−1) as the first input is a must. 17 :param testnumber: An integer with test ID number.
18 :param testresult: A boolean with the result of
current test.
3.2.2 Step 2. Program Script. 19 :return: nothing.
20 """
Create a new python file and call it Lab2_P2.py. 21 if testresult:
22 print("Test %d has passed." % testnumber)
23 else:
24 print("Test %d has FAILED !!!! <<<< WARNING" %
3.2.3 Step 3. Write a template for your problem solution. testnumber)
25
We need a function for computing the grade average. This 26 def comparefloats(first, second):
function takes no inputs and returns the final grade average. 27 """
28 A function to compare two floats.
Here is a minimal set of test cases. You can add as much 29 :param first: One float number to compare.
as you see fit: 30 :param second: The other float number.
31 :Return: A Boolean. True if inputs are within
tolerance.
1) The first input is −1. Result should be zero. 32 """
2) One grade. 10. Result should be 10. 33 # define your tolerance
34 TOL = 1E-14
3) Two grades. 10 and 20. Result should be 15. 35 # return
4) Three grades. 10, 20, and 30. Result should be 20. 36 return abs(second - first) < TOL
37
5) Four grades. 50.5, 60.5, 70.5, 80.5. Result should be 38 if __name__ == "__main__":
65.5 39 # Test cases:
40
41 # Test 1: The first input is -1. Result should be
Remember, to compare float numbers just test if they are zero.
within a tolerance (example: 10−14 ). Do not compare floats 42 test1 = comparefloats(0, gradesaverage())
with ==. 43 # Test 2: One grade. 10. Result should be 10.
44 test2 = comparefloats(10, gradesaverage())
45 # Test 3: Two grades. 10 and 20. Result should be
• There is one more file to create this time. 15.
• In order to avoid typing all inputs yourself, lets put 46 test3 = comparefloats(15, gradesaverage())
47 # Test 4: Three grades. 10, 20, and 30. Result
all of them in a new plain text file. should be 20.
• Each input should be in a different line. 48 test4 = comparefloats(20, gradesaverage())
49 # Test 5: Four grades. 50.5, 60.5, 70.5, 80.5.
• You learned how to create plain text files in Lab1. Result should be 65.5
However, this time you can use PyCharm to create 50 test5 = comparefloats(65.5, gradesaverage())
51
it. Just right click on your project and select New >> 52 # Test reports
File, as in figure 4. 53 testreport(1, test1)
54 testreport(2, test2)
55 testreport(3, test3)
56 testreport(4, test4)
57 testreport(5, test5)
Examine this file, and make sure you understand why Algorithm 5 Python code for the problem P2.
each of this numbers are in their current positions.
1 def gradesaverage():
2 """
3.2.4 Step 4. Design a flowchart for your solution. 3 Function to compute average of grades.
4 :return: Final: The average.
Every single person will have a slightly different solution, 5 """
6
although in general they might do the same. Here is a 7 # initialize variables.
proposal. 8 sum = 0
9 counter = 0
10 done = False
11
gradeaverage
12 # Loop until is sentinel value is entered
13 while not done:
14 grade = float(input("Enter a grade: "))
sum = 0 15
16 # this next two lines are only for testing
purposes.
counter = 0 17 # when running in __main__ with input
redirection
18 # from a file, you want to see the input. So,
done = False
print it.
19 if __name__ == ’__main__’:
True 20 print(grade)
not done 21
Tips
1) Assume that the weather station is connected to
your standard input.
2) For every input, your program should produce stan-
dard output of the form:
Tue Feb 20 13:35:26 2018, Temperature
is 17.9000 C = 64.2200 F
• (use %10.4f for the temperature values)
3) The current date and time can be obtained using the
function ctime() from the module time.
from time import ctime
4) A file with all output can be created using redirec-
tion of stdout in Terminal.
python Lab2_P3.py < inputs_P3.txt >
output_P3.txt
5) Your program can be tested with some 3 or 4 short
cases.
If the time is obtained from the computer then it will
be different every time you run a test. How do you
test for it then if a comparison with a fixed value
will always fail?
6) In Step 6, use your program to convert all values
from −200.0 C up to +200.0 C in steps of 0.1 C.
Tip: Those are 4000 values. You don’t want to type
them manually into a file. But you can write a very
short python program (5 python lines) that writes
them for you.
4 F INISHING UP.
For this lab you have created several files.
1) Create a ZIP file (only one zip file called Lab2.zip)
containing all files you have created.
These include all .py files, .txt files and all
flowcharts you have created.
2) Upload it to Laboratory #2 assignment in Google
Classroom.
• This is an individual lab.
3) Before leaving the lab, verify with your TA/In-
structor that the submission was correct.
R EFERENCES
[1] Cay S. Horstmann and Rance D. Necaise. 2015. Python for Everyone
(2nd ed.). Wiley Publishing.