Skip to the content

else and finally

Python · Unit 9: Errors and exceptions

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. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    The person types 4. Complete it so it prints the square only if they typed a number.

  4. 4. Predict the output

    What does this code print?

  5. 5. Multiple choice

    If the try has no error at all, which blocks run?

  6. 6. Complete the code

    Complete it to count every attempt, good or bad.

  7. 7. Find the bug

    This program should say you can't divide by 0 and then say Done. Which line has the bug?

  8. 8. Find the bug

    The person types x. The program should always say thank you, error or not. Which line has the bug?

  9. 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. 10. Predict the output

    Three values get checked. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →