Conditional Statements are used to break the linear code. We don’t always want to have our code follow a straight lines we want to branch off based on a a condition. If the condition is true we want to go one way and if it’s false it goes another way.
The most common type of flow control statement is the if statement. An if statement’s clause (that is the block following the if statement) will execute if the statement’s condition is True. The clause is skipped if the condition is False.
Example of if statement
if age >= 21: print("give beer")
Notice that we use:
- the if word
- followed by the condition that is either True or False.
- A colon
- Starting on the next line, an indented block of code (this is the clause_
All flow control statements end with a colon and are followed by a new block of code (the clause). The if statement’s clause is the block with the print statement.
An if clause can be followed by an else statement. The else clause is only executed when the if statement’s condition is False.
Example of an else statement
if age >= 21: print("give beer") else : print("You need to leave the bar")
An else statement has
- The else keyword
- A colon
- Starting on the next line an indented block of code called the else clause.
While only one of the if or else clauses will execute, you may have a case where you want one of many possible clauses to execute. The elif statement is an else if statement that always follows an if or another elif statement. It has another condition that is checked only if any or the previous conditions were False.
Example of elif statement
if age >= 21: print("give beer") elif age >= 20: print("You only have to wait one more year") else: print("You need to leave the bar")
Notice that the elif statement consists of the following:
- The elif keyword
- A condition that executes to either true or false
- A colon
- Starting on the next line, an indented block of code called the elif clause.
The elif clause executes if the person is not 21 or older and if they are older than 20. However if the person is under 20 the else block will execute.
When there is a chain of elif statements only one or none of the clauses will be executed.