Training, Open Source Programming Languages

This is page

Our email: • Phone: 01144 1225 708225

For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Python module Y109
Exercises, examples and other material relating to training module Y109. This topic is presented on public courses Learning to program in Python, Python Programming, Intermediate Python

There's a limit to how many checks you can build into programs, and some things (such as a connection being lost) that you can't check for at all. Exceptions allow you to try to run a block of code, and if it fails you jump to a block that catches the exception so that you can.

Related technical and longer articles
errors v exceptions

Articles and tips on this subjectupdated
4444Elements of an exception in Python - try, except, else, finally
All the elements of an exception handler in one example ... [here] try - enters at the top and continues through the block except - jump to there is an exception is thrown else - run after the try block completes without exception thrown finally - always run after the other blocks have completed A ...
4161Python varables - checking existance, and call by name or by value?
A couple of good questions from a recent delegate... Q. How do I check for the existance of a variable in Python? A. Reference it and see if an exception is thrown. Here's an example in which I create a variable only if my program is run with command line parameters:   import sys   if ...
4029Exception, Lambda, Generator, Slice, Dict - examples in one Python program
A new example from last week's Python course, showing exception, lambda, generator and list slices in a practical programming example. The task we took was to go through a file of railway stations and ticket sales figures, and report on the most and least used 20 in the UK. The programs's [here]. a) ...
3930Reporting the full stack trace when you catch a Python exception
Python exceptions are a safety net which let you catch data or program problems or other unexpected issues without having to explicity code each and every potential problem or problem group - a wonderful fail safe mechanism. If you fail to write your Python code with try and except blocks, it will use ...
3913How many times ... has this loco headed west through Tenby? - Python exceptions
If you have a stock of 117 locomotives on your railway, and each is on the front of a train through Tenby as it heads for Pembroke just 12 times a year (it's a Summer Saturday Special working!), will - in the course of their 30 year life - every locomotive have worked that train? Will the reason that ...
3664Error checking in a Python program - making your program robust via exceptions
Error checking of inputs, in some way, is vital. You may use conditionals such as if, you may precheck data before it reaches your program, or you may do both. But can you be sure you'll meet every eventuality? It's a difficult game forecasting everything that might go wrong. By using excpetions, ...
3441Pressing ^C in a Python program. Also Progress Bar.
If you want to stop a user interrupt via ^C aborting your program, you can catch a KeyboardInterrupt in Python. There's an example [here] which I wrote earlier today. It also shows how important it might be to use two try/except blocks rather than one - I've specified two inputs in the same block and, ...
3433Exceptions - a fail-safe way of trapping things that may go wrong
As part of a previous post, I was looking at the "Internal Server Errors" logged on our web server over the past 3 months ... and I found one coming from a Python / CGI demonstration which I wrote and uploaded for a delegate a couple of months back. Internal server error 500 (by default on Apache httpd) ...
3177Insurance against any errors - Volcanoes and Python
Have you heard of people who have taken out insurance, only do discover that they're not covered for some eventuality - "but the list of circumstances doesn't include your flight being canceled because the plane couldn't fly through volcanic ash" is a story that many people heard, with an irony that ...
2998Using an exception to initialise a static variable in a Python function / method
Exceptions are sometimes "sold" as a way of trapping errors - but they're more than that - they're an excellent way of trapping conditions where there isn't a valid result. "How many people live in this house" you may ask of a function / method call, and the answer may come back as "2" or "5" ... or ...
2994Python - some common questions answered in code examples
Some tips and new examples from last week ... Python in Plymouth! • How do I put comments in a Python regular expression to make it more readable: [source] • How do I use a python dictionary as a table of counters - in our example, counting the number of people in our team who have each of ...
2622Handling unusual and error conditions - exceptions
"I can't answer that question in the way you expect" ... that's something that may be said to you occasionally - you ask someone what suit a playing card is that they're holding and they cannot tell you because it is a joker, or you ask what number is written on a piece of paper when the paper is blank. The ...
2408Robust user input (exception handling) example in Python
One of the questions in the "exceptions" section of the Python Course asks my delegates to "Graham Proof" a piece of code: first = int(input("First number: ")) second = int(input("Second number: ")) print "Sum is "+str(first+second) The idea is that I come round the room and put really awkward inputs ...
2368Python - fresh examples of all the fundamentals
Some more new examples in Python - from this week's course. From my Introduction to Python / simple example to show the power of the language, I present my example that parsed a big data (log) file and counter and sorted by number of accesses the hits from various remote hosts. A long report, ending ...
2281Python - using exceptions to set a fallback
In Python, you should use exceptions to catch error conditions such as files that you're unable to open, broken network connections, and user inputs which give a problem - it's all very well putting traditional checks in your code, but you'll be well advised to use try and catch as well for additional ...
2018UnboundLocalError - Python Message
What does THIS mean? UnboundLocalError: local variable 'taxrate' referenced before assignment It means that you have tried to modify the value of a variable - perhaps in a function - before you have given it an initial value: taxrate = 15 def getnet(gross):   taxrate /= 100.   net ...
1236Trying things in Python
Are you used to writing long sections of code to validate user input? Perhaps you are, or perhaps you have shortened such code over the years using Regular Expressions where you can specify a pattern to be matched. One regular expression can replace 30 lines of other code. But in Python, Java and ...
1042Nested exceptions in Python
Yes, you can nest exceptions in Python - here's an example from yesterday's course. I'm reading in lines from a data file and counting the numbe of occurrences of a particular series of events in a dictionary of dictionaries. An exception is thrown if a counter doesn't already exist ... we'll catch ...
381Exceptions in Python
Rather than having to check ahead of time for every possible error, Python provides an exception handling capability too. Simply try to perform you action, and define what's to be done in an except block if the action you want can't be completed. Here's an example in which we (try to) read an integer ...
Examples from our training material
attempt   full traceback log from exceptions   Program with a bug!
dbnover   Events spread over a number of units   Use of pass to provide an empty block
duff   Try, except, else and finally   Using excpetion for fail-safe error handling   Read from a URL resource with error trapping   Using excpetions to allow *some* user errors   try and except within a loop
kx   Answer to exercise   static variable in Python
ouch   try, except, finally example
oy   Raising Exceptions yourself
prog   Status line. Also trapping ^C   Handling multiple exceptions types
railx   Busiest and quietest stations   passing exceptions back to calling code   Example of a runtime error   Example of a piece of code that sometimes crashes
stopc   trapping ^C in Python   Example of a syntax error
topstats   Exception, Lambda, dict   Use of try and except
ui   Read an integer - validated   static variable - initialise via exception
Python practical on a Public training course in Melksham
Background information
Some modules are available for download as a sample of our material or under an Open Training Notes License for free download from [here].
Topics covered in this module
What is an exception?.
Using try and except.
Types of exceptions.
Running mandatory cleanup code.
Raising an exception.
Practical examples - exceptions in use.
Simple application - generate a list of prime numbers.
Code testing and optimisation.
Complete learning
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule page.

Well House Consultants specialise in training courses in Ruby, Lua, Python, Perl, PHP, and MySQL. We run Private Courses throughout the UK (and beyond for longer courses), and Public Courses at our training centre in Melksham, Wiltshire, England. It's surprisingly cost effective to come on our public courses - even if you live in a different country or continent to us.

We have a technical library of over 700 books on the subjects on which we teach. These books are available for reference at our training centre.

© WELL HOUSE CONSULTANTS LTD., 2024: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: • WEB: • SKYPE: wellho

PAGE: • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb