Assignment and coding tips

  • Analytical derivative is just the regular derivative: $$x^2 \to 2x $$
  • There are hidden tests which use 'numpy', some people manually write 'import numpy as np', if you are doing this put it on a new line so that 'import numpy' alone is still there.
  • Remember to 'Restart and Run all' in the kernal menu
  • There are marks for titles / labels etc...

Notebook server

Please make sure to use this year's server!

https://compphys-2324.notebooks.danielmaitre.phyip3.dur.ac.uk

Read the error!

Error types in Python guide you to the issue.

The last lines of the traceback are key.

Inspect the line where the error occurs and its predecessor.

Managing Infinite Loops

Infinite loops pose a unique debugging challenge because they keep running, causing either:

  • No output, making it unclear if the program is stuck
  • Excessive output, which can overwhelm the system

Implement a loop counter as a best practice to prevent infinite loops.

  icounter = 0
  while True and icounter < 10000:
      icounter += 1
      # Execute some code
      if condition:  # Replace 'condition' with your actual conditional statement
          break
  
  if icounter == 10000:
      print("Loop terminated due to counter.")
                          

Handling Off-by-One Errors

An Off-by-One error occurs when a loop iterates one time too few or too many.

In the following example, the loop runs nsteps times:

for i in range(nsteps):
    result[i] = ...
                        

The loop's highest index value is i = nsteps - 1.

The function range(beg, end) iterates from beg to end - 1, covering end - beg steps.

Focusing on the first element and total steps often simplifies reasoning about loop boundaries.

Non-Subscriptable Object Error

This error arises when using array syntax x[i] on a non-subscriptable object like x.

def f():
  return [1, 2, 3, 4]

f[1]
                      

In this case, f is a function. To make it subscriptable, invoke it first:

f()[1]
                      

TypeError: ‘XXX’ object is not callable

With xxx either float or int. This happens normally when parenthesis are forgotten.

In [23]:
3(x-y)
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-23-112ceb8d6610> in <module>()
    ----> 1 3(x-y)
    
    TypeError: 'int' object is not callable