5. Making Choices
Sometimes 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:
if "hello" in "helloworld":
print("it's in the string!")
In plain English, the above code says: "If the string
hellois contained in the string
helloworld, then output
it's in the string!"
Since the condition
"hello" in "helloworld"is
True, the next line
print("it's in the string!")is executed.
We can also introduce an
else:to execute an alternate outcome (e.g. if the condition is not met)
if sister_age > brother_age:
print("sister is older!")
print("brother is older")
You can also use multiple comparisons in a single condition. For example, the following
ifstatement finds out if the temperature is between the value 10 to 20, which is described by "larger than 10 and smaller than 20".
if temperature>10 and temperature <20:
We can create even more alternate outcome based on the different conditions:
print("Sister is older!")
print ("Same age.")
print ("Brother is older")
In fact, you can have as many
elifconditions as you like. Note that in this case
elsestatement is a "catch all" condition; if all the
elifconditions are NOT met, then execute the