Jed Rembold & Fred Agbo
January 29, 2025
Which of the below blocks of code would print something different from the others?
for n in range(10):
if n % 2 == 0:
print(n)
for i in range(0,10,2):
if i > 0:
print(i)
for j in '02468':
L = int(j)
print(L)
for k in range(0,10):
if not (k % 2 > 0):
print(k)
Suppose we wanted to write a function to compute the greatest factor of a provided number (not including the number itself)
Algorithm:
def greatest_factor(num):
"""Finds the greatest factor of a number."""
for i in range(num-1,0,-1):
if num % i == 0:
return i
If debugging is the process of removing software bugs, then programming must be the process of putting them in.
Edsger W. Dijkstra
Concentrate on what your program IS doing, instead of what it SHOULD be doing.
Let Python help you: print or log the state of different variables.
Stop and read. The documentation. The error messages.
The rich
library offers some very
pretty error messages: install with
pip install rich
At the top of your code, then include:
from rich.traceback import install
install(show_locals=True)
Use PythonTutor or a debugger to track EXACTLY what is happening in your program.
Don’t make random changes to your code in the hopes that it will miraculously start working.
Talk it out.
Test your code as you go! Either manually or automatically.