else and finally
Python · Unit 9: Errors and exceptions
- Full plan
- Python
- 10 exercises
After the except blocks you can add an else: it runs only if the try didn't crash.
That's where what depends on everything going well goes, and the try keeps just the line that might fail.
try:
n = int("8")
except ValueError:
print("Not a number")
else:
print("Double:", n * 2)Prints
Double: 16
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
The person types 4. Complete it so it prints the square only if they typed a number.
4. Predict the output
What does this code print?
5. Multiple choice
If the
tryhas no error at all, which blocks run?6. Complete the code
Complete it to count every attempt, good or bad.
7. Find the bug
This program should say you can't divide by 0 and then say Done. Which line has the bug?
8. Find the bug
The person types x. The program should always say thank you, error or not. Which line has the bug?
9. Put the lines in order
The person types 6. Put the program in order. It converts, warns if it isn't a number, prints double if it is, and always says thank you at the end.
10. Predict the output
Three values get checked. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.