Learn Python: Control Flow

Learn how to build control flow into your python code by including if, else, and elif statements as well as try and except statements. Expect to learn all you need to know about boolean variables and logical operators.

Start[missing "en.views.course_landing_page.learn-python-3.course_illustration" translation]

Key Concepts

Review core concepts you need to learn to master this subject

Relational Operators

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

Relational operators can be used to compare the relation between two values. The code above shows what those relational operators are. Most of them, such as >, <, >=, <=, are ones that are often used in math. Python also has operators that are only used in programming languages, such as == and !=. If the comparison is correct (e.g. 1 < 5), the operator will return True. If the comparison is false (e.g. 1 == 5), the operator will return False.

Equal Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python equal operator (==) is used to compare two values, variables or expressions to determine if they are the same. If they are the same, the operator returns True. If they are NOT, then it returns False. The operator takes the data type into account when making the comparison, so a string value of "2" is not considered to be equal to a numeric value of 2. If expressions are used, then they are evaluated to a value of True or False before the comparison is made by the operator.

Not Equals Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python not equals operator (!=) is used to compare two values, variables or expressions to determine if they are NOT the same. If they are NOT the same, the operator returns True. If they are the same, then it returns False. The operator takes the data type into account when making the comparison so a value of 10 would NOT be equal to the string value "10" and the operator would return True. If expressions are used, then they are evaluated to a value of True or False before the comparison is made by the operator.

Comparison Operators

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

In Python, relational operators compare two values or expressions. The most common ones are less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (>=). If the relation is sound, then the entire expression will evaluate to True. If not, the expression evaluates to False.

The Not Equals Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The not equals operator is a comparison operator that compares two values or expressions. It returns False if the values on either side are equal and True if the values on either side are not equal. As shown in the code above, the not equals operator can compare both numerical values and strings. It is formatted as (!=).

Boolean and Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python and operator performs a Boolean comparison between two Boolean values, variables, or expressions. If both sides of the operator evaluate to True then the and operator returns True. If either side (or both sides) evaluates to False, then the and operator returns False. A non-Boolean value or variable will always evaluate to True when used with the and operator as long as they are assigned to a value.

The and Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The and operator is a logical operator that combines two boolean expressions. If both boolean expressions are true, then the and operator will return True. However, even if one expression is false, the operator will return False.

The Python or Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python or operator combines two Boolean expressions and evaluates to True if at least one of the expressions returns True. Otherwise, if both expressions are False, than the entire expression evaluates to False. The code above gives examples on how this works.

The Python not Operator

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python Boolean not operator is used in a Boolean expression in order to evaluate the expression to its inverse value. If the original expression was True, including the not operator would make the expression False, and vice versa. For example, the statement 1>2 evaluates to False so adding the not operator will make not 1>2 evaluate to True.

if Statements

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python if statement is used to determine the execution of code based on the evaluation of a Boolean expression. If the if statement expression evaluates to True, then the indented code following the statement is executed. If the expression evaluates to False then the indented code following the if statement is skipped and the program executes the next line of code which is indented at the same level as the if statement.

Conditional Statements

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

Python uses conditional or if statements to run a segment of code only if a given boolean expression, or condition, is deemed true. If the expression evaluates as False, the code following the if statement will not run. In the code above, the method sweetSixteen() will only run if the conditional statement, myAge == 16, is true. Since the variable is equal to 16, the program will call sweetSixteen().

else Statement

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python else statement provides alternate code to execute if the expression in an if statement evaluates to False. The indented code between the if and else is executed if the expression evaluates to True. The indented code immediately following the else is executed only if the expression evaluates to False. To mark the end of the else block, the code must unindented to the same level as the starting if line.

If-Else Statements

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

else statements can be paired with if statements to provide a default control flow option. If the boolean expression of the if statement evaluates false, the code following the else statement will be run. For example, in the code above, since myAge is 15 not 16, the method sweetSixteen() will not be run. Rather the program will defer to the else statement and run happyBirthday().

Boolean Values

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

Booleans are a data type in Python, much like integers, floats, and strings. However, booleans only have two values: True of False. Specifically, these two values are of the bool type. Since booleans are a data type, creating a variable that holds a boolean value is the same for other data types.

elif Statement

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

The Python elif statement allows for continued checks to be performed after an initial if statement. An elif statement differs from the else statement because another expression is provided to be checked just as with the initial if statement. If the expression is True the indented code following the elif is executed. If the expression evaluates to False the code can continue to an optional else statement. Multiple elif statements can be used following an initial if to perform a series of checks. Once an elif expression evaluates to True no further elif statements are executed.

Handling exceptions in Python

== #checks if two values are equal != #checks if two values are not equal < #checks if first value is less than second > #checks if first value is greater than second >= #checks if first value is greater than or equal to second <= #checks if first value is less than or equal to second

A tryand except block can be used to handle error in code block. Code which may raise an error can be written in the try block . During execution, if that code block raises an error, the rest of the try block will cease executing and the except block code will execute.

Chevron Left Icon
Control Flow
Lesson 1 of 2
Chevron Right Icon
  1. 1

    Imagine waking up in the morning. You wake up and think, "Ugh, is it a weekday?" If so, you have to get up and get dressed and get ready for work or school. If not, you can sleep in a bit lon...

  2. 2

    In order to build control flow into our program, we want to be able to check if something is true or not. A boolean expression is a statement that can either be [...] or [...] . Let's go back t...

  3. 3

    Now that we understand what boolean expressions are, let's learn to create them in Python. We can create a boolean expression by using relational operators. Relational operators compare two it...

  4. 4

    Before we go any further, let's talk a little bit about [...] and [...] . You may notice that when you type them in the code editor (with uppercase T and F), they appear in a different color tha...

  5. 5

    "Okay okay okay, boolean variables, boolean expressions, blah blah blah, I thought I was learning how to build control flow into my code!" You are, I promise you! Understanding boolean variabl...

  6. 6

    Now that we've added conditional statements to our toolkit for building control flow, let's explore more ways to create boolean expressions. So far we know two relational operators, equals and not ...

  7. 7

    Often, the conditions you want to check in your conditional statement will require more than one boolean expression to cover. In these cases, you can build larger boolean expressions using _boolean...

  8. 8

    The boolean operator [...] combines two expressions into a larger expression that is [...] if either component is [...] . Consider the statement [...] This statement is composed of two exp...

  9. 9

    The final boolean operator we will cover is [...] . This operator is straightforward: when applied to any boolean expression it reverses the boolean value. So if we have a [...] statement and ap...

  10. 10

    As you can tell from your work with Calvin Coolidge's Cool College, once you start including lots of [...] statements in a function the code becomes a little cluttered and clunky. Luckily, ther...

  11. 11

    We have [...] statements, we have [...] statements, we can also have [...] statements. Now you may be asking yourself, what the heck is an [...] statement? It's exactly what it sounds like...

  12. 12

    [...] , [...] , and [...] statements aren't the only way to build a control flow into your program. You can use [...] and [...] statements to check for possible errors that a user might enc...

  13. 13

    Great job! We covered a ton of material in this lesson and you've increased the number of tools in your Python toolkit by several fold. Let's review what you've learned this lesson: Boolean e...

  1. 1

    This lesson will help you review Python functions by providing some challenge exercises involving control flow. As a refresher, function syntax looks like this: [...] For example, a function t...

  2. 2

    [...]

  3. 3

    [...]

  4. 4

    [...]

  5. 5

    [...]

  6. 6

    [...]

  7. 7

    [...]

  8. 8

    [...]

  9. 9

    [...]

  10. 10

    [...]

  11. 11

    [...]

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo

Learn Python: Control Flow

Start[missing "en.views.course_landing_page.learn-python-3.course_illustration" translation]