Why python programmers tend to write "return False" in conditionals instead of writing "return True"?

I’m a beginner in Python and I find myself confused about some coding habits. One of them is as the title suggests. Could anyone offer a kind answer?

it would be better to show some code snippets


That’s not a habit. When we do it, then because that’s the right thing to do.


Got it. Thanks!

But I’m still curious about examples that gave you the impression :-). There might actually be a habit in the bigger picture that leads to more often returning False.

I’m recently taking the course CS50’s Introduction to Programming with Python and I encounter a problem that is a little difficult for me. I searched for answer and found many of them uses “return False”, like this:

Code before return True within function is_valid just checks those invalid situations(then return False), in other words, it’s the logic decides return False, not the coding habit


Please post code as text, not images.

That’s what I suspected, that’s indeed due to a habit in the bigger picture that leads to more often returning False. Namely the habit of thinking positive :-). In this case, writing a function is_valid. Instead of is_invalid. Naturally, that leads to return False as soon as you find any of multiple possible reasons why it’s not valid. And naturally only one return True at the very end, when you checked everything.


And the reason to write an is_valid instead of an is_invalid function is that that’s typically what you want and it reads better. You use it in code like if is_valid(s): or if not is_valid(s):. Avoids double negation if not is_invalid(s). And double negation never ain’t not hard to not misunderstand for nobody, don’t you not disagree?


It’s distributed short-circuiting. Separate if statements like

if x:
    return False
if y:
    return False

return <something>

could be written as

return not x and not y and <something>

but sometimes the logic is clearer (and there’s less nesting) to use multiple separate if statements that can return early.