--Originally published at Coding The Future
Photo by Matthew Smiths
Many times in life we are faced with crossroads and have to make a decision. In coding, things work similarly. Sometimes, actions that the program triggers depend on what the user chooses or inputs. This is where if-statements come in handy.
An if-statement triggers different actions depending on a certain condition. By using if-statements, you can tell a computer to do this if a certain condition is met, and do something else if it isn't.
In Python 3, declaring an if-statement is quite simple. All you have to do is to type the keyword if followed by a condition, and close with a colon. Here's a quick example:
if logWeight > 23:
print("Your suitcase exeeds the maximum weight allowed.")
As you can see, in the first line, I start by declaring an if, and then I state the condition, and close with a colon. The following indented lines specify the code that will be triggered if the condition is met. In natural language, it reads "if the suitcase's weight is greater than 23kg, print a warning message".
Let's say, however, you wanted to trigger a different action if the condition wasn't met. For example, if the suitcase's weight was less than 23kg. Then all you need to do is add an else to your statement. Take a look:
if logWeight > 23:
print("Your suitcase exeeds the maximum weight allowed.")
else:
print("Thank you for your business.")
As you can see, all I did was to add new line (non-indented though) with the keyword else, and told the program that if the weight was anything but greater than 23, then print a message thanking the the customer.
But let's say, you wanted to get really specific, and have different actions for different conditions. Instead
Continue reading "WHAT IF? Exploring If-statements" →