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

lec_file_debugging

Uploaded by

ramii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lec_file_debugging

Uploaded by

ramii
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Agenda

• Working with Files


CSCE 160
Intro to Computer Science • Debugging

Prof. Kim

© 2016-2024 Sun-il Kim. 1 © 2016-2024 Sun-il Kim. 2

1 2

Storage
• Memory: Temporary, short-term storage • https://websites.umich.edu/~umfandsf/other/ebo
– Once you close the program, it’s gone oks/alice30.txt
– Once you turn off the computer, it’s gone

• Hard drive: Long-term storage


– Once saved, it stays on the drive until you
delete it or there is a hardware failure

© 2016-2024 Sun-il Kim. 3 © 2016-2024 Sun-il Kim. 4

3 4

import sys, os
Some questions about reading from files
#setup file path/directory: to where the .py file is
__location__ = os.path.realpath(os.path.join(os.getcwd(),
os.path.dirname(__file__))) • What happens if the file does not exist?
It is telling the computer
that you are going to READ
def readFile(fileName):
from the file
#setup file to open • How do you process the data once read?
file = open(os.path.join(__location__,fileName), 'r')
– It is stored as an array of strings (line by line)
#read data as an array of strings → character matrix – It can be treated as a matrix of characters
data = file.readlines()
print(data)

#close the file


file.close()

fn = input("What file you wanna read?:")


readFile(fn)
© 2016-2022 Sun-il Kim. 5 © 2016-2022 Sun-il Kim. 6

5 6

1
import sys, os
Exercise
#setup file path/directory: to where the .py file is
__location__ = os.path.realpath(os.path.join(os.getcwd(),
os.path.dirname(__file__))) • Write a function that counts the occurrence of certain
It is telling the computer characters in the text file
that you are going to READ
def readFile2(fileName):
#setup file to open
from the file def countLetter(data, myChar):
file = open(os.path.join(__location__,fileName), 'r') #return how many times myChar shows up in data
#read data as an array of strings → character matrix
data = file.readlines()
for row in range(len(data)):
print(data[row])

#close the file


file.close()

fn = input("What file you wanna read?:")


readFile(fn)
© 2016-2022 Sun-il Kim. 7 © 2016-2024 Sun-il Kim. 8

7 8

def writeFile(fileName):
#open file so we can write to it.
f = open(os.path.join(__location__,fileName), 'w')
Solving a Mystery
It is telling the computer that you are
going to WRITE to the file
{(“The case is one where we have been
compelled to reason backward from
for i in range(10): effects to causes.”
f.write("wow. I'm writing to a file. i=" + str(i) + "\n")
– Sherlock Holmes)
The write function takes in ONE parameter (as a string).
Anything you want written must be converted to a single string, OR – The Adventure of the Cardboard Box}
you can call the write function multiple times (each time passing in a string).
– Sir Arthur Conan Doyle
f.close() #safely closest out the file

fn = input("What file name do you want to use to save?:")


writeFile(fn)

Exercise:
What happens if the file with the same name already exists?
What if it does not exist?
© 2016-2022 Sun-il Kim. 9 © 2016-2024 Sun-il Kim. 10

9 10

Finding the bug in your code Debugging


Every line of code is suspect until proven innocent • The programs you write will have bugs…
by debugging. However, the programmer is always
• compile time error vs. run time error and…
guilty. • logical error

• Compile time problems are easy (the compiler tells you


exactly what the problem is)

• Run time problems are also easier now (the tool tells you
where the program crashed)

• Logical errors are harder


– You have to figure out where the problem is

© 2016-2024 Sun-il Kim. 11 © 2016-2024 Sun-il Kim. 12

11 12

2
initial inspection:
How do you start debugging? def testFunc3():
# here we have a more elusive logical problem that does NOT
• Compile-time errors are easy… # result in a runtime error. Rather, the result is just wrong.
Output example:
Enter side length a:3

• Run-time problems: a=float(input("Enter side length a:")) Enter side length b:4
– May or may not crash b=float(input("Enter side length b:"))
c=float(input("Enter side length c:")) Enter side length c:5
x (opposite side a): 50.20818050044277
• Start with an educated guess on where the problem is #get angles y (opposite side b): 0.0
• Inspect the program STATE x = math.acos(((b*b)+(c*c)-(a*a))/(2*c*c)) z (opposite side c): 90.0
– The program is obviously not working as you intended… y = math.acos(((a*a)+(c*c)-(b*b))/(2*a*a)) Area 6.0
z = math.acos(((a*a)+(b*b)-(c*c))/(2*b*b))
– You will NOT find the solution in your head → It’s in the code…
inspect it! #get area
– Do NOT randomly move things around area = a*b*math.sin(z)/2

– Check the logical flow of the program #convert radians to angles


– Check value(s) held by variables x = x*(180/math.pi)
– Inspect how many times do loops run y = y*(180/math.pi)
z = z*(180/math.pi)
– Check array bounds
– Check the conditional statements print("x (opposite side a):", x)
• always true / always false print("y (opposite side b):", y)
print("z (opposite side c):", z)
print("Area", area)
– To start, try placing print statements to figure these things out.

© 2016-2024 Sun-il Kim. 13 © 2016-2024 Sun-il Kim. 14

13 14

