5. Making Choices

If... statement

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 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

We can also introduce an else: to execute an alternate outcome (e.g. if the condition is not met)

sister_age=15
brother_age=12
if sister_age > brother_age:
    print("sister is older!")
else:
    print("brother is older")

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".

temperature=15
if temperature>10 and temperature <20: 
	Print("nice!")
else:
	Print("Too extreme!")

If...elif...else statement

We can create even more alternate outcome based on the different conditions:

sister_age=15 	
brother_age=15
if sister_age>brother_age:
	print("Sister is older!")
elif sister_age==brother_age:
	print ("Same age.")
else	
	print ("Brother is older")

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