So far weβve only been able to check a single condition in our βͺοΈ
/π
statements. But, we actually check more conditions by using the π
βͺοΈ
statement.
Like the βͺοΈ
that starts our conditionals, the π
βͺοΈ
accepts a condition and has a code block (π
β¦π
) that executes if the condition is π
. One or more π
βͺοΈ
statements can be added after the βͺοΈ
statement. The π
statement will still be added at the very end as the default to run if the conditions for βͺοΈ
and π
βͺοΈ
are all π
.
Letβs take a look at an example:
π€yellowπ€ β‘οΈππ trafficLight βͺοΈ trafficLight π π€greenπ€ π π π€Go!!π€βοΈ π π βͺοΈ trafficLight π π€yellowπ€ π π π€Slow down...π€βοΈ π π βͺοΈ trafficLight π π€redπ€ π π π€Stop!π€βοΈ π π π π π€This light's broken.π€βοΈ π π Prints: Slow down...
In the example above, we included two π
βͺοΈ
statements. Each checked for different conditions. The first condition that evaluated to π
executed its code block, so Slow down...
was printed to the terminal. Once a code block has executed, the rest of the statements donβt run. If none of the conditions were π
, e.g. trafficLight
had a value of π€brownπ€
, then π
βs block runs.
Instructions
Letβs make a program that tells us if what the phase of water is depending on the water temperature in Celcius.
Under the waterTemp
variable, add a βͺοΈ
statement that checks if waterTemp
is greater than or equal to 100
. Then, in its code block (ππ
), use a πβοΈ
to print out the string: π€Steamπ€
.
We also have to account for when waterTemp
is in its liquid state.
After the βͺοΈ
statement, add a π
βͺοΈ
statement that checks if waterTemp
is greater than 0
. Then, in its code block (ππ
), use a πβοΈ
to print out the string: π€Liquidπ€
.
What if our water is frozen?
After the π
βͺοΈ
statement, add another π
βͺοΈ
statement that checks if waterTemp
is greater than -273
. Then, in its code block (ππ
), use a πβοΈ
to print out the string: π€Iceπ€
.
What waterTemp
isnβt a valid temperature?
Letβs add a π
statement just in case. Inside its code block (ππ
), use a πβοΈ
to print out the string: π€Temperature not validπ€
.