Python中While循环内函数的else块未执行问题求助
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
elsestatement wasn't at the same indentation level as theif(e.g., indented one level deeper), Python would treat it as part of theifblock instead of a separate branch. This could make it never trigger, even if you didn't get an error message. Double-check thatelselines up perfectly withif. - 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

