Computer Science
Write a program with non-void version of above function and then write flow of execution for both the programs.
Python Functions
2 Likes
Answer
The non-void version of above code is as shown below :
1. def print_number(number):
2. next_number = number + 1
3. return next_number
4. print(print_number(4))
5. print(print_number(6))
6. print(print_number(8))
7. print(print_number(2 + 1))
8. print(print_number(4 - 3 * 2))
9. print(print_number(-3 - 2))
Output
5
7
9
4
-1
-4
Explanation
def print_number(number)
— This line defines a function namedprint_number
that takes one argumentnumber
.next_number = number + 1
— Inside theprint_number
function, this line calculates the next number after the input number by adding 1 to it and assigns the result to the variablenext_number
.return next_number
— Inside theprint_number
function, this line returnsnext_number
.Then the
print_number
function is called multiple times with 4, 6, 8, 3 ,((4 - 3 * 2) = -2), ((-3-2) = -5) as arguments.
The flow of execution for the above program with non-void version is as follows :
1 → 4 → 1 → 2 → 3 → 4 → 5 → 1 → 2 → 3 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 1 → 2 → 3 → 7 → 8 → 1 → 2 → 3 → 8 → 9 → 1 → 2 → 3 → 9
Line 1 is executed and determined that it is a function header, so entire function-body (i.e., line 2 and 3) is ignored. Then line 4 is executed and it has function call, so control jumps to the function header (line 1) and then to first line of function-body, i.e., line 2, function returns after line 3 to line containing function call statement i.e., line 4. The next lines 5, 6, 7, 8, 9 have function calls so they repeat the above steps.
The flow of execution for the void version program is as follows :
1 → 4 → 1 → 2 → 3 → 4 → 5 → 1 → 2 → 3 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 1 → 2 → 3 → 7 → 8 → 1 → 2 → 3 → 8 → 9 → 1 → 2 → 3 → 9
Line 1 is executed and determined that it is a function header, so entire function-body (i.e., line 2 and 3) is ignored. Then line 4 is executed and it has function call, so control jumps to the function header (line 1) and then to first line of function-body, i.e., line 2, function returns after line 3 to line containing function call statement i.e., line 4. The next lines 5, 6, 7, 8, 9 have function calls so they repeat the above steps.
Answered By
3 Likes
Related Questions
In the following code, which variables are in the same scope ?
def func1(): a = 1 b = 2 def func2(): c = 3 d = 4 e = 5
Write a program with a function that takes an integer and prints the number that follows after it. Call the function with these arguments :
4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2
What is the output of following code fragments ?
def increment(n): n.append([4]) return n L = [1, 2, 3] M = increment(L) print(L, M)
What is the output of following code fragments ?
def increment(n): n.append([49]) return n[0], n[1], n[2], n[3] L = [23, 35, 47] m1, m2, m3, m4 = increment(L) print(L) print(m1, m2, m3, m4) print(L[3] == m4)