Get startedGet started for free

Comparisons and control flow

1. Comparison operators

Like in MATLAB, Python supports logical operators such as greater than, less than, equal to, and so on, which let you check whether values meet some criteria. In this lesson, you will learn these operators and how to use them to control the flow of your code.

2. Using comparison operators

Comparison operators compare the two value and return the outcome of the comparison. In this example, the variable "meets_criteria" will be "True" or "False" based on the comparison between the variables "value" and "threshold." Since we are using the "greater than" operator, "meets_criteria" will be True if "value" is greater than "threshold," which it is.

3. The comparison operators

There are six comparison operators available in Python. You'll note a strong similarity between the comparison operators in Python and MATLAB. Notably, all are the same except for the "Not equal" operator, which differs between the two languages.

4. If

Comparison operators are especially useful for controlling the flow of your code using if statements. If statements work similarly to if statements in MATLAB, with a few distinct differences. In Python, the statement is separated from the expression to evaluate by a colon; then the expression is indented with four lines. Like for loops, the statement terminates when the code block is no longer indented.

5. Else

You can use "else" to specify an alternative block of code to execute when the conditions of the if statement are not met.

6. Else if

If there are multiple conditions you need to evaluate, you can add "else, if" statements using the expression "elif" after the if statement to add additional conditions. Each statement is evaluated in order, so the first statement, which evaluates "True," will be executed and subsequent statements will not be evaluated.

7. Let's practice

Now you are ready to practice using comparison operators and if statements to control the flow of your code.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.