Python:for循环内满足条件时无法终止函数的解决方法
I see exactly what's going on here—when your code hits the else clause and sets number to [-1,-1], it doesn't stop the loops or exit the function right away. The loops keep running until they finish, which is why your previous attempts to use return weren't working (you probably placed it outside the scope where the invalid condition is triggered).
Here's the fixed version of your function that terminates immediately when the invalid state is hit:
def character(char_type, word, number): for i in range(len(word)): for e in range(len(char_type)): if word[i] == char_type[e]: if char_type == vowels: number[0] += 1 elif char_type == consonants: number[1] += 1 elif char_type == valid_symbols: # No change to number needed pass else: # Modify the existing list instead of reassigning a new one number[0] = -1 number[1] = -1 # Immediately exit the function to stop all loop execution return
Key Fixes Explained:
- Immediate Return: Right after updating
numberto the invalid state, we callreturn. This stops all nested loops cold and exits the function instantly—this is the missing piece you needed. - Proper List Modification: Your original code did
number = [-1,-1], which creates a new local list instead of modifying the list you passed into the function. By settingnumber[0]andnumber[1]directly, the changes will be reflected in the original list outside the function. - Cleaner Valid Symbols Handling: Replaced the redundant
number = numberline withpassfor better readability.
If you want to optimize further, you could avoid nested loops by checking if word[i] is in char_type (using if word[i] in char_type: instead of looping through char_type), but the above changes directly solve your termination problem.
内容的提问来源于stack exchange,提问作者williamash2

