Raspberry_Pi_Education_Manual

Notes:

The main part of the Roman Numerals program also introduces the idea of “ exceptions ”. When a function you write detects something wrong, you need to let the callers of your code know. You can do this by raising an error.

if number < 1 or number > 4999: raise ValueError

“ValueError” is raised by other parts of Python when you attempt an operation on a variable that cannot be done, so we’ve used it here. The program catches the exception and prints a message.

except ValueError :

print ( "Try again" )

Troubleshooting those bugs A “bug” is computer jargon for a mistake in your program. I have not intentionally put bugs in the listings, so if you find you cannot run a program or it gives a weird response, you have somehow introduced a bug. The term has been around since the time of Thomas Edison (c. 1878) but the often-reported case of a moth causing a problem inside a computer around 1947 cemented the term in the world of computers. The ability to track down bugs is an invaluable skill for all programmers. With all the best intentions and planning, mistakes can be made. When starting to program, it is better to type in the examples listed here. It might take longer but you are in training. You are training to type and how to avoid making typing errors. Your ability to proof-read code will increase as you work through these examples. When you find a bug, don ’ t panic and start changing code at random. Look at the listing, look at your code, and work through each part logically to find out what you should be seeing, compared to what you are actually seeing. The errors given by Python will be confusing but it is only by following the instructions in your code and telling you why it cannot continue. At some point, you will discover that computer programmers use another program called a debugger to analyse and find bugs in their code as it runs. You won’t need the debugger just yet but there is an alternative method. The easiest method is to add “print()” commands to your code to find out what is going on in the variables and how far Python is through your program. Think of it as inserting a probe into the code to tell you what is happening. When you have removed all the bugs and your program runs properly, you can then remove all those print commands to clean up the results.

Experiments in Python

90

Made with FlippingBook flipbook maker