Uncategorized

operator precedence – Why is the environment diagram in the following Python code inconsistent with its execution order?


The evaluation order will be as follows:

  • add_one(9) is executed, as it’s the innermost nested expression
  • the return value of 10 is calculated and returned from function
  • square function is invoked with 10 as its parameter
  • the return value of 100 is calculated and returned from function
  • as this is the outermost function call, the expression results in 100

The big difference to your list is the order in which the functions are executed. The innermost is usually* executed first. You can think of the brackets (parentheses) that we use to invoke functions as another layer of operator priority. Things within brackets are run before things outside brackets.

While GPT is right about functions being invoked before operators, here the question is more about which function gets invoked first. Once a function is invoked, it doesn’t matter what it or other functions contain – the whole function is being run using the same rules, but applied to the function body only. E.g. functions called within an expression in the function would be called before operators in the same expression.

* = the only exception being latent functions like lambdas, in which case the parameter itself is of type function. You will get to this a bit later in your studies.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *