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
  np.percentile returns wrong value? AceTylercholine 2 822 Jul-13-2023, 06:59 PM
Last Post: Skaperen
  function returns dataframe as list harum 2 1,609 Aug-13-2022, 08:27 PM
Last Post: rob101
  extratreesclassifier returns all zeroes instead of feature importances Led_Zeppelin 0 943 Jul-20-2022, 08:15 PM
Last Post: Led_Zeppelin
  function accepts infinite parameters and returns a graph with those values edencthompson 0 960 Jun-10-2022, 03:42 PM
Last Post: edencthompson
Sad Iterate randint() multiple times when calling a function Jake123 2 2,204 Feb-15-2022, 10:56 PM
Last Post: deanhystad
  Function - Return multiple values tester_V 10 4,796 Jun-02-2021, 05:34 AM
Last Post: tester_V
  function that returns a list of dictionaries nostradamus64 2 1,902 May-06-2021, 09:58 PM
Last Post: nostradamus64
  '|' character within Regex returns a tuple? pprod 10 5,977 Feb-19-2021, 05:29 PM
Last Post: eddywinch82
  Recursive function returns None, when True is expected akar 0 3,504 Sep-07-2020, 07:58 PM
Last Post: akar
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,610 Aug-10-2020, 02:51 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

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