What is the difference between if, elif and else in Python?
An if tests its condition and runs its block when the condition is true. An elif is tested only when every test above it in the same chain was false, and an else runs when all of them were false. So in one chain of if, elif and else, at most one block runs, the first whose condition is true. Two separate if statements, on the other hand, are each tested, and both can run.
Why is my condition x == 1 or 2 always true in Python?
Because Python compares first and then applies or to what is on each side: it reads the comparison of x with 1, or the number 2 alone. In a condition, any number other than zero counts as true, so the right side is always true and the block always runs. Write a full comparison on each side: x equal to 1, or x equal to 2. In Java the same line does not compile.
What are De Morgan's laws in programming?
They say how to negate a condition made of two parts. The opposite of a and b is not a, or not b: it is enough that one part is false. The opposite of a or b is not a, and not b: both parts must be false. Negating each part is not enough: the and must become an or, and the or an and. A truth table of four rows checks it.
Should I use less than or less than or equal to in an if statement?
Read the rule for the boundary value. Words such as up to and including, at most, at least or from mean the boundary is included: less than or equal to, or greater than or equal to. Words such as under, below or above mean it is excluded: strictly less than, or strictly greater than. Then test the program on the boundary itself, just below it and just above it.
Why does my Python program print several messages instead of one?
Because it uses separate if statements, and each one whose condition is true runs its block. When the cases overlap, such as a level of at most 5 that is also at most 20, several messages appear. To show one message, write a single chain of if, elif and else, with the most restrictive condition first: Python then stops at the first true condition.