Having Python tell us if something is true or not is fundamental to anything that we want to do in programming. Based on something being true or false, we can tell our code to do something. By using if statements, Python is able to evaluate information and act accordingly.
“If this wall only has three players, I can get it into the top corner. I’ll shoot.”
“If they are playing 3 defenders, I will need to select quick wingers to exploit space.”
Let’s take a look at an example with some numbers.
if 11 > 10: print("Done!")
If the statement ’11 is greater than 10′ is true, print done. But what if we give something as false?
if 9 > 10: print("Done!")
Nothing happens! But we can tell the statement to do something in the case of something false:
if 9 > 10: print("Done!") else: print("That was false!")
That was false!
The ‘else:’ statement adds the instructions on what to do if it is false. Please pay close attention to how we structure this. There is a ‘:’ after ‘else’, and a tab space on the new line for the command. This is important!
In 2100, Oldcastle United take the brave step of hiring a robot head coach. Throughout the game, Bobby Roboson decides to tell his players to attack more or less depending on the score. eGaffer may use the following code:
OldcastleScore = 0 OpponentScore = 0 if OldcastleScore < OpponentScore: print("ATTACK ATTACK ATTACK!") else: print("10 men behind the ball!")
10 men behind the ball!
So above, if the opponent are ahead, Oldcastle attack. Otherwise, they play ultra-defensively.
We don’t seem to have taken account for a draw. Let’s upgrade iCoach with an ‘elif’ statement – short for else if.
OldcastleScore = 0 OpponentScore = 0 if OldcastleScore < OpponentScore: print("ATTACK ATTACK ATTACK!") elif OldcastleScore == OpponentScore: print("Stay solid, but exploit any opportunity!") else: print("10 men behind the ball!")
Stay solid, but exploit any opportunity!
Awesome, our coach has increased his decision making by 50%! It now checks to see if we are losing, if we are drawing or if anything else is happening (which can only be winning). If you change the scores in the example, it will react accordingly. Pretty cool!
If statements are fundamental to programming – they give machines the ability to react based on information that it receives.
Between ‘if’, ‘elif’ and ‘else’, we gave a coach the ability to assess the scoreline and act accordingly. Great job!