为何我的Collatz序列Python代码出现‘maximum recursion depth exceeded’错误?两类代码差异解析及修改方案咨询
Hey Chris, let’s break down exactly why your Collatz sequence code is throwing that "maximum recursion depth exceeded" error, how it differs from the working version, and how you can fix your code (yes, you can keep the while loop inside the function if you want—your initial guess about the loop location was off!).
1. Why Your Code Crashes With a Recursion Error
Let’s look at your code again and spot the critical issue:
def collatz(number): while number != 1: number=collatz(number) # 🚨 This is the problem! if number % 2 == 0: print ((int(number))//(2),sep='') return ((int(number))//(2)) elif number % 2 == 1: print (3*int(number)+1,sep='') return (3*int(number)+1)
Here’s what happens when you call collatz(5) (for example):
- The function starts, checks
5 != 1(true), so it enters the loop. - The first line inside the loop calls
collatz(5)again—this creates a new instance of thecollatzfunction running with the same number. - That new function instance also enters the loop and calls
collatz(5)again… and this repeats forever. - The code below the recursive call (the
if/elifchecks) never gets executed—you’re stuck in an infinite loop of calling the function over and over, which hits Python’s built-in limit on how many times a function can call itself recursively. That’s the "maximum recursion depth exceeded" error.
2. How the Working Code Avoids This
The correct code splits the logic into two clear parts, which eliminates the recursive mess:
def collatz(number): if number % 2 ==0: #even number print ((int(number))//(2),sep='') return ((int(number))//(2)) elif number % 2 ==1:#odd number print (3*int(number)+1,sep='') return (3*int(number)+1) try: print('Enter number:') number=int(input('>')) #user input while number !=1: #performs loop until number becomes 1 number=collatz(number) #number gets passed to collatz function until it arrives at 1 except ValueError: print('Please enter an integer')#error message if non-integer is input
- The
collatzfunction only does one single step of the sequence: it takes a number, calculates its next value, prints it, and returns it. - The
whileloop lives outside the function, in the main code. It keeps callingcollatzwith the updated number until it hits 1. - It also adds a
try/exceptblock to handle cases where the user enters a non-integer (which your code was missing).
No recursion here—just a loop repeatedly calling a simple function, so there’s no risk of hitting recursion limits.
3. Fixing Your Code (With the Loop Inside the Function)
You don’t have to follow the correct code’s structure! You can keep the while loop inside the collatz function—you just need to remove the recursive call and update the number directly in the loop. Here’s the fixed version:
def collatz(number): while number != 1: if number % 2 == 0: number = number // 2 print(number, sep='') elif number % 2 == 1: number = 3 * number + 1 print(number, sep='') # Loop exits automatically when number becomes 1 print('Enter number:') try: number = int(input('>')) collatz(number) except ValueError: print('Please enter an integer')
What changed:
- Removed the recursive
number=collatz(number)line—instead, we calculate the next value and update thenumbervariable directly. - The loop now runs step-by-step, updating the number each time, until it reaches 1.
- Added the
try/exceptblock to handle bad input, making it as robust as the correct code.
This version works perfectly, and the while loop is still inside the function—proof that your initial guess about the loop location wasn’t the issue. The problem was just the accidental infinite recursion.
Key Takeaways
- Recursion needs a clear stop condition: If you ever use recursion, make sure there’s a point where the function stops calling itself. Your code didn’t have that.
- Loop vs. Recursion: The correct code uses a loop to repeat steps, while your original code incorrectly mixed loops and recursion. Both approaches work, but you have to pick one and stick to it.
- You can structure code your way: There’s no rule that says the loop has to be outside the function—you just need to make sure the logic flows correctly.
内容的提问来源于stack exchange,提问作者Chris

