473,809 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recursive function stuck in a loop

90 New Member
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n<0:
  3.         print 'error'
  4.     if n==0:
  5.         return 1
  6.     else:
  7.         return n * fact(n-1)
  8.  
  9. # I tried
  10. >>fact(-2)
  11. error
  12. error
  13. error
  14. error
  15. error
  16. error
  17. ....
  18.  
I would like to know why did the error occur and how to fix it?
Oct 29 '07 #1
4 1229
bartonc
6,596 Recognized Expert Expert
That's because, the way it is written, both if statements are executed. This slight mod will fix it:
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n<0:
  3.         print 'error'
  4.     elif n==0: # need elif so the rest are not evaluated if n < 0
  5.         return 1
  6.     else:
  7.         return n * fact(n-1)
Oct 29 '07 #2
bartonc
6,596 Recognized Expert Expert
That's because, the way it is written, both if statements are executed. This slight mod will fix it:
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n<0:
  3.         print 'error'
  4.     elif n==0: # need elif so the rest are not evaluated if n < 0
  5.         return 1
  6.     else:
  7.         return n * fact(n-1)
It would, however, be much more readable like this:
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n > 0:
  3.         return n * fact(n - 1)
  4.     elif n == 0: # take care of exceptions after the business
  5.         return 1
  6.     else:
  7.         print 'error'
Oct 29 '07 #3
bvdet
2,851 Recognized Expert Moderator Specialist
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n<0:
  3.         print 'error'
  4.     if n==0:
  5.         return 1
  6.     else:
  7.         return n * fact(n-1)
  8.  
  9. # I tried
  10. >>fact(-2)
  11. error
  12. error
  13. error
  14. error
  15. error
  16. error
  17. ....
  18.  
I would like to know why did the error occur and how to fix it?
Your code can also be modified to work like this:
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n < 0:
  3.         print 'error'
  4.         return None
  5.  
  6.     if n == 0:
  7.         return 1
  8.     return n * fact(n-1)
When Python encounters a return statement, it immediately returns control to the calling script. Note that the else statement is not required for the same reason.
Oct 29 '07 #4
bartonc
6,596 Recognized Expert Expert
Your code can also be modified to work like this:
Expand|Select|Wrap|Line Numbers
  1. def fact(n):
  2.     if n < 0:
  3.         print 'error'
  4.         return None
  5.  
  6.     if n == 0:
  7.         return 1
  8.     return n * fact(n-1)
When Python encounters a return statement, it immediately returns control to the calling script. Note that the else statement is not required for the same reason.
Great point, BV. And just to add to the mix, I'll point that:
Expand|Select|Wrap|Line Numbers
  1. def somefunc(someargs):
  2.     if someargs == blablabla:
  3.         return None
  4. # is equivalent todef somefunc(someargs):
  5.     if someargs == blablabla:
  6.         return  # functions and methods with no return value automatically return None
Oct 29 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

10
5686
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. Not being a computer scientist, I find recursive functions to be frightening and unnatural. I'd appreciate if anyone can tell me the pythonic idiom to accomplish this. Thanks for your help,
4
1376
by: Gregory Piñero | last post by:
Hi, Would anyone be able to tell me why my function below is getting stuck in infinite recusion? Maybe I'm just tired and missing something obvious? def replace_within_node(node,oldnode,newnode): if node is oldnode: return newnode else:
41
3393
by: Harry | last post by:
Hi all, 1)I need your help to solve a problem. I have a function whose prototype is int reclen(char *) This function has to find the length of the string passed to it.But the conditions are that no local variable or global variable should be used.I have to use recursive functions.
10
2573
by: AsheeG87 | last post by:
Hello Everyone! I have a linked list and am trying to include a recursive search. However, I am having trouble understanding how I would go about that. I don't quite understand a recursive search....would any of you be so kind to explain it to me...maybe include some examples. I would GREATLY appreciate it!!!
1
1432
by: J. Frank Parnell | last post by:
arrrrrg: Condo for rent has 3 price tiers (for different times of the year): value regular premium For every 7 nites they stay, they get 1 free, and that free one should be the cheapest night (1 value nite, 6 premium nites, they should get the value nite free)
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10643
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10391
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4333
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3862
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.