1/29
Looks like no tags are added yet.
Why does print(y) fail if y has not been assigned?
NameError: y is not defined yet.
Why is if x=3: invalid Python?
Assignment was used in a condition; write if x==3:
Why does x = np.array([1,2,3]); x[3] fail?
Out-of-range index: valid positions are 0,1,2
Why does np.sqrt(4+5) differ from np.sqrt(4)+5?
Parentheses change which expression is under the square root.
What must follow if, elif, else, and for headers?
A colon : and an indented body.
How should you trace code by hand on an exam?
Track variable values line by line; use a small table for loops.
Debug: radius = np.sqrt(1+8*np.exp(1) // missing final parenthesis
Correct to radius = np.sqrt(1 + 8*np.exp(1))
Debug: area = np.pi*radius^2
Use radius**2: area = np.pi*radius**2
Debug: x = np.array(1,2,3)
Use brackets for data: x = np.array([1,2,3])
Debug: print(x[3]) for x=np.array([1,2,3]
IndexError; use indices 0,1,2 or x[-1] for the final value.
Debug: y=x+2 when x is undefined
Define x first, then calculate y.
Debug: a=np.linspace(0,1,0.1) for spacing 0.1
Use 11 points: np.linspace(0,1,11)
Debug: x=np.arange(0,5,5) when five unit-spaced values wanted
Use np.arange(0,5,1), giving [0,1,2,3,4]
Debug: y=np.abs(x[x>0]) when all nonzero magnitudes wanted
Use np.abs(x[x!=0]); x>0 excludes negatives.
Debug: x[x>0 and x<5] for a NumPy array
Use x[(x>0) & (x<5)] with elementwise &
Debug: loop sum starts at total=1 for summing 1..4
Use total=0 to avoid adding an extra 1
Debug: for k in range(1,n): when sum should include n
Use range(1,n+1) because the stop is excluded.
Debug: for k in range(5): x[k+1]=... on x=np.zeros(5)
Last index k+1=5 is out of bounds; use range(4)
Debug: for k in range(4) print(k)
Add a colon: for k in range(4):
Debug: if x>0: followed by an unindented print inside its block
Indent the body, for example four spaces before print(...)
Debug: if np.sin(np.pi)==0 expects exact equality
Floating-point values can be slightly off; test abs(np.sin(np.pi))<tol
Debug: if x>0: when x is a whole NumPy array
Use (x>0).any()/.all() for one Boolean, or x[x>0] for selection
Debug: y=x; x[0]=9 changed y too
Use y=x.copy() if you need independent arrays
Debug: trying to call np.pi()
Remove parentheses: np.pi is a constant
Debug: root-finding chooses [a,m] even though f(a),f(m) have same sign
Keep the half with opposite endpoint signs instead
Debug: checking f(a)==0 only and assuming there is no interior root
Evaluate a bracket and midpoint; roots can be between endpoints
Debug: using (a+b) / 2 but never updating a or b
Update one endpoint after testing signs so the bracket shrinks.
Debug: plotting y=x**2 with no x array defined
Create an x grid before calculating y, e.g. x=np.linspace(-2,2,41)
Debug: code prints y before assigning y on a later line
Move the print below the assignment to y
Debug: forgetting to use one variable from an earlier step
Check names and execution order; use the assigned variable consistently