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

Python中While循环内函数的else块未执行问题求助

Troubleshooting the Else Block Issue in Your Loop

Hey there! Let's dig into why your else block isn't executing when you wrap jump_slide() in a while True loop.

First, let's start with the most common pitfall for Python beginners: indentation. Python relies entirely on indentation to define code blocks, so a misaligned else can cause unexpected behavior (or silent failures). Let's look at your original code fixed with proper structure:

Correctly Indented Working Code

def jump_slide():
    num = int(input('Enter a number :'))
    if num > 20:
        print('slide under')
    else:
        print('jump over')

# Wrap the function in a loop
while True:
    jump_slide()

Why Might the Else Block Fail?

  • Misaligned Indentation: If your else statement wasn't at the same indentation level as the if (e.g., indented one level deeper), Python would treat it as part of the if block instead of a separate branch. This could make it never trigger, even if you didn't get an error message. Double-check that else lines up perfectly with if.
  • Accidental Input Values: It's easy to accidentally type numbers greater than 20 when testing the loop without noticing. Even though the standalone function works, confirm you're actually entering values ≤20 when testing the loop version.
  • Hidden Conversion Issues: While you said the standalone function works, if you ever input non-numeric values (like spaces or letters) you'd get a ValueError—but since you didn't mention errors, this is less likely.

Quick Debug Tip

Add a debug print statement right after converting the input to verify what value your function is using:

def jump_slide():
    num = int(input('Enter a number :'))
    print(f"Debug: Number received is {num}")  # Add this line
    if num > 20:
        print('slide under')
    else:
        print('jump over')

This will show you exactly what num is each time, so you can confirm if the condition is being evaluated correctly. If the debug print shows a number ≤20 but the else block still doesn't run, you definitely have an indentation issue to fix.

内容的提问来源于stack exchange,提问作者Richardson Harrison

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:14:48