5. Making Choices
If...
statement
If...
statementSometimes your instructions require the computer to make choices based on certain conditions. In our example of coding a simple toy car, a condition in could be: "If the car encounters an obstacle, then turn right"
A simple "if..." condition in Python looks like this:
In plain English, the above code says: "If the string hello
is contained in the string helloworld
, then output it's in the string!
"
Since the condition "hello" in "helloworld"
is True
, the next lineprint("it's in the string!")
is executed.
If...else
statement
If...else
statementWe can also introduce an else:
to execute an alternate outcome (e.g. if the condition is not met)
You can also use multiple comparisons in a single condition. For example, the following if
statement finds out if the temperature is between the value 10 to 20, which is described by "larger than 10 and smaller than 20".
If...elif...else
statement
If...elif...else
statementWe can create even more alternate outcome based on the different conditions:
In fact, you can have as many elif
conditions as you like. Note that in this case else
statement is a "catch all" condition; if all the elif
conditions are NOT met, then execute the else
statement.
Last updated