[Type B] Working with Functions – Chapter 3 Sumita Arora

|
Table of Contents

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

Python
def next_num(num):
    next_num = num + 1
    return "Next number after " + str(num) + " is " + str(next_num)

# Call the function with the provided arguments and print the results
print(next_num(4))
print(next_num(6))
print(next_num(8))
print(next_num(2 + 1))
print(next_num(4 - 3 * 2))
print(next_num(3 - 2))

Flow of Execution for:

  • Void Version: 1 → 6 → 1 → 2 → 3 → 7 → 1 → 2 → 3 → 8 → 1 → 2 → 3 → 9 → 1 → 2 → 3 → 10 → 1 → 2 → 3 → 11 → 1 → 2 → 3
    (Control doesn’t return to function call statement as nothing is being returned by the function for void functions, they only print)
  • Non-void Version: 1 → 6 → 1 → 2 → 3 → 6 → 7 → 1 → 2 → 3 → 7 → 8 → 1 → 2 → 3 → 8 → 9 → 1 → 2 → 3 → 9 → 10 → 1 → 2 → 3 → 10 → 11 → 1 → 2 → 3 → 11

If somebody arrived at a doubt for the use of converting integer to string conversion in the function at line 3, know the reason behind this being that using this concatenates the strings “Next number after “, num, ” is “, and next_num together to form the desired output string.

Finally, when the function is called, it returns this concatenated string instead of a tuple with commas and brackets.

Otherwise, your output would look like this rather than what you expected as same from Q16.

('Next number after', 4, 'is', 5)
('Next number after', 6, 'is', 7)
('Next number after', 8, 'is', 9)
('Next number after', 3, 'is', 4)
('Next number after', -2, 'is', -1)
('Next number after', 1, 'is', 2)
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

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