De Morgan's rule
One of the subscribers brought me a problem. Roughly, it sounds like this:
“Read standard input and count strings. Stop counting when the user enters конец or КОНЕЦ.”
The question was how to write the loop condition.
It looks trivial, but I think I can easily write a post (or two) around this question.
First, let’s try the straightforward approach with an exit condition:
n = 0
while True:
s = input()
if s == "конец" or s == "КОНЕЦ":
break
n += 1
print(n)
Here we use the break keyword, which exits the loop and skips the rest of the loop body.
So we know that we reach n += 1 only if s differs from the end-of-input marker.
Personally, I don’t like these break and continue guys — they always look like goto in disguise.
Let’s try to remove the if … break construction and move the condition into the while.
To do this, we need to invert the exit condition and write down the continuation condition instead.
Formally, the exit condition is:
s == "конец" or s == "КОНЕЦ"
So the continuation condition is:
not (s == "конец" or s == "КОНЕЦ")
And here comes De Morgan’s rule.
Let’s look at our comic strip with almost Rescue Rangers trying to find a brilliant. They know that Fat Cat hid it inside one of Nimnul’s robots — the one that is round and green. But finding such a robot in a crowded laboratory is hard.
So Gadget uses her invention and reverses the polarity. Now the diamond is inside all robots except the round and green one.
The team plays it safe and reasons like this:
if a robot is either not green or not round, we grab it.
As you can see, they find the diamond — using De Morgan’s rule.
This is important because when you write programs, you constantly switch between:
👉exit conditions
👉continuation conditions
The practical rule is simple (for basic cases):
To negate a logical expression, negate each term and swap or ↔️ and.
Let’s apply it to our example.
n = 0
s = input()
while s != "конец" and s != "КОНЕЦ":
n += 1
s = input()
Everything has its price.
Now we have to write s = input() twice.
But at least we got rid of break.
