Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function fails to exit
#1
very basic recursion function expected to print the value of sum upto the entered number from 1, but prints the out put several times, instead of only ones. however if I add exit() after print, it works. Please help what is wrong in this code, as I dont want to use exit(). kindly help

def recsum (entnf,sumf):
    while entnf>0:
        sumf=sumf+entnf
        entnf-=1
        recsum(entnf,sumf)
    print("Condition failed, coming out of the loop")
    print("Sum is: ", sumf)
    #exit()
print("ENter the number for which you want to calculate sum upto 0: ")
numbr = int(input())
print("Entered # is: ",numbr)
sum = 0
recsum(numbr,sum)
The output is:

Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Condition failed, coming out of the loop
Sum is: 6
Reply


Messages In This Thread
function fails to exit - by harig3 - Aug-16-2020, 07:47 PM
RE: function fails to exit - by BitPythoner - Aug-16-2020, 08:21 PM
RE: function fails to exit - by harig3 - Aug-17-2020, 05:48 PM
RE: function fails to exit - by deanhystad - Aug-16-2020, 08:51 PM
RE: function fails to exit - by deanhystad - Aug-17-2020, 06:35 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python difference between sys.exit and exit() mg24 1 1,947 Nov-12-2022, 01:37 PM
Last Post: deanhystad
  Exit function from nested function based on user input Turtle 5 3,047 Oct-10-2021, 12:55 AM
Last Post: Turtle
  Exit Function - loop Tetsuo30 2 2,124 Sep-17-2020, 09:58 AM
Last Post: Tetsuo30

Forum Jump:

User Panel Messages

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