0

I learnt about using the except function to prevent your code from crashing but I want to understand it better on how python executes it.

For example, I have code that adds a pair of numbers and if the variable nums has more than two numbers it should give AssertionError.

1    def sum_pair(pair):
2        assert len(pair) == 2
3        return pair[0] + pair[1]

4    try:
5        total = sum_pair(nums)
6        print 'The total is', total
7    except AssertionError:
8        print 'Abort'

So from my view python executes Lines 1, 2, 4, 5, 7 and 8 only. Is this correct way to understand it?

Thank you

1
  • The statements inside a function aren't executed until you call the function. So line 2 won't be executed until after line 5. Commented May 16, 2016 at 21:57

2 Answers 2

2

When an exception is signalled, the call stack is searched for a try block that has an except clause that matches the type of the exception. The stack is unwound to that point, the code in the except clause is executed, and then execution continues after the try block.

So when line 2 detects that the assertion has failed, it immediately exits the sum_pair() function and executes the code starting from line 8.

Sign up to request clarification or add additional context in comments.

Comments

1

Technically, it executes Lines 4,5,1,2,7,8 in that order.

3 Comments

I'm pretty sure the OP realizes that and was just sorting the executed line numbers. Additionally, this answer would be more suitable as a comment.
@TigerhawkT3, Fair enough. When I read the question, I interpreted it as OP wanting to know if the execution order was the correct way to understand it, but your point is well taken.
IMHO, the def line is executed first, so that the identificator sum_pair is knows to the interpretor. So the order of execution is 1,4,5,2,7,8

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.