Class 4 Lab 2 ‐ Error Handling - Justin-Boyd/Python-Class GitHub Wiki

Step 1

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

Step 2

  • Declare the variable product and assign it an integer value of 1.
product = 1

Step 3

  • Create a for loop that performs four iterations.
for i in range(4):

Step 4

  • In the for loop, ask the user to provide a number, cast that number to an integer, and assign it to a new variable. Multiply each input by the product variable and assign the result to the same variable.
    num = int(input("Enter a number: "))
    product *= num

Step 5

  • Place the user input and mathematical operation in a try block. Make sure that you use indentation when placing it in the try block.
    try:
        num = int(input("Enter a number: "))
        product *= num

Step 6

  • Create an except block that prints a message to the console when user input is a non-integer.
    except :
        print("The input is not a valid number")

Step 7

  • Run the code from Step 6, input an integer, then input a non-integer, and observe the results.
  • The last input, as shown below, is a non-integer. The error is caught by the except statement in the try block and triggers the invalidation message to appear.

Step 8

  • Add a line to print the four numbers' product and cast the integer to a string.
print("The product of the 4 numbers is: "+ str(product))

Step 9

  • Rerun the code, but this time input integers only. Observe the results.

Final Code

"""Lab Objective: Practice handling errors that may occur in the code."""

product = 1
for i in range(4):
    try:
        num = int(input("Enter a number: "))
        product *= num
    except:
        print("The input is not a valid number")
print("The product of the 4 numbers is: " + str(product))

print(product)

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