Home > database >  Q20. What is the order of execution of the lines of the following program?
Q20. What is the order of execution of the lines of the following program?

Time:12-14

Q20. What is the order of execution of the lines of the following program?

def f1(x): #1
 temp = x   1 #2
 return temp #3
def f2(y): #4
 t = y -1 #5
 v = f1(t) #6
 return v #7
 #8
print(f2(5)) #9

Answers (choose one):
a) 1-2-3-4-5-6-7-9
b) 1-4-9-4-5-6-1-2-3-6-7-9
c) 1-2-3-4-5-6-7-9-4-5-6-7
d) 1-4-9-4-5-6-1-2-3-6
e) None of the above
Here they say that the answer is e (none of the above) but im not sure what would be the correct order that python would execute these lines. how would i know for each different function ?

CodePudding user response:

In your code there are 2 functions these 2 functions run when it will call so first the line 9 execute which calls f2 function it will run till #6 line and than the f2 function calling another function f1 now f1 function will start to execute till end than comes to the f2 intialize v and then execute 7th line which is returning and than finally it will print the statement..!

CodePudding user response:

You can resolve the key points here by defining a function with a deliberately introduced error. For example,

def f(x):
    return squirt

Assuming squirt is not defined in the global scope (outside the function definition), calling this function would result in the error

NameError: name 'squirt' is not defined

However, notice that it is perfectly acceptable to define the function, with def f(x). This means that the lines of the function are not executed in any way when the line defining the function (def f(x)) is executed.

Only once the function is called are the lines of the function executed (without re-executing the definition).

Another point, it seems somewhat ambiguous to ask when the line is executed, when the line contains a call to another function (e.g. line #6). However, the assignment contained in line#6 cannot actually take place until the value to the right of the assignment expression is evaluated. So you may say that line#6 - an assignment - is executed after lines #2 and #3 are executed. Likewise, line#9 cannot be executed until the call to f2 is resolved.

Taking these points together, and combining with the fact that Python code is read from top to bottom, the answer would be

1-4-5-2-3-6-7-9
  • Related