Read It
Flow Control
Comparison Operators
Operator | Meaning |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater Than |
<= | Less than or Equal to |
>= | Greater than or Equal to |
These operators evaluate to True or False depending on the values you give them.
Examples:
Boolean evaluation
Never use ==
or !=
operator to evaluate boolean operation. Use the is
or is not
operators,
or use implicit boolean evaluation.
NO (even if they are valid Python):
YES (even if they are valid Python):
These statements are equivalent:
And these as well:
Boolean Operators
There are three Boolean operators: and, or, and not.
The and Operator's Truth Table:
Expression | Evaluates to |
---|---|
True and True | True |
True and False | False |
False and True | False |
False and False | False |
The or Operator's Truth Table:
Expression | Evaluates to |
---|---|
True or True | True |
True or False | True |
False or True | True |
False or False | False |
The not Operator's Truth Table:
Expression | Evaluates to |
---|---|
not True | False |
not False | True |
Mixing Boolean and Comparison Operators
You can also use multiple Boolean operators in an expression, along with the comparison operators:
if Statements
else Statements
elif Statements
while Loop Statements
break Statements
If the execution reaches a break statement, it immediately exits the while loop's clause:
continue Statements
When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.
for Loops and the range() Function
The range() function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.
You can even use a negative number for the step argument to make the for loop count down instead of up.
For else statement
This allows you to specify a statement to execute after the full loop has been executed. Only
useful when a break
condition can occur in the loop: