"

6 Conditional Statements

Hasan Malik and Rutwa Engineer

Learning Objectives

  • Learn about If-Statements
  • Learn about If-Else Statements
  • Learn about If-Elseif-Else Statements
  • Learn when to use each type of conditional statement
  • Learn the not operator
  • Learn how boolean variables interplay with conditional statements

Introduction

If statements (also called conditional statements) are the most fundamental decision-making technique in programming. They allow your program to make decisions based on whether or not particular conditions are met.

Have you ever tried to make an email account? When you try to sign up, the system asks you to input your age. Then, if your age is >= 18, you are permitted to make an account. This is an example of a conditional statement being used in a real-life application.

Similarly, cops who track speeding violations often use speed detectors by the side of highways. If the speed of any vehicle is found to exceed 60 (or 70, or 80 – whatever the speed limit happens to be), then a speeding violation is issued. This is another example of a conditional statement being used in real-life computations.

This module is one of the longer ones. Please understand each example carefully. Once you’ve understood an example, try to tweak the example scenario slightly and test the modified code—remember that the best way to learn programming is to play around with the concepts you’re learning!

Exercise

Can you think of any other examples of if-statements being used in real life?

If-Statements

Armed with this knowledge, let us proceed to learn if statements in Lua.

Example

age = 21

if age>18 then

print("You may create an email.")

end

print("Program finished.")


Output:

You may create an email.

Program finished.

Look at the above example. Here, we use an if statement to evaluate a condition. The condition here is “age>18” i.e. if the value of the variable age is greater than 18, then – and only then – the indented block of code will be executed.

That might be a lot of stuff to take in at once, so let’s go slowly!

After the condition, the keyword then is used to specify that we are now going to write a block of code that should only be executed if the condition is true.

At the end of this block of code, we write the keyword end to specify that the if statement is complete and the remainder of the code should run normally. This is why the statement “Program finished” is bound to execute regardless of whether the age is >18 or not.

Example

age = 16

if age>18 then

print(“You may create an email.”)

end

print(“Program finished.”)


Output:

Program finished.

This is because the age was not greater than 18, therefore the indented block of code between then and end did not run. However, because the last line is not within the indented block of code, it still outputs Program finished.

Now, here’s something for you to think about – what if the value of age was 18? Would the condition be considered as true or false?

Answer

It would be considered false, because 18 is not greater than 18. Therefore, we would get the same output as in Example 2!

If we wanted 18-year-olds to be able to create an email, then we could change the condition as follows:

Example

age = 18

if age>=18 then

print(“You may create an email.”)

end

print(“Program finished.”)

The operator X >= Y means “X is greater than or equal to Y”. As 18 is equal to 18, this condition therefore is true, so the program outputs:

Program finished.

Exercise

Write an if statement using the operator <= in your condition.

If-Else Statements

Usually, we want our code to do something if the condition is true, and something different if the code is false.

For example, in the email example, if the age is >= 18, we want the user to be able to create an email. If not, then we want to tell them that they cannot create an email.

To do this, we can use if-else statements.

Example

age = 14

if age>=18 then

print("You can create an email!")

else

print("You are too young to create an email.")

end


Output:

You can create an email!

If we change the value of age to 18, then it outputs:

You are too young to create an email.

If-Else Syntax

The syntax of an If-Else Statement is very similar to a simple if-statement.

Note that there is only one end keyword used.

Exercise

Exercise: Write an if-else statement based on a real-life example.

If-Elseif-Else Statements

Often, cases in the real world are not black-and-white. There are many more possible situations than a simple if-else statement can cover. To account for this, we use if-elseif-else statements, which can cover exceptional cases.

Example

score = 75

if score >= 90 then

print("Grade: A")

elseif score >= 80 then

print("Grade: B")

elseif score >= 70 then

print("Grade: C")

else

print("Grade: F")

end

Here, the score is being checked for multiple cases.

Firstly, we check if score >= 90. The program realizes than 75 is not greater than or equal to 90, therefore it ignores the first print statement.

Secondly, it checks if score >= 80.  The program realizes than 75 is not greater than or equal to 80, therefore it ignores the second print statement.

Thirdly, it checks if score >= 70.  The program realizes than 75 is greater than 70, therefore it executes the third print statement.

Key Takeaway

As soon as an else-if statement is executed, the program immediately ignores all subsequent cases and proceeds directly to the end statement.

We can also use strings in our condition. Let’s see the next example.

Example

weather = "rainy"

if weather == "sunny" then

print("It's a sunny day! Wear sunglasses and sunscreen.")

elseif weather == "cloudy" then

print("It's cloudy. You might not need sunglasses, but keep a light jacket handy.")

elseif weather == "rainy" then

print("It's rainy. Don't forget your umbrella and raincoat!")

elseif weather == "snowy" then

print("It's snowy. Wear warm clothes and be careful on the roads.")

else

print("Weather condition unknown. Check the forecast and prepare accordingly!")

end

This is an example of a basic weather app that recommends its user to prepare for the weather depending on the climate.

