Python Forum
How returns behave in a function with multiple returns?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How returns behave in a function with multiple returns?
#1
The code below returns 8. Why does not it return 2 instead? I do not understand how return behaves in the code below. what is the rule? Thanks for your help.. khasbay
def f(x):
    if x==0:
        return 2
    else:
        return x+f(x-1)

print(f(3))
deanhystad write May-19-2024, 01:54 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Follow the function calls to compute the value for f(3).

You call your function f(3).

In the function, 3 != 0, so the function returns 3 + f(2).

We call f(2). 2 != 0, so the function returns 2 + f(1).

We call f(1). 1 != 0, so the function returns 1 + f(0).

We call f(0). 0 == 0, so the function returns 2

We have these values for f()
f(0) = 2
f(1) = 1 + f(0) = 3
f(2) = 2 + f(1) = 5
f(3) = 3 + f(2) = 8

Recursion is when a function calls itself. the value of f(3) is slightly confusing not because it has two return statements, but because it uses recursion. This is the same function with one return statement.
def f(x):
    return 2 if x == 0 else x + f(x-1)

print(f(3))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python re.finditer returns a null string when expecting a None result arbiel 8 802 Jan-11-2026, 02:57 AM
Last Post: Pedroski55
  Endgame engine with non-standard figures doesn't behave correctly max248 0 872 Dec-07-2024, 12:44 PM
Last Post: max248
  np.percentile returns wrong value? AceTylercholine 2 2,664 Jul-13-2023, 06:59 PM
Last Post: Skaperen
  function returns dataframe as list harum 2 4,075 Aug-13-2022, 08:27 PM
Last Post: rob101
  extratreesclassifier returns all zeroes instead of feature importances Led_Zeppelin 0 1,737 Jul-20-2022, 08:15 PM
Last Post: Led_Zeppelin
  function accepts infinite parameters and returns a graph with those values edencthompson 0 1,770 Jun-10-2022, 03:42 PM
Last Post: edencthompson
Sad Iterate randint() multiple times when calling a function Jake123 2 4,250 Feb-15-2022, 10:56 PM
Last Post: deanhystad
  Function - Return multiple values tester_V 10 7,931 Jun-02-2021, 05:34 AM
Last Post: tester_V
  function that returns a list of dictionaries nostradamus64 2 3,164 May-06-2021, 09:58 PM
Last Post: nostradamus64
  '|' character within Regex returns a tuple? pprod 10 11,084 Feb-19-2021, 05:29 PM
Last Post: eddywinch82

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020