You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的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):

  1. The function starts, checks 5 != 1 (true), so it enters the loop.
  2. The first line inside the loop calls collatz(5) again—this creates a new instance of the collatz function running with the same number.
  3. That new function instance also enters the loop and calls collatz(5) again… and this repeats forever.
  4. The code below the recursive call (the if/elif checks) 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 collatz function only does one single step of the sequence: it takes a number, calculates its next value, prints it, and returns it.
  • The while loop lives outside the function, in the main code. It keeps calling collatz with the updated number until it hits 1.
  • It also adds a try/except block 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 the number variable directly.
  • The loop now runs step-by-step, updating the number each time, until it reaches 1.
  • Added the try/except block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 06:39:47