Class 4 Lab 1 ‐ Try & Except Practice - Justin-Boyd/Python-Class GitHub Wiki

Step 1

  • Open PyCharm, click File at the top left, and select New Project.

Step 2

  • Create a new Python file in PyCharm by right-clicking the project you created and selecting New > Python File.

Step 3

num1 = int(input("Please enter a number: "))
  • Request a number from the user and assign it to a variable

Step 4

num2 = 0
  • Create a new variable with the value 0.

Step 5

try:
    num1 = int(input("Please enter a number: "))
    num2 = 0
    div = num1/num2
    print(div)
  • Divide the first variable by the second variable and print the result.
  • As these operations need to be handled appropriately, begin the code with a try error-handling block.

Step 6

try:
    num1 = int(input("Please enter a number: "))
    num2 = 0
    div = num1/num2
    print(div)
except ZeroDivisionError:
    print("Can’t calculate it")
  • Write an except block to catch the ZeroDivisionError exception.

Step 7

except ValueError:
    print("Something went wrong!")
  • Create another exception using the built-in TypeError. Run the code and insert a word instead of a number. Note how the ZeroDivisionError exception is not executed. Why?

Final Code

"""Lab Objective: Use try and except to handle code errors."""

try:
    num1 = int(input("Please enter a number: "))
    num2 = 0
    div = num1/num2
    print(div)

except ZeroDivisionError:
    print("Cant calculate it")

except ValueError:
    print("Something went wrong!")

# prevents program from closing upon execution
input("\nPress 'Enter' to exit the program")