-
Notifications
You must be signed in to change notification settings - Fork 1
Debugging
Bram Cohen, the creator of BitTorrent wrote, "90% of coding is debugging. The other 10% is writing bugs". Even amongst Computer Science college students, there is the belief that encountering bugs in the coding process is inevitable. I just have a simple suggestion; get good.
There is nothing inherent with coding that creates bugs. Computers do exactly what you tell it to do. My biggest recommendation to preventing bugs is to actually take out a sheet of paper and write down a roadmap of the logic you want your program to follow. You can then break down the problem into easy, bite-sized chunks.
Python also has some tools that help you determine exactly what your program is doing and where it is going awry. We will be exploring those tools and they may hopefully help you The earlier you catch bugs, the easier they will be to fix.
Syntax errors are the most common errors while one is learning Python. The way to read Syntax Errors is to determine what line the error is occuring at and find the error before the little arrow. In this case, the syntax error is caused by missing a colon (:) for the while statement.
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntaxEven though code may be syntatically correct, it still may cause an error when the Python interpreter tries to run it. Exceptions are usually used in cases where your program is expecting user input and the user may input something you do not expect.
>>> 5/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zeroIt is possible to handle exceptions so that your program can recover so that your program knows how to deal with these errors instead of crashing fantastically. This is done with the try-except block.
while True:
numerator = int(input('Please enter a numerator: '))
denominator = int(input('Please enter a denominator: '))
try:
print(str(numerator/denominator))
except ZeroDivisionError:
print('You cannot divide by zero. Try again...')If there are no problems with the code, the try block runs normally. If there is a problem inside of the try block, Python will jump straight to the except block. An except block can take a tuple containing multiple exception types.