Using the power of deduction Use prints to help inspect INTERMEDIATE values
def testFunc3(): def testFunc3():
# here we have a more elusive logical problem that does NOT Output example: # here we have a more elusive logical problem that does NOT Output example:
# result in a runtime error. Rather, the result is just wrong. # result in a runtime error. Rather, the result is just wrong. Enter side length a:3
Input side a:3
Input side b:4
Input side c:5 a=float(input("Enter side length a:"))
Enter side length b:4
a=float(input("Enter side length a:"))
b=float(input("Enter side length b:")) x(opposite a):NaN b=float(input("Enter side length b:"))
y(opposite b):55.771133672187425 c=float(input("Enter side length c:")) Enter side length c:5
c=float(input("Enter side length c:"))
z(opposite c):90.0 print (a, b, c) 3.0 4.0 5.0
Area:6.0 0.8762980611683406 0.0 1.5707963267948966
#get angles #get angles
x = math.acos(((b*b)+(c*c)-(a*a))/(2*c*c))
x (opposite side a): 50.20818050044277
x = math.acos(((b*b)+(c*c)-(a*a))/(2*c*c))
y = math.acos(((a*a)+(c*c)-(b*b))/(2*a*a)) y = math.acos(((a*a)+(c*c)-(b*b))/(2*a*a))
y (opposite side b): 0.0
z = math.acos(((a*a)+(b*b)-(c*c))/(2*b*b)) z (opposite side c): 90.0
3 5 z = math.acos(((a*a)+(b*b)-(c*c))/(2*b*b))
Area 6.0
print(x, y, z)
#get area
area = a*b*math.sin(z)/2 4 #get area
area = a*b*math.sin(z)/2

#convert radians to angles • Area should be 3*4/2 = 6. This is correct.


x = x*(180/math.pi)
#convert radians to angles
x = x*(180/math.pi)
Inspecting the output:
y = y*(180/math.pi)
z = z*(180/math.pi)
• Angle Z, opposite side c should be 90. This is also correct. y = y*(180/math.pi) • We know that problem (y angle = 0.0) is not
z = z*(180/math.pi)
due to radians to angle conversion.
• Angle Y is wrong.
print("x (opposite side a):", x)
print("y (opposite side b):", y) • is it wrong because of radian to deg conversion? or
print("x (opposite side a):", x)
print("y (opposite side b):", y)
• because we fed this line 0.0 as input…
print("z (opposite side c):", z) • was it calculated wrong in the first place? print("z (opposite side c):", z)
print("Area", area) print("Area", area)
• Therefore, the problem came from the
original calculation for y
© 2016-2024 Sun-il Kim. 15 © 2016-2024 Sun-il Kim. 16

15 16

Using the power of deduction


def testFunc3():
Debugging Tool
# here we have a more elusive logical problem that does NOT Output example:
# result in a runtime error. Rather, the result is just wrong.
Input side a:3
Input side b:4 • Spyder has a debug mode that allows you to
Input side c:5
a=float(input("Enter side length a:"))
b=float(input("Enter side length b:")) x(opposite a):NaN inspect the program while it is running
c=float(input("Enter side length c:")) y(opposite b):55.771133672187425

#get angles
z(opposite c):90.0
Area:6.0
– Pause and Inspect variables during run-time
x = math.acos(((b*b)+(c*c)-(a*a))/(2*c*c))
y = math.acos(((a*a)+(c*c)-(b*b))/(2*a*a))
z = math.acos(((a*a)+(b*b)-(c*c))/(2*b*b)) 5
#get area
3
• You can use break points
4
– You can set break points to any line of code
area = a*b*math.sin(z)/2

#convert radians to angles • Area should be 3*4/2 = 6. This is correct.


x = x*(180/math.pi)
y = y*(180/math.pi) • Angle Z, opposite side c should be 90. This is also correct.
– The program will stop when it reaches a break
z = z*(180/math.pi)
point
print("x (opposite side a):", x) • Angle Y is wrong.
print("y (opposite side b):", y) • is it wrong because of radian to deg conversion? or • You can inspect the value of different variables
print("z (opposite side c):", z) • was it calculated wrong in the first place?
print("Area", area)
• Formula should have been:
arccos ( (b*b + c*c - a*a) / (2*b*c) )
(but why did it work for angle z?)
© 2016-2024 Sun-il Kim. 17 © 2016-2024 Sun-il Kim. 18

17 18

3
Double click to the left or line number
to set a break point.

© 2016-2024 Sun-il Kim. 19 © 2016-2024 Sun-il Kim. 20

19 20

When you run via the debug option, it will stop Notice that the variable explorer now has the new
at the break point. variable a with its value assigned.

Use the “run current line” button to execute Note that we are now at line 65.
code on line 64.
To see what the function call does, you have to
step into the function, instead of doing “run
current line.”

© 2016-2024 Sun-il Kim. 21 © 2016-2024 Sun-il Kim. 22

21 22

We are now inside testFunc2. Keep going down the line by clicking “run current
line,” and see what happens to the variables, and
You can continue by clicking “run current line.” watch the computer execute your program line by
line.

© 2016-2024 Sun-il Kim. 23 © 2016-2024 Sun-il Kim. 24

23 24

4
Exercise
• Test out the debugging.py program.
After a while, we are still in the loop. • Run one function at a time by modifying main.
The value of i is currently at 10 (see table above).
We are about to index into list[i] and it will cause
an array out of bounds error and return the
function with an index error (as you continue to
• Use the debugging tool to monitor the program
click on “run current line”) and see what happens.

• Try testFunc1. Run it multiple times. It will hang


sometimes. Place a breakpoint inside the loop
and watch the variable value as it is update in
each iteration of the loop. What is the problem
w/ the program?

© 2016-2024 Sun-il Kim. 25 © 2016-2024 Sun-il Kim. 26

25 26

You might also like