Python Python Basics Functions and Looping Exception Flow

Christopher Hill
Christopher Hill
1,030 Points

Can someone breakdown the sequence to this code I'm confused about the order.

print("A") try: result = "test" + 5 print("B") except ValueError: print("C") except TypeError: print("D") else: print("E") print("F")

1 Answer

Alright let's check the logic, and go through each step very slowly. First the complete code below,

print("A")
try:
    result = "test" + 5
    print("B")
except ValueError:
    print("C")
except TypeError:
    print("D")
else:
    print("E")
print("F")

Now breaking it down; First step;

print("A")

The first step is "print("A")", pretty simple no need to overthink, so let's run it,

print("A")

#Output is "A". YES WE GOT "A"

Now step 2 is the try block, things can get complicated but let's focus.

try:
    result = "test" + 5
    print("B")

OH, this seems to be wrong because the "test" is a string type and the (5) is an int type, notice that the "test" word has the quotation marks("") at the beginning and end of it, so it makes it a string type and since the number (5) have no quotation marks and is a number, so it's an integer or int type, WE CANNOT add two different types, so this cannot be valid, and print("B") cannot execute BECAUSE the statement;

result = "test" + 5

will give out a TYPE ERROR. so print("B") is not valid, hence no output. But if we look at the next step there is an exception, meaning there is some error do this;

try:
    result = "test" + 5         # This gives us a Type error because "test" is a string type and 5 is an int type
    print("B")
except ValueError:   # print("C") will execute if there is a Value Error, and in this case we have a type error not ValueError                                  
    print("C")
except TypeError:     # Now there is the error that is our type of error the TYPE ERROR, so this line of code will execute.
    print("D")

Since we have a type error so print("D") will execute.

NOW, we have two outputs "A" and "D"

moving on to the next step;

else:
    print("E")  # This line of code will only execute IF nothing is executed in the try block and no errors were there.

Since we had a Type error, the Else line of code won't execute, So print("E") won't execute. Now for our last step;

print("F") # This code will execute directly because it has no try block, no conditions or anything.
# output gives us "F"

print("F") will give us "F".

So now we have all the answers

"A" "D" "F"

Christopher Hill
Christopher Hill
1,030 Points

Wow, thank you so much this helps me out tremendously. It all makes since now.