Python Control Flow
Python Control Flow
Comparison Operators
Operator Meaning
== Equal to
!= Not equal to
These operators evaluate to True or False depending on the values you give them.
Examples:
>>> 42 == 42
True
>>> 40 == 42
False
>>> 42 == 42.0
True
>>> 42 == '42'
False
Boolean Operators
There are three Boolean operators: and , or , and not .
Expression Evaluates to
Expression Evaluates to
Expression Evaluates to
Mixing Operators
You can mix boolean and comparison operators:
>>> (1 == 2) or (2 == 2)
True
Also, you can mix use multiple Boolean operators in an expression, along with the
comparison operators:
if Statements
The if statement evaluates an expression, and if that expression is True , it then
executes the following indented code:
The else statement executes only if the evaluation of the if and all the elif
expressions are False :
Only after the if statement expression is False , the elif statement is evaluated
and executed:
Example:
>>> age = 15
>>> age = 15
Switch-Case Statement
The Switch-Case statements, or Structural Pattern Matching, was firstly introduced in
2020 via PEP 622, and then officially released with Python 3.10 in September 2022.
Default value
The underscore symbol ( _ ) is used to define a default case:
>>> spam = 0
>>> while spam < 5:
... print('Hello, world.')
... spam = spam + 1
...
# Hello, world.
# Hello, world.
# Hello, world.
# Hello, world.
# Hello, world.
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 loop
The for loop iterates over a list , tuple , dictionary , set or string :
You can even use a negative number for the step argument to make the for loop count
down instead of up.