A lot of times we face situations where we have to make decisions:
We may have to decide simple stuff like, “Should I bring and umbrella out?”, or more complex questions like “Should I, based on the historical pattern of rainfall, and weather forecasts from twenty different sources, go to the beach next Sunday?”. The complex question presents you with conditions, and you will base your decisions on those conditions. For example, if the weather forecast says that it will be 30 degrees Celsius, which means that it is likely to be sunny on Sunday, I will go to the beach. Written in Python, it may look like this:
if temp == 30:
What the above procedure mean is that if
temp (an integer representing the temperature in degrees Celsius) is
30, we will
go. The double equals sign
'==' is an
equality comparator. It basically takes the expression on both sides and compare them. It returns a boolean value of
True if both expressions have the same value.
A boolean value is like a simple light switch:
A boolean can be in either of two states:
False. (Mind the capitalization.)
So in the procedure above, only if
temp == 30 is true, we will return go. Other wise the procedure exits without any output.
Modifying the code a bit, we can choose to return a different output if the
temp is of an undesirable value:
if temp == 30:
In this case we are returning
NOGO for any values of
temp besides 30.
At this point you might be thinking, “but I want to go to the beach even if the temperature is
31 degrees Celsius!” Bravo!
if temp == 30:
if temp == 31:
Simple as that, you can write as many if as you want, but why go through the trouble?
if temp == 30 or temp == 31:
So if you have multiple conditions that
return the same output, you can place them all in the same
if statement. What this program does is that it looks at the value of
temp == 30 evaluates to True, it immediately returns
temp is not 30, it will look at the second expressions, which is
temp == 31, and if this expression evaluates to True, it will return
go. This process continues for as many
or that you state. Only either expressions on its side need to evaluate to
True for the code block below to be interpreted.
So now you might be thinking, “but I want to go to the beach as long as the temperature is between 25 and 35 degrees Celsius!” Are we going to write
or conditions? No definitely not, Python creators are smart to have given you more comparison operators.
if temp >= 25 and temp <= 35:
These peculiar looking operators
'<=' are actually pretty simple. The first one means greater than or equals to, and the second one means smaller than or equals to. They are basically a hybrid of the basic operators,
'>'. You see a new term,
and. This comparison operator is similar to
and requires the expressions on both of its sides to evaluate to
True before the code block below is interpreted, as compared to
or where only either one needs to be true.