FLOW CONTROL, PYTHON

Monica
3 min readJul 14, 2021

--

Flow control statements can decide which python instructions to execute under certain conditions.

BOOLEAN VALUES

  • Has 2 values: True and False.
  • They always start with a capital T or F.
  • Can be stored in variables.
Example

COMPARISON OPERATORS

  • Compare two values and evaluate to a single Boolean value
    == Equal to
    != Not equal to
    < Less than
    > Greater than
    <= Less than or equal to
    >= Greater than or equal to
Comparison operators

BOOLEAN OPERATORS

  • Include and, or and not
  • used to compare boolean values
The and Operator’s Truth Table
The or Operator’s Truth Table

Examples

FLOW CONTROL STATEMENTS

if Statements

  • Will execute if the statement’s condition is True, does not execute if the condition is false.
  • Consists of the if keyword, a condition, a colon and the if clause
Example of if statement

else Statements

  • An if statement can be followed by an else statement.
  • Is executed only when the if statement’s condition is false.
  • Consists of the else keyword, a colon and the else clause.
Example of if … else statement

while Loop Statements

  • the code in a while clause is executed as long as the while statement’s condition is true
  • Consists of the while keyword, a condition, a colon and the while clause
Example of while loop

The program sets the name variable to an empty string.

The code here asks the user to type their name, which is assigned to the name variable.

If the value in name is not equal to the string ‘Monica’ , then
the condition is True , and the execution enters the while clause again.

OUTPUT

break Statements

  • With the break statement we can stop the loop even if the condition is true.

continue Statements

  • used inside loops, like break statements.
  • When the program execution reaches a continue statement, it jumps to the start of the loop and re-evaluates the loop’s condition

Example

the output is as follows:

for loops

  • Is used to execute a block of code only for a certain number of times.
  • A for statement consists of the for keyword, a variable name, the in keyword, a call to the range() method, a colon and the for clause.

Example 1

The code above outputs numbers from 0 to 10, excluding 10, incrementing by 1.

Example 2

The code above outputs numbers from 2 to 8 excluding 8, incrementing by 1.

Example 3

The code above outputs numbers from 2 to 20 excluding 20, incrementing by 4.

--

--

No responses yet