Note the “==” operator. We have discussed it previously under the Comparison Operators section when talking about the number data type. The == operator is called the equality operator in Lua. It is used to check whether the item on its left side is exactly equal to the item on its right side. For example, 5==5 is true, but 4==5 and 6==5 are false. Similarly, in this program, weather == “cloudy” is false and weather == “rainy” is true, because in the first line of the code, we initialized weather = “rainy”.

Key Takeaway

The equality operator works for string values as well.

Here, many students get confused between the assignment operator “=” and the equality operator “==”. Note that the assignment operator is only used when initializing/updating the value of a variable, and the equality operator is only used for comparisons.

Now, let us analyse the example above.

Examine the code line by line yourself. You will see that the condition is fulfilled only in the second else-if statement, therefore the program will output:

It’s rainy. Don’t forget your umbrella and raincoat!

Exercise

Write an if-elseif-else statement with at least four different elseif statements.

Multiple Conditions

Part of being a good programmer is being able to understand that the real world is complex. Oftentimes, your code needs to make decisions based on the value of multiple variables.

Example

Let’s say that you can take a roller-coaster only if you have a ticket and you are an adult and your height is greater than 5 feet.


ticket = true

age = 19

height = 5

 

if ticket == true and  age >=18 and height >= 5 then

print (“You may ride the roller-coaster!”)

else

print(“You cannot ride the roller-coaster.”)


Output:

You may ride the roller-coaster!

This code checks all three conditions using the keyword and. This means that all three conditions have to be fulfilled for the first indented block of code to be executed. If even a single condition is false, then the code will move to the else statement.

If we change the value of age to 16, the code outputs:

You cannot ride the roller-coaster.

because one of the conditions was not fulfilled.

Note: What is the data type of the variable ticket?

Show/Hide

That’s right – Boolean! Boolean variables are extremely useful in checking conditions, because their value is always either true or false.

In this case, we could have instead written our if statement as follows:

if ticket and  age >=18 and height >= 5 then

The variable “ticket” is—on its own—acting as a condition! Isn’t that cool?

How does this work? Well, for boolean variables, if their value is true, then the condition is considered as being true. And if their value is false, then the condition is considered as being false!

Writing shorter and easier-to-read code is a highly-valued skill in programming. Using boolean variables is, therefore, often a smart decision.

Key Takeaway

For boolean variables, if their value is true, then the condition is considered as being true. And if their value is false, then the condition is considered as being false!

 

Exercise

Write an if-elseif-else statement using the and operator.

 

Example

Let’s say that you can enter the TTC if you have a ticket, or have a monthly pass, or you are a VIP.


ticket = true

monthly_pass = false

vip = false

 

if ticket or monthly_pass or vip then

print("You may board the bus.")

else

print("You cannot board the bus.")

end


Output:

You may board the bus.

Notice the or operator. Unlike the and operator, which requires every single condition in the sequence to be true, the or operator is much more generous. If even a single condition is true, then the overall condition of the if statement is considered as being fulfilled!

Exercises

  • If we had used an and operator instead of an or operator, what do you think the output would have been, in the above example?
  • Write an if-elseif-else statement to describe who can enter a concert of your favourite singer.

Sometimes, we want to check if a particular thing has not been done.

For example, let’s say you are handing out free juices to your friends, but you want to make sure each friend only gets one juice. We can model this using the following code:

Example

already_gotten = false

 

if not already_gotten then

print(“Here’s your juice!”)

else

print(“Sorry, you’ve already had your juice.”)

end

Here, the keyword not flips the condition.

not is a boolean operator that flips the value of the condition.

The not Operator

not <true> will be false.

not <false> will be true.

The Condition as a Boolean

You should think of the condition of a conditional statement as a boolean value.

The if-statement is only executedwhen the expression between if and then evaluates to true.

Now, revisit the above example.

already_gotten has a value of false, because we initialized it as false. The not operator flips the value of already_gotten. Therefore, not already_gotten evaluates to true, therefore, the code outputs:

Here’s your juice!

On the other hand, observe this code:

 

already_gotten = true

 

if not already_gotten then

print(“Here’s your juice!”)

else

print(“Sorry, you’ve already had your juice.”)

end

Here, the code outputs:

Sorry, you’ve already had your juice.

because already_gotten is true, so therefore, not already_gotten is false. Thus, the expression between if and then overall evaluates to false. Hence the if-statement is not executed, and the program runs the else-statement instead.

Wrapping Up: Conditional Statements

Now that you understand how if-else statements work, observe all the above examples again. See that the if-statement runs only when the expression between if and then evaluates to true.

If it evaluates to false, then the code checks the elseif-statements, one by one.

If none of them evaluate to true, then the code runs the else-statement.

Truthy and Falsy Values

In Lua, only nil and false are considered falsy. Everything else, including 0 and “”, is truthy.

Congratulations—you’ve finally learnt conditional statements, one of the cornerstones of programming!

 

 

License

Learn Coding and Animations in Lua Code Copyright © by Kyra Ma; Hasan Malik; and Rutwa Engineer. All Rights Reserved.