KnowledgeBoat Logo

Computer Science

Write a program with non-void version of above function and then write flow of execution for both the programs.

Python Functions

1 Like

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
  1. def print_number(number) — This line defines a function named print_number that takes one argument number.

  2. next_number = number + 1 — Inside the print_number function, this line calculates the next number after the input number by adding 1 to it and assigns the result to the variable next_number.

  3. return next_number — Inside the print_number function, this line returns next_number.

  4. 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

2 Likes


Related Questions