Photo by Domenico Loia on Unsplash
Without if else statements, your code is like a GPS without a map - directionless and destined to get lost
In Python (or any other programming language), "if-else" statements are used to make decisions in your code. Think of it like making a choice based on a condition. Let's find out how they work.
Example 1
Imagine that you want to play a game outside. Before you go outside, you may want to check the weather. If it is sunny, you can go and play. If it is rainy, you cannot go and play. Let's create a program to showcase this scenario.
Step 1
Create the below variable
Step 2
Create the "if-else" statement and print the program.
Step 3
Your "output" window should have the below result.
You can change your variable is_sunny to false (Written as False) and you will get the below statement
That's a simple example but now, let us use some numbers
Example 2
Imagine that you're playing a video game that has eight levels. Suppose that after playing the first five levels, you have earned 400 points. To go to the sixth level, you need to have 600 points or more points. Since the player's 400 points are lower than the required 600 points, you cannot go to the next level. The only option is to replay the other levels until you reach 600 or more points.
Step 1
Type the below variables in your editor. Set the current points earned by the player to 400 and the required points to reach level 6 to 600.
Step 2
Type the below "if-else" statement in your editor, and print it. Check if the player has enough points to proceed to level 6.
Step 3
Run the whole program and you should get the below output.
It looks like the player will not have enough points to proceed. Anyway, you can play around with the program, or come up with your examples, and post them in the comments if you wish to.
Keep in mind that "if-else" statements can become more complex such as nested statements, and also add more conditions rather than just one "else" statement. For now, this simple explanation will do for now though I will touch on nested "if-else" statements and the additional conditions to the decision-making process.
Okay, that is all folks. In the next article, we shall look at logical operators. Stay tuned.