Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function fails to exit
#4
(Aug-16-2020, 08:21 PM)BitPythoner Wrote: Is the point of the program to add the entered number to it's positive counterpart?

thank you sir for the response. objective of the program is to print the sum of all numbers starting from 1 till that number ( actually in opposite direction)

Lets say , number entered = n

so I wish to print sum = n + ( n-1) + (n-2) + (n-3)...until it reaches 0

Example:

if n = 5
then I would like the sum to be = 5 + 4 + 3 + 2 + 1 = 15

I am able to achieve it if I use the exit() , just as in the code below:


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)
output is :

Output:
ENter the number for which you want to calculate sum upto 0: 5 Entered # is: 5 Condition failed, coming out of the loop Sum is: 15
however what I fail to understand is , in the absence of the exit(), even after the while condition fails, the control is going back to recsum(entnf,sumf) which is just above the two print statements and its doing some a few times before it exits.
I am still learning, so any help is highly appreciated.
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