Conditionals and Control Flow
Learn how to use conditionals and control flow to create programs that generate different outcomes.
StartConditionals & Control Flow
Lesson 1 of 2
- 1Just like in real life, sometimes we’d like our code to be able to make decisions. The Python programs we’ve written so far have had one-track minds: they can add two numbers or print something, b…
- 2Let’s start with the simplest aspect of control flow: comparators. There are six: Equal to (==) >>> 2 == 2 True >>> 2 == 5 False Not equal to (!=) >>> 2 != 5 True >>> 2 != 2 False …
- 3Excellent! It looks like you’re comfortable with basic expressions and comparators. But what about extreme expressions and comparators?
- 4Comparisons result in either True or False, which are booleans as we learned before in this exercise . # Make me true! bool_one = 3 < 5 Let’s switch it up: we’ll give the boolean, and you’ll wr…
- 5Boolean operators compare statements and result in boolean values. There are three boolean operators: 1. and, which checks if both the statements are True; 2. or, which checks if at least one …
- 9Boolean operators aren’t just evaluated from left to right. Just like with arithmetic operators, there’s an order of operations for boolean operators: 1. not is evaluated first; 2. and is evaluate…
- 10Great work! We’re almost done with boolean operators. # Make me false bool_one = (2 <= 2) and “Alpha” == “Bravo”
- 11if is a conditional statement that executes some specified code after checking if its expression is True. Here’s an example of if statement syntax: if 8 < 9: print “Eight is less than nine!” …
- 12Let’s get some practice with if statements. Remember, the syntax looks like this: if some_function(): # block line one # block line two # et cetera Looking at the example above, in the eve…
- 13The else statement complements the if statement. An if/else pair says: “If this expression is true, run this indented code block; otherwise, run this code after the else statement.” Unlike if, els…
- 14elif is short for “else if.” It means exactly what it sounds like: “otherwise, if the following expression is true, do this!” if 8 > 9: print “I don’t get printed!” elif 8 < 9: print “I get pr…
- 15Really great work! Here’s what you’ve learned in this unit: Comparators 3 = 5 10 == 10 12 != 13 Boolean operators True or False (3 = 5) this() and not that() **Conditional stateme…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory