CODE 3
Logic, Loops and Conditionals
Learning Objectives
- Learn about conditional statements and how to write them
- Learn how to use logic operators in your code
- Learn how to use for and while loops
- Create an app that searches a database
Congratulations on all your hard work so far! This is a really big unit but it contains a lot of the coding concepts essential for programming your app. Don’t get hung up on things you don’t understand because you can always come back to them later!
Before you start this unit, let’s review some concepts from the previous coding units that you will need:
- Algorithms are step-by-step instructions for your app to follow.
- Booleans are a datatype with two values: true and false.
- Event Handlers tell your app what to do when something happens.
- Variables are names for pieces of data that can change.
Try playing this fun Made With Code Robot game before you get started with this unit. It will help you get you familiar with the concepts you are about to learn. If you can’t figure out all five levels now, try coming back to it after you’ve finished this unit!
Conditions
You’ve been using event handlers a lot so far! In the past two coding challenges when your user hit a button, your app did something. For example, in the app you made in Code Challenge 2, the enter button added items to a to-do list. The event was the user hitting “enter” and the way the app handled it was by adding the user’s text to the to-do list. The code for your app worked like this:
You may have noticed in our example app or in your own ‘to-do list’ app, that the user could add a blank box into the list. Because of this, the user could have a really long list with nothing in it!
Let’s say that you didn’t want your user to be able to add a blank box to their to-do list. So, every time the user hits enter, you write code to ask your app “has the user entered text”? If the answer is yes, then the app adds the text to the to-do list. If the answer is no, then the app doesn’t add it. Now your code looks more like this:
In this case, "do this" means "add the text", and "do that" means "don't add anything". This a great way to fix your problem, but remember that computers can’t think for themselves, so you can’t directly ask them questions like you would ask a person.
In coding, when you want to ask your app a question, you program it to check a condition. A condition is something that a computer determines to be either true or false. True is like the computer is answering yes and false is like answering no. You can tell your app to do different things depending on if the condition is true or false. Here’s how you would ask your app if the user has entered text using a condition:
Do you remember the data type booleans from Code 2: Data and Variables? Booleans are a data type that can be true or false. When your app evaluates a condition, it outputs a boolean!
Conditional Statements
If/Else Statements
So now you know what a condition is, but how do you use it in coding? In coding, you ask your computer to evaluate conditions by writing conditional statements. Conditional statements are the way computers can make decisions. Conditional statements always have an if part, which tells the app what to do when the condition is true. Conditional statements also usually have an else part, which tells the app what to do when the condition is false. If you leave out the else part then your app will do nothing when the condition is false. Now your code for your enter button would look something like this:
Here is what conditional statements look like in App Inventor:
Here’s how these blocks work. You put a condition next to if. You put the code for what your app should do if the condition is true next to then and what you want your app to do if the condition is false next to else. If the condition is true, only the code next to then will run and all the code next to else will be ignored. If your condition is false, the code next to then will be ignored and the code next to else will run. Think of it as saying "If this condition is true then do this, else do this".
Let’s go back to the example we were using from Code Challenge 2. Here is what the conditional looks like filled in.
Here, when the user clicks the ‘enter’ button the app will evaluate this condition: “the length of the string entered in the textbox is not equal to zero”. If this condition is true (the length of the string is not equal to zero) it means the user has entered text, so the app will add the text to a list. If the condition is false (the length of the string is equal to zero), then the app ignores all the code that is next to then and skips to else, which notifies the user to "Enter some text!".
Activity 1
Can you think of some conditional statements that help you make decisions every day? Here are some examples to get started with:
- If it is raining, then take an umbrella with you
- If you are hungry, then eat snack, otherwise wait until later
- If your dog is whining, then take the dog for a walk
- If it is cold outside, bring a jacket
- If your hair is tangled, then brush it
- If you are sick, then go to the doctor
- If your phone is dead, then charge it
Else If Statements
So far you’ve learned how to write conditional statements that evaluate one condition and have two possible outcomes. In this section you’ll learn how to write conditional statements that evaluate more than one condition and have more than two possible outcomes.
Else if allows you to add another condition to your conditional statement. This second condition will be evaluated after the first condition and only if the first condition is false. If the second one is also false, then the app will default to else or it will do nothing. In the diagram below, the conditions are blue and the possible outcomes are in purple.
Conditional statement with two conditions and three possible outcomes. Condition 2 is only evaluated if Condition 1 is false.
Conditional statement with one condition and two possible outcomes.
Here’s what the blocks look like in App Inventor:
Your first condition goes next to if, and your second condition goes next to else if. Let’s look at an example:
You are designing an app that is only meant for users ages 13-18 teenagers and you want your app to let your users know if they are too young or too old to use your app. You have three possible outcomes:
- The user is too young
- The user is too old
- The user is the right age
You have the user enter their age into the app and store it in a variable called “age”. Here’s how you could use an if/else if/else statement to check your user's age.
The first condition tests if the user is younger than 13. If she is, then the app alerts her that she is too young. If she is not, the app then tests if she is older than 18. If she is, then the app alerts her that she is too old. If she is not, then the app tells her she is the right age.
You can actually add as many conditions as you want to your conditional statement by using else if, but it’s really important to note the order in which the app evaluates the conditions. Your code will always start with the first condition and then continue in order until it finds a condition that is true. When it finds a condition that is true it will carry out the code under it. If none of the conditions are true, it will carry out the code in the else part.
Here are some things to remember when using if/else/else if statements:
- You can test as many conditions as you want
- The statement works from top to bottom, so put the condition you want to be tested first at the top of the statement
- The only code that will be carried out is the code under the first statement found to be true
For more information on conditionals, check out MIT’s website here.
Activity 2
Identifying which conditions your app should evaluate can be tricky! Sometimes you know what you want your app to do, but it may be be hard to know which conditions to check. Let’s practice writing some conditions that you think the apps check when you use them. Here’s an example to get you started! See if you can come up with more examples.
Logging into a social media account:
- Conditions to check:
- The username is correct
- The password is correct
- The user has not tried to log in more than five times
Another hard part about writing conditional statements is translating the condition you have in mind into something your app can actually understand. In the example above, we checked a user’s age by first creating a variable that would be equal the user’s age. It is not always intuitive to set up conditions and it will take practice! Here are questions to ask yourself when trying to set up the right condition:
- Does your condition depend on information the user entered?
- Do you need to set up any variables?
- If so what type? Is it a number, list, or string?
- Can you use math operators such as less than (<) , greater than (>), equal to (=), not equal to (≠) in your condition?
- Do you need to compare the value of something with a value in a database?
- Do you need to compare something with data from somewhere else, like a website? (This will be discussed more in Code 4)
- What type of data does your condition rely on? Do you see any operations for that data type that will help you?
- Ex: Comparing two strings, finding the length of a string, adding items to a list, comparing two lists, etc.
- Try skimming through the operations in App Inventor to see if it helps you.
Logic
So far you’ve learned how to make your app do different things using conditional statements. You can tackle lots of new problems by knowing a few logic operators. Logic operators take multiple booleans inputs and simplify them into one boolean output. Because your app sees conditions as true or false, you can use conditions as inputs to logic operators. There are three major logic operators that you’ll learn in this section: and, or, and not. Although they may seem strange, you'll see examples below of how logic operators can help you build your app.
and Operator
In order for the and operator to output true, all of its inputs must be true. If any of the input conditions are false, your code will evaluate the whole statement as false. Here are all the possible outcomes when using and and function.
True and True = True
True and False = False
False and True = False
False and False = False
Here’s how you can think using and in a conditional statement:
Note: Using the and operator is different than using else if because both conditions are evaluated at the same time instead of one after the other. They also both need to be true for the app to see the conditional as true.
Examples
You should use and when you need two conditions to be true in order for something to happen. Here are some examples of when you may want to use and in your app!
- Logging into social media:
- If (the username is correct) and (the password is correct) → then allow the user to log in
- Winning a game
- If (the player finishes the level) and (time is not up) →then the user wins
- Finding a grocery store:
- If (the store is open) and (the store is near the user) → then show in the search results
- Posting pictures:
- If (the user has selected a picture) and (the user has entered a caption) → allow the user to post the picture
Can you think of any more examples?
or Operator
For the or operator to output true, only one of the inputs needs to be true. Here are all the possible outcomes when using the or operator.
True or True = True
True or False = True
False or True = True
False or False = False
Here’s how you can think using or in a conditional statement:
Note: The or operator may also seem similar to else if to you. The or operator is different because both conditions are evaluated at the same time instead of one after the other. The or operator is better to use when you have two conditions that should have the same outcome if they are true.
Examples
- Losing a game:
- (If time runs out) or (the player loses all their lives) → then the player loses
- Showing search results
- (If the title matches) or (the description matches) → show it in the search results
- Recommending videos to a user
- (If the user watched it in the past) or (it is similar to something the user liked) → recommend it to the user
not Operator
The not operator is an easy one! The not operator switches the value of a boolean to be the opposite of what it is.
not true = false
not false = true
Sometimes it is easier to write a condition that makes your app check the opposite of what you want. For these scenarios you can use the not operator. Here's how you can think of it in a conditional statement.
Examples
- You want to check if there is text in a textbox, but it’s easier to check if the textbox is empty than to check if there is something there. You use the not operator so you can check if the textbox is not empty.
- If not (textbox = “ ”) → do this
- You want to exclude search results about puppies, so you make sure the word puppy is not there by using the not operator.
- If not (article contains word puppy) → show results
- You can combine logic operators to do more things. Here’s how you could show search results that have the word kitten and do not have the word puppy.
- If not (article contains word puppy) and (article contains word kitten) → show results
Activity 3
Do you know that you can use and, or and not in a Google search? This is a good way of narrowing down or broadening search results when you’re looking for something. Try it out! Make sure that you type "AND", "OR" or "NOT" in all capitals. Check out the examples below:
Searching for 2017 AND Technovation gives results that contain both 2017 and Technovation:
Searching for 2017 OR Technovation gives results that contain either 2017 or Technovation:
Loops
Imagine if you were asked to write down your name one hundred times in a row. Not only would this be really boring, but it would take you a long time. If you got tired, you might even start to make mistakes! If you asked a computer to print out your name one hundred times, it would do it really fast without making mistakes! Unlike people, computers are great at doing the same thing over and over again. You can take advantage of this by using loops. A loop is a block of code that will repeat over and over again.
There are two types of loops, while loops and for loops. While loops will repeat until a condition you set is no longer true, and for loops will repeat a certain number of times.
For loops
For loops will repeat a block of code a set number of times. The reason they are called for loops is because you can tell your app how many times you want it to repeat to the code for. You can think about for loops as telling your app, “repeat this, for 14 times” or “repeat this, for 5 times”.
For loops use a variable to count how many times the code has been repeated, called a counter. You control how many times the loop repeats by setting where the counter starts and ends. You also set how much the counter goes up by each time the code repeats. In most scenarios you’ll want the counter to increase by 1 each time the loop repeats.
In App Inventor, for loops look like this:
The part that says number is the counter. For now the counter is has the name number, but you can change that. number will start at 1 and will stop when it is equal to 5. Each time the code inside the loop repeats, number increases by 1. So this loop will repeat the code inside of it 5 times. Right now, this loop doesn’t do anything, since the do part is empty. Let’s walk through an example.
We haven’t changed anything about the number variable, but we have added some code to the do part of the loop. Each time this loop runs, the app will alert its user “hello”, so the user will get alerted 5 times. Here is how the app will run through this loop:
This loop would be useful if you wanted to alerts the user “hello” 5 times. This may not seem that useful since it isn’t that hard to put 5 notifier blocks in a row saying “hello”. But what if you wanted to alert the user “hello” 100 times? This would be much easier to do with a loop than by putting 100 blocks in a row!
Another way that for loops can be useful is by using the counter variable in your code. Each time the loop runs the counter variable will have a different value and this can be really useful. Here’s an example.
In this for loop we are using the variable number in the code by attached it to the word “hello”. Number increases by 1 each time, so the app will keep print out different things each time it runs. Here is how the app will run through this loop now:
For Each Loops
Another useful type of for loop that you can use in App Inventor is this one:
Here, the counter variable is called item and is already set to repeat for the number of items in a list. These loops be very useful whenever you need to do something with a list. Here’s an example.
Let’s say you had a list of numbers and you wanted to add up every number inside the list and store it in a variable called sum. Here’s how you would do this with a for each loop.
Each time the loop runs, the variable sum will get an item from numberList added to it. The loop will automatically stop after all the numbers in the list have been added!
Note: You may have noticed that the counter variables in this section are a lot like the local variables you learned about in Code 2! Just like local variables, you can only use them inside the loop.
While Loops
While loops are loops that will continue to go until a condition is no longer true. The reason they are called while loops because the code will repeat while a condition is still true. You can think of while loops as telling your app “while this happens, repeat this” or “while this hasn’t changed, repeat this”.
Example
You’re having a party and you want the music to keep playing until all your guests leave. You could describe your party as this loop:
- While (people at party > 0)
- do: keep playing music
What if you also want your music to stop playing when it gets later than midnight? You can program while loops to end the loop based on multiple conditions using logic. Now you can describe your party as this loop.
- While (people at party > 0) and (time < midnight)
- do: keep playing music
In this case the music would stop as soon as everyone left the party or if it is past midnight.
To use a while loop you need to set up a condition that starts out as true. If your condition starts out as false, then your loop will never run. The loop will check the condition each time before it repeats to make sure the condition is still true.
Here’s what while loops look like in App Inventor:
With while loops it’s possible to run into errors! If you choose a condition that will never be false, then your loop will never end. This is called an infinite loop. Here’s an example:
Since 1 will always be equal to 1, this condition can never be false! When we ran this code in App Inventor our phone froze and we couldn’t do anything. You may also get a message saying that the App Inventor Companion App has stopped working.
Code 3 Challenge: Search a Database
Create an app that allows the user to search a database of information and view their results. The database should contain names and descriptions of famous people, places, movies, music, events or anything else you want. Make sure you have at least three entries in your database.
Try to figure out how to complete the Coding Challenge on your own before looking at the instructions. The instructions show just one way of how this challenge can be solved.
Reflection
Congratulations on completing this lesson! This was a huge lesson but it will be very useful when you are creating your app! Don’t forget that you can always review anything you don't understand now.
Review of key words:
- Booleans - datatype that can be true or false
- Conditions - something an app evaluates to be true or false
- Conditional Statement - tells the app what to do after evaluating conditions
- AND Operator - evaluates as true if all of the inputs are true
- OR Operator - evaluates as true if one of the inputs is true
- NOT Operator - evaluates as the opposite of the input
- Loop - a repeating block of code
- For Loop - repeats a block of code a certain number of items
- For Each Loop - repeats a block of code for the number of items in a list
- While Loop - repeats a block of code while a condition is true