Starer: Find my errors:
- Look at the program on the left, it is based on an old nursery rhyme
- What does the program do?
- What should it do?
- There are 6 errors, correct them and make the program run
|
|
Lesson Introduction: An Example of Try and Except
Sometimes you will have a section of code that is working and then you will introduce a new section which makes it fail. This can be very frustrating indeed! To resolve this you can use try and except, try an section of code and if it fails then except it. Note that this is EXCEPT not accept.
Sometimes you will have a section of code that is working and then you will introduce a new section which makes it fail. This can be very frustrating indeed! To resolve this you can use try and except, try an section of code and if it fails then except it. Note that this is EXCEPT not accept.
- Look up the difference between accept and except
- Look at the code below and run it, it does not print line 7, why?
- What is the error?
- Without deleting the Try and Except, edit the program to print line 7.
- Look at the algorithmic representation of the code and discuss.
Part 2: Another Example:
- Run the code below and enter a number - what happens?
- Run it again an enter text / letters - what happens, why?
- On line 8 add the code line, print number, run the code what happens.
Part 3: Your turn
- Look at the code below - use a try and except to check that a number has been entered, if it has then print nice work, if not a number then print an error message of your choice.
- Check out the answer here
Part 4: Pay Day
- Look at the program below that works out your pay.
- Try it out, Enter Hours: 45, Enter Rate: 10, Pay: 450
- Rewrite the computation so that the employee gets paid 1.5 (15 punds) for every hour worked above 40 hours.
- How much do they get paid, check with your partner / teacher
- Now re-write your pay program using try and except so that your program handles non-numeric inputs gracefully.
- For example, Enter Hours: 20, Enter Rate: nine, Error, please enter numeric input
- Enter Hours: forty, Error, please enter numeric input
What have you learnt today?
- Tell another friend what you found hard and why
- What three new skills have you learnt
- Describe two programs where you might use Try and Except