Conditionals
Controlling Program Flow w/ Conditionals
A conditional allows a decision to be made about which code path to take.
- allows for conditional execution of code.
- it uses boolean values and boolean expressions to evaluate a condition
What do you think the two possible values are for boolean values?
The bool Type
Python represents these boolean values using the bool type. The bool type has two possible values:
Some things to pay attention to…
- both values start with an uppercase letter (you'll know you're doing it right in IDLE when they're highlighted appropriately →)
- these values are reserved words (keywords); they can't be used as variable names
Boolean Expressions / The Equality Operator
A boolean expression is just an expression that eventually evaluates to a boolean value.
- True evaluates to True
- False evaluates to False
The equality operator, == (double equals), will test the left and right hand sides for equality and evaluate to the appropriate boolean value
- 1 == 1 evaluate to True
- "foo" == "foo" evaluates to True
- "foo" == "bar" evaluates to False
if Statements
We use if statements to conditionally execute code.
- they start with the keyword if
- …followed by a boolean expression and a colon
- the code that is to be executed if the condition is met is placed in an indented code block.
For example:
if Statements continued
This will also work with equality operators and variables
Let's Make a Game!
Let's try making a number guessing game. Here's the expected output:
Review
- What's the equality operator in Python?
- What are the two possible values for the bool type?
- How do we write an if statement?