Bertelsmann Tech Scholarship Challenge, Python, Udacity

Python Control Flow: Conditional Statements

Conditional Statements

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.

if Statement

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.

else Statements

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.

elif Statement

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.

Bertelsmann Tech Scholarship Challenge Course – Data Track Nanodegree Program. Lesson 23: Videos 1 – 6

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s