Coding 10: Loops

Loops

Coding 10

Using loops is one way to possibly improve your app and earn points in the the Demo Video section of the rubric.

In this lesson, you will…

  • Learn about loops
  • Create an app that you can bring to birthday parties

Key Terms

  • Loops - a way to tell a computer to do something (a block of code) many times in a row
  • For Loop -  repeats a block of code a set number of times
  • For Each Loop - repeats once for each item in a list
  • While Loop - repeats a block of code until a condition is no longer true

Loops

In this lesson, you’ll learn about loops. Loops are a way to tell a computer to do something many times in a row. Computers are really good at doing things over and over again, and doing them fast.

Imagine you were asked to write your name down 100 times in a row. This might take you a long time, and you might make a few mistakes along the way. This is a perfect task for a computer, which would be able to do it really fast and without any mistakes. 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 while a condition is true, and for loops will repeat a certain number of times. You’ll also learn about for each loops which are a type of for loop that repeats once for each item in a list. Let’s go through each of them in more detail.

For loops

For loops will repeat a block of code a set number of times. The reason they are called for loops is that 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 17 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 and Thunkable, for loops look like this:

App Inventor

for loop block

Thunkable

The part that says number is the counter. For now, the counter is named 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.

App Inventor

Thunkable

Thunkable also has a repeat loop, which works the same way, but without the counter. It can be used in place of the count with number block when you don’t need to keep track of number, as in the example above.

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.

App Inventor

Thunkable

In this for loop we are using the variable number in the code by joining it to the word “hello”. Number increases by 1 each time, so the app will display different phrases 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 and Thunkable is this one:

App Inventor

Thunkable

Here, the counter variable is called item and this loop is already set to repeat for the number of items in a list. These loops are very useful whenever you need to do something with a list. 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.

App Inventor

Thunkable

While Loops

While loops are loops that will continue to run while a condition is 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”.

Here are two examples to think about:

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 (guests 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 (guests 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.

While Loop Diagram

Here’s what while loops look like in App Inventor and Thunkable:

App Inventor

while loop block

Thunkable

With while loops it is 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:

App Inventor

Thunkable

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. When you’re coding you’ll break things all the time. That’s part of the learning process! Restart your companion app and try again.

Mobile apps are event-driven - that is, the code runs based on events, like button clicks and finger swipes. That means that loops are not very commonly used. The most likely loop block you will use will be the for each block, and that will be only if you are using lists in your app.

Activity: Multiplication tables

Remember doing your multiplication tables in school? Wouldn’t it be nice to have an app that does it for you? In this app, the user will enter a number, and the app will display that number multiplied by the numbers 1-12. For example:

You’ll need to use a for loop:

App Inventor

Thunkable

The code is started for you, but you need to fill in the missing blocks. This for loop counts from 1 to 12 for the multiplication table. 

Result is the label that will display the multiplication table. So you’ll use a join block to join what already is in Result.Text with the next line of the table. The “\n”  is called a line feed and it will drop the text to the next line. For example, the code blocks:

Joins what is in Result.Text, “1 x 4 = 4” with a line feed and “2 x 4 = 8” so Result.Text will now look like this:

1 X 4 = 4

2 X 4 = 8

Using the join block in the loop will continue to add more to Result.Text each time it iterates through the loop, which means each time it executes the code within the loop. Eventually, Result.Text will contain the entire multiplication table for that number! You may not need all the extra slots in the join block. You can just remove any extras by clicking on the blue gear icon and dragging them out.

Reflection

In this lesson, you learned about for loops, while loops, and for each loops. You also created an app that used a for loop in it!

  • How do you think you might use loops in your final app?
  • Does this give you any ideas for how you might build some of your features?

Additional Resources: Hangman Tutorial

App Inventor: Hangman Tutorial (Advanced)

Do you want some more practice using loops? You can try this tutorial by Technovation alumni Jennifer John.

App Inventor - Snow Globe Tutorial (Advanced)

Snow Globe Tutorial

This tutorial uses loops and the Any Component feature of App Inventor to generalize behavior for a group of components. It’s a handy feature to use if you have many of the same type of component. In this case, there are several Ball components that fall in the sky when the phone is shaken. Rather than write code for every single Ball, you put the Ball components in a list and use a loop for one set of code.

Coding 9: Advanced Logic and Conditionals

Advanced Logic and Conditionals

Coding 9

Learning about advanced logic and conditional will help you earn points in the technical part of the Demo Video section of the rubric. It will also potentially help you make your mobile app work better!

In this lesson, you will…

  • Learn how to write conditional statements that use logic
  • Improve your Magic 8 Ball app so that a person can’t ask a question that doesn’t have a question mark in it.

Key Terms

  • Logic Operators - allow computers to make decisions based on multiple conditions
  • And - a programming operator that will output  true when all input conditions are true
  • Or - a programming operator that will output true when at least one of the input conditions are true
  • Not - outputs the opposite of the condition input

Conditions

In the last coding lesson, you learned how to make your app do different things using conditional statements. In this lesson, you will learn about logic operators. Logic operators allow computers to make decisions based on multiple conditions. In App Inventor, these are blocks that need two inputs. There are three major logic operators that you’ll learn in this section: and, or, and not.

and Operator

The and operator will output true when all of the input conditions are true. If any of the input conditions are false, it will output false. Here are all the possible outcomes when using the and operator.

True and True = True

True and False = False

False and True = False

False and False = False

Here’s how you can think about using and in a conditional statement:

Note: Using the and operator is different than using an else if statement because both conditions are evaluated at the same time instead of one after the other.

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 about 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.

not Operator

The not operator switches the value of an input condition to be the opposite of what it is.

not true = false

not false = true

Here's how you can think of it in a conditional statement.

Activity: Magic 8 Ball Improvements - Logic Operators

In this activity, you are going to make one more improvement to your magic 8 ball app using logic operators. Your app will tell users to “ask them a question first” whenever

  • The user asks a question that doesn’t have a question mark in it
  • The textbox is empty

 

Question 1: First, what are the two conditions that you need to check for. How could you write these conditions in App Inventor?

Question 2: Do you think you need to use the and operator or the or operator for this? Where do you think this should go in your code?

Use your Magic 8 Ball code from the past two lessons. If you need the starter code, here it is again:

Reflection

In this lesson, you learned how to use logic operators to make more advanced conditionals statements.

  • What are some other conditions that might be helpful to add to the magic 8 ball app?
  • Can you think of some places in your app that you might want to use it?

Coding 8: If / Else / Else If Conditional Statements

If / Else / Else If Conditionals

Coding 8

Learning about conditionals  will help you earn points in the technical part of the Demo Video section of the rubric. It will also potentially help you make your mobile app work better!

In this lesson, you will…

  • Learn how to write an If / Else / Else If Conditional Statement
  • Improve your Magic 8 ball app by not allowing the user to ask the same question twice in a row

Key Terms

  • If / Else / Else If - conditional statements are statements that have more than one condition

If / Else / Else If

So far you’ve learned how to write conditional statements that check conditions to decide if they are true or false. The conditional statements you created in the last coding lesson had two possible outcomes. In this lesson, you’ll learn how to write conditional statements that check more than one condition and have more than two possible outcomes.

If / Else / Else If conditional statements are conditional statements that have more than one condition.  If the first condition is false, only then will the second condition will be checked. If the second one is also false, then the app will default to else or it will do nothing. Check out the diagram below. The conditions are blue and the possible outcomes are in purple.

A conditional statement with one condition and two possible outcomes.

A conditional statement with two conditions and three possible outcomes. Condition 2 is only checked if Condition 1 is false.

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 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:

  1. The user is too young
  2. The user is too old
  3. 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.

App Inventor

Thunkable

The first condition checks 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 checks 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 add as many conditions as you want to your conditional statement by using else if, but it’s really important to pay attention to the order in which the app checks 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 of the block, 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

The next coding lesson will cover logic and some more advanced conditionals that senior division students should try. If your team is in the junior division and this is your first time learning how to code, you may skip it.

Activity: Even Better Magic 8 Ball

In this activity, you’re going to improve your magic 8 ball app. In the last lesson, you made sure that the user put in some text before getting an answer. However, the user didn’t need to ask a new question to get a new answer.  They could keep pressing enter, and as long as there was text in the text box, our app would give them an answer.

Let’s fix this. We are going to use an if / else / else if conditional statement to check if the user has entered any text, and then if they have entered text, we will check to see if this question this a different question than the last question asked.

We set up a variable called lastQuestion, which is going to remember the last question that the user asked.

 

Here’s how our code works. Each time the user gets an answer from our magic 8 ball, our code updates the variable lastQuestion with whatever is in the textbox.

Now you need to figure out how to check that the variable lastQuestion is not the same as what the user has in the textbox now. You’ll need to finish this  If / Else / Else if statement. Download the example code to get started.

Reflection

In this lesson, you learned how to use If Else and Else If conditional statement.

  • What are some other conditions that might be helpful to add to the magic 8 ball app?
  • Can you think of some places in your app that you might want to use it?

Coding 7: If / Else Conditional Statements

If/Else Conditional Statements

Coding 7

Using conditionals is one way to earn more points in the Demo Video section of the rubric.

In this lesson, you will…

  • Learn about conditional statements and how to write them
  • Improve your magic 8 ball app by making sure the user puts a question in the textbox

Key Terms

  • Conditions -  A state or situation something is experiencing
  • Conditionals Statements -  A way for computers to make decisions based on conditions
  • If/Else - A common form of conditional statements in programming; tells the computer that if the condition is true, do this. Else, if the condition is false, do another thing.

Conditions

So far, you have been using a lot of event handlers. In the past few activities, when your user pushed a button, your app did something. For example, in the magic 8 ball app from Coding 6 Lists, the enter button added items to a to-do list. The event was the user pushing “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:

If you didn’t get a chance to do this activity, you can download the code and try it now.

You may noticed that you just can press enter without asking a question (leaving the box blank), and the app will still give you an answer. Let’s fix this. We don’t want our users to get answers without asking any questions. So, every time the user hits enter, we want our code to check, “has the user entered any text”? If the answer is yes, then the app gives them an answer. If the answer is no, then the app tells them to ask a question. Now your code looks more like this:

Here, "do this" means "give an answer", and "do that" means "tell them to ask a question". 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 can decide is 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 Coding 4: Data and Functions? Booleans are a data type that can be true or false. When your app checks a condition, it gives the answer in the form of a boolean.

Conditional Statements

So now, you know what a condition is, but how do you use it in coding? In coding, you ask your computer to check 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 if will run. Think of it as saying "If this condition is true then do this, or else do that".

Let’s go back to the example we were using from the Magic 8 Ball. Here is what the conditional looks like filled in.

Here, when the user clicks the ‘enter’ button the app will check this condition: “the string in the textbox does not equal a blank string”. If this condition is true (the string does not equal a blank string) it means the user has entered text, so the app will give the user an answer. If the condition is false (the string is equal to a blank string), then all the code next to then is ignored, and skips to else, which tells the user to "Ask me a question first!".

There are a few different ways to write this conditional statement. All of them work, there is no correct answer. There are four more examples below. See if you can understand them.

Example 1:

Condition: the length of the string in the textbox is not equal to zero

Example 2:

Condition: the textbox is not empty

Example 3:

Condition: the length of the string in the textbox is equal to zero

(notice that the blocks next to then and else are switched compared to example 1)

Example 4:

Condition: the textbox is empty

(notice that the blocks next to then and else are switched compared to example 1)

Activity: Smarter Magic 8 Ball

It’s time to make your magic 8 ball app better! You want your app to check to see if the user has really entered when they press “enter”. See if you can remember how to create your conditional statement.

Activity - Winner Counting App

This activity builds on the activity from Coding 5: Variables. If you haven’t done that activity yet, try it now!

Now that you’ve mastered conditionals for your magic 8 ball, let improve another one of our old apps, the counting app. Let’s turn this app into game. Try to start the count over as soon as the user reaches 100. So, when the user presses a button to increase the count, you’ll want to check and make sure that they are not going over 100.  Where do you think you should put your conditional statement?

Reflection

In this lesson, you learned about conditional statements. Can you think of some conditional statements that you use to make decisions every day? Here are some examples:

  • If it is raining, then take an umbrella with you, else get wet
  • If it is cold outside, then bring a jacket, else you will freeze!
  • If your phone is dead, then charge it, else you won’t be able to use your phone.
  • If you are sick, then go to the doctor, else go to school.
  • If your clothes are dirty, then wash them, else have no clean clothes to wear!
  • If you eat your vegetables, then you will get dessert, else mom won't let you!

Coding Challenge 2: Make an Encyclopedia App

Make an Encyclopedia App

Coding Challenge 2

This challenge will help you earn points in the Demo video section of the rubric.

In this challenge, you will...

  • Apply what you have learned about lists
  • Create an encyclopedia app

Key Terms

  • Encyclopedia - A book where you can look up information about a subject
  • Start Value - In App Inventor, this is information that you can pass from one screen to another.

Challenge: Make an Encyclopedia App

Create an app that helps the user learn about any topic you want. It could be famous people, popular movies, famous places, upcoming events, or anything else. Choose 3-6 examples of that topic and show their names on one screen. (For example, you could display a list of the names of women scientists.) When the user clicks on one of the names, your app should give them more information about it.


Welcome to your second coding challenge! This is a checkpoint for you to practice what you have learned so far. we recommend you solve this challenge in App Inventor, Thunkable, Java, or Swift, but you can solve it using the language you are using for your Technovation project

Below are the instructions highlight one way to solve it in App Inventor and in Thunkable.

Here is an example solution to help you get inspired:

Activity: Write Pseudocode

Before you start coding, try to write out some pseudocode to describe what you want your app to do. Here’s our example that we wrote out before creating our solution:

  • When the user opens the app, there will be a list of women inventors
  • When the user clicks on one of the women inventors in the list, the app takes them to a new screen
  • On the new screen, there is information about the inventor, her name and a description of her life.
  • When the users clicks “back,” the app goes back to the main list of women inventors

App Inventor Solution

Here’s a video tutorial made by Technovation alumni Jennifer. 

 

Written out Instructions

Thunkable Solution

 

Written out Instructions

Reflection

Congratulations on completing your second code challenge!

  • Can you suggest any improvements that could be made to the encyclopedia app that would make it more fun and useful?
  • How would you change your app if you wanted to also show a picture of each woman inventor along with her description?

 

Additional Resources

Debugging

If you cannot get your app to work correctly, you might have what is called a bug. A bug is just an error that you need to fix. Debugging is the process of finding and fixing that error. If  you want some debugging tips to help you find errors, check out Coding 14 - Debugging your App from Week 10.

Start Values in App Inventor

Each time you create a new screen in App Inventor, it is like starting a new app. Each screen runs independently and can’t access information that is on other screens. This means that the global variables in Screen 1 won’t be available in Screen 2. In order to pass information between screens you will need to use the open a new screen with start value block.

Coding 6: Lists

Lists

Coding 6

This lesson will help you earn points in the rubric lines for the Demo Video.

In this lesson, you will learn...

  • How to organize data into lists
  • How to use lists in an app

Key Terms

  • Lists - a way to organize multiple pieces of data in App Inventor and Thunkable
  • Index -  a number that tells you where a piece of data is in a list 
  • Array - common name for lists in programming languages other than App Inventor and Thunkable

Lists and Arrays

As you build your app, you might need a way to organize data and information. Luckily, in computer science, there are ways of organizing data so that you can easily find it and use it.

Can you think of any examples of how you organize information and objects in your life? Here are some examples of things you might do to organize things:

  • Putting a friend’s phone numbers in a contact list
  • Writing your homework down in a planner
  • Creating a grocery list before you go shopping
  • Put clothes in a closet

In App Inventor and Thunkable, you can use something called a list to organize data in your programs. Lists can hold multiple pieces of data and they’re easy to get data from. You may have made a to-do list or a grocery list before, and lists in programming are very similar.

List name: Groceries

  • Apples
  • Bananas
  • Oranges

Lists are really useful for holding a lot of information. Each thing in a list has an index, which is a number that tells you its position in the list. The first item in a list will have an index of 1, the second item in a list will have an index of 2 and so on. Here’s an example:

List name: Groceries

  • Apples (Index = 1)
  • Bananas (Index = 2)
  • Oranges (Index = 3)

Note: In many programming languages, lists are called arrays. and indexes start at 0, not at 1. Make sure to check the rules when learning a new programming language!

 

How to use Lists in App Inventor and Thunkable

In App Inventor and Thunkable, you can go to blocks and select “lists”. List look like this:

App Inventor

Thunkable

Here is how you could make a list of fruits.

App Inventor


Thunkable

Your app understands this information like this:

List Name: Fruits

  • Apples (Index = 1)
  • Bananas (Index = 2)
  • Oranges (Index = 3)

You can get one thing from a list instead of using the whole list. If you wanted to just put the string “bananas” into a textbox instead of the entire list, you would need to tell your app to look at index 2 in this list. Here’s how you would put “bananas” into a label using App Inventor, from the list shown above:

App Inventor

Thunkable

You can also add, remove, and replace things in lists. Let’s say you forgot to add “kiwis” and “grapes” to your fruit list. You could add them like this:

App Inventor

Thunkable

Now your app will see your list like this:

List Name: Fruits

  • Apples (Index = 1)
  • Bananas (Index = 2)
  • Oranges (Index = 3)
  • Kiwis (Index = 4)
  • Grapes (Index = 5)

You should use lists anytime you have multiple pieces of information that you want to include under the same variable name. For example, if you wanted to display the top ten high scores for a game, you could make ten variables with names like HighScore1, HighScore2, HighScore3 and so on until you get to HighScore10.

The easier way to do this would be to make a list called HighScores that contains the ten high scores and then display them by using their indexes. Using a list would also allow you to replace and add more high scores more easily and would save you a lot of time.

 

Activity: Magic 8 Ball

We created an app that is just like a magic 8 ball. You can ask it a question, press ask, and it will give you an answer.

However right now, this app can only respond with “yes”, “no” and “not sure”. You need to finish this app so that the magic 8 ball can also respond with “probably”, “maybe” and “I don’t know”. Download the code to get started!

Bonus

Are you ready to take your magic 8 ball to the next level? Follow this tutorial to learn how to make your magic 8 ball answer a questions when you shake your phone!

Note: In her tutorial, Jennifer makes use of two screens, which works a little bit different than our code. See which solution you like better!

 

Reflection

In this lesson you learned about lists as a way to store and retrieve information.  Next, you’ll need to use lists, variables and functions to complete the second coding challenge!

  • How did you change the magic 8 ball app so that it was able to respond with more answers?
  • How could you include lists in your app?

Additional Resources: ListView and ListPicker Examples

There are two very important user interface components you can use with lists in App Inventor called ListView and List Picker.

ListView

This is a visible component that allows placing a list of text elements in your Screen to display.

You can add elements from to a ListView from a List.

App Inventor

Thunkable

Here is what your app will look like with this code

Your user can select things in your list and you can program your app to do different things. Here is some code that we set up to create a list where the user can remove the items from it.  We created our list as a variable so that we can remove items from it easily.

App Inventor

Thunkable

Here is our app in action! Test it for yourself!

ListPicker  (only available in App Inventor)

The ListPicker is a button that, when clicked on, displays a list of items for the user to choose from.

Here’s how you can add items using a list!

Here is what our app looks like:

 

Just like ListView, you can also let your user select an item and do something with it. Here is some code we wrote. We used a label to display what our user what picks.

Here’s our app in action. Test it for yourself!

Coding 5: Variables

Variables

Coding 5

This lesson will help you earn points in the rubric lines for the Demo Video.

In this lesson, you will learn...

  • What variables are and how to use them

Key Terms

  • Variables - a piece of data that can change
  • Global Variables -  variables that can be used anywhere in your code
  • Local Variables - variables that can only be used inside certain functions

Variables

One of the most important concepts in coding is a variable. A variable is a name for a piece of data that can change. An easy way to remember is that a variable can vary, or change in value.

There’s lots of information that is important to you every day that changes value. Here are some examples:

  • Your age
  • The weather
  • Today’s date

 

Picture a variable as a box that you can store some information inside of and put away. Before you put it away, you put a name on the box to remember what is inside of it. When you need the information you can go find the box get what if inside. You can also change what is inside the box but keep the same name on it.

 

Variables are a way for your app to remember something. Just like the box, your variables will need a couple of things.

  • A name so that your app can find it
  • Some information to store

 

Variables are useful anytime you need your app to “remember” some information and when that information might change. Here are some examples:

  • A player’s score in a game
  • A person’s answer to a quiz question
  • Things that are in someone’s shopping cart

 

Example: How to use variables to store the score in a game in App Inventor

To better understand variables and how to use them, let’s walk through an example. Imagine you are creating a game where the user can earn and lose points. You want the player to be able to see their score, so you put the score into a label. At the start of the game, the player has zero points so you added a block like this to the game.

However, the player’s score will change as she plays the game. Each time she gains or loses points you have to update the text box. When she gets more points, you add a block like this.

That works, but now what about the next time the player earns 10 points?  You’ll have to update the text again to say 20. Then what if the player loses points? You will have to change her score to 15. What if she gains points again? This can get confusing really fast.

In scenarios like this, you can create a variable to keep track of the player’s score. You can create a variable called score that always has the value of the player’s current score. As she plays the game, you can add and subtract points from score and you won’t need to worry about keeping track of what her current score actually is. Here’s how it would work in App Inventor and Thunkable. First you would grab this block from the variables section.

App Inventor

global name

Thunkable

This block tells the app that there will be a variable and asks you to give the variable a name and a value. Here’s what the block would look like for a game where the player’s score started at zero.

App Inventor

global score 0

Thunkable

With this block, you are telling the app that there will be a piece of data called score and that it will change value as the game is played. Every time the app starts up, it is going to create a variable called score and set it zero. Now you can do what’s called “set” and “get” your score variable. “Get” will allow you to see what the value of the score is. Here’s how you would tell your app to display the score in a textbox.

App Inventor

Thunkable

“Set” allows you to assign a new value for your user’s score. Every time the player earns points you can tell the app to do this.

App Inventor

Thunkable

OR

This tells your app to change the value of the score to whatever it is now and add ten to it. If the current score is zero, the new score would be 10. If the current score is 25, the new score would be 35. Now you don’t have to worry about assigning the score every time your player gains or loses points. The app will just take the current score and add 10 to it.

App Inventor

Thunkable

It is okay if you are still confused about variables! They are really hard to understand and the best way to understand them is to practice using them. You will get practice using them in the next few coding lessons and coding challenges.

Activity: Counting App

This is an app that allows you to count by 1, 5 and 10.

However, it is incomplete! The counter can never start over. Fix this app so that you can reset your counter and start over from zero.

Reflection

  • What are other variable that you can identify in your life?
  • How would you use variables in your app?
  • How can variables benefit your app?

Additional Resources: Local and Global Variables (App Inventor) and App, Stored, and Cloud Variables (Thunkable)

App Inventor and Thunkable each treat variables a little differently, so just read the section for whichever platform you are using to code your app.

Local and Global Variables - App inventor

You may have noticed in the section above that the variable block said “global”. There are two types of variables, local variables and global variables. When you create variables, you’ll have to think about whether you want to use the variable at multiple places in your code, such as the score variable from above, or if you want to use it in just one place. 

 

 

 

Global variables can be used anywhere. Like you saw above, the score variable needed to be used multiple times. You had to use it when the player earned points, when the player lost points, and to display it in the textbox. It could also be used for a high-score table. You can never reuse a name when using a global variable. If you did, your app won’t know which variable to use. Luckily App Inventor won’t allow you to create two variables with the same name.  If you’re in doubt of which variable type to use, use global. One thing to remember is that each screen in App Inventor has to have its own variables. A global variable can be accessed anywhere within a screen.

getting global variables

 

Local variables can only be used at one spot in your code. If you need a variable to keep track of something in just one place, use a local variable.  For example, you might want to use a variable just for a Button.Click event, or inside a procedure that you have made. The local variable will only be able to be used inside the “local variable” block and App Inventor won’t let you use it outside of it. Unlike global variables, you can reuse the names of local variables.setting local variables

 

In the coding challenge, you’ll see examples of when to use global variables and when to use local variables. To learn more about global and local variables visit MIT’s website: Global and Local Variables.

 

App, Stored, and Cloud Variables - Thunkable

Thunkable treats variables differently than App Inventor. It has three categories of variables.

 

App variables

...are similar to global variables in App Inventor. They can be used anywhere in the app, and on any screen. Like you saw above, the score variable needed to be used multiple times. You had to use it when the player earned points, when the player lost points, and to display it in the textbox. It could also be used for a high-score table.

You can never reuse a name when using a global variable. If you did, your app won’t know which variable to use. Luckily Thunkable  won’t allow you to create two variables with the same name.  If you’re in doubt of which variable type to use, use an app variable.

Stored variables

...allow you to store a variable on your device. When you close an app on your device, all variables are wiped from the memory of the device. So the next time you open the app, the variable is recreated. That is why you add a variable to your app using the initialize variable block. It initializes the variable to whatever starting value you give it.

Stored variables do not get wiped when you close the app. It stores the current value on the device, and when you reopen the app, it retrieves the value. Note that the initialize block for stored variables does not require a starting or initial value. The initial value is retrieved from the device. Of course, if it is the first time you are running the app, you will need to set the value for the variable somewhere in your app.

Cloud variables

...are similar to stored variables, except the variables are stored in the cloud. To use cloud variables, you will have to add a Firebase component to your app. Your cloud variables will be stored in the Firebase database. When the user closes and reopens the app, the current value of the variable will be retrieved from Firebase.

 

 

 

For more information on Thunkables different variable types, visit the Thunkable website, Variables.

Coding 4: Data and Functions

Data and Functions

Coding 4

This lesson will help you earn points in the Demo video portion of the rubric.

In this lesson, you will learn...

  • Learn what data is 
  • Learn about different functions that you can use in Thunkable and in App Inventor

Key Terms

  • Data - information that your app can understand and use
  • String - a type of data that uses characters
  • Function - is a block of code that does a specific task
  • Output -  information that comes out of a function
  • Properties -  attributes that describe different components in your app
  • Number - a type data that is a number
  • Boolean - a type of data that is can be one of two values, true or false
  • Input -  information that goes into a function
  • Components - Parts of your app 

Data and Functions

So far you have learned that in order to make your app do things, you need to tell it when it should do things. For mobile apps, you tell your app to do things when an event happens. But how do you know what types of things you can tell your app to do? In order to get a computer to do something, you need to tell it to do it in a way it understands.

At some point in your life, you’ve probably heard the word data. Data can mean a lot of things, but in computer science, data is the information that your app can understand and can use. You should know about three basic types of data you will use in this lesson:

Numbers - this is a type data that is a number.

Strings -  a type of data that uses characters. You can think of strings as being text, such as the words “hello” and “world”.

Booleans - a type of information that is can be one of two values, true or false. True basically means “yes” and false basically means “no”

Functions

You can tell your app  what to do using something called a function or procedure (in Thunkable it is called a function; in App Inventor it is called a procedure. They are the same thing). A function is a block of code that does a specific task. Functions take an input and give you an output. The input is the information that goes into a function and the output is the information that comes out of a function.

Let’s take a look at some functions or procedures that you can use in App Inventor and Thunkable.

 

Math functions

Math functions take numbers, do some math on them, and then give you the answer. There are lots of different math functions that you can use. Here are some examples:

Function Input Output Examples
Adding Two or more numbers The sum of those numbers  

Subtracting Two numbers The difference of those numbers
Multiplying Two or more numbers The product of those numbers
Random integer Two numbers A random number that is between those two numbers

Examples of when you might use something like this:

  • Keeping a score in a game
  • Counting
  • Adding money and subtracting the money from someone’s balance in their bank account

Text functions

A string is a type of information that uses characters. You can think of strings as being text, such as the words “hello” and “world”.

There are also lots of functions that use text. Here are some examples.

Function Input Output Examples
Join Two or more strings Two strings put together  

Length One string The number of characters in that string

Examples of when you might use something like this:

  • Displaying words on the screen
  • Checking to see if that someone is how long a password is
  • Checking to make sure someone is using the correct password

Functions of Components

Some user interface components in App Inventor and Thunkable have functions that can be used with them. These functions can perform an action associated with the component. For example, the Sound component can Play, Pause, Resume and Stop.  The Camera component can TakePicture (App Inventor) or take photo (Thunkable). All function or procedure blocks are purple and denote action. Some components do not have any functions associated with them. For example, the Label component does not “do” anything, so it does not have any functions associated with it. 

Activity: Using Image Properties

Go back to the  image gallery you made in coding challenge 1. Using the properties of your image, create a way for no image to be displayed when you click a button labeled “none”.

Hint: you will need to use the boolean blocks “true” and “false”.

 

Check out how we solved it!

Need help? Check out out this tutorial that creates a slideshow, but also gives the user the ability to show “no picture” on their screen.

If you didn’t do Coding Challenge 1 go back to do it now!

Reflection

In this lesson you learned about how to write functions and how to use the properties of different components to make your app do different things.

  • What property of your image did you use in the activity?
  • Can you think of anything you learned in this lesson that you want to use in your app?

Additional Resources

Debugging

If you cannot get your app to work correctly, you might have what is called a bug. A bug is just an error that you need to fix. Debugging is the process of finding and fixing that error. If  you want some debugging tips to help you find errors, check out Coding 14 - Debugging your App from Week 10.

Coding Challenge 1: Make an Image Gallery

Build an Image Gallery

Coding Challenge 1

This challenge will help you earn points in the technical portion of the Demo video in the rubric.

To complete this challenge, you will...

  • Use what you have learned about event handlers and user interface
  • Create your own image gallery app

Key Terms

  • Pseudocode - writing out an algorithm in plain language, instead of in code

Challenge: Make an Image Gallery

Create an app that allows someone to view at least three different pictures. The app should have a "gallery" feel, so the user should be able to view each picture, one at a time.


 

Welcome to your first coding challenge! This is a checkpoint for you to practice what you have learned so far. We recommend you try solving this challenge with App Inventor, Thunkable, Swift, or Java (as those some of the languages you can submit to our competition in)! Below are the instructions that highlight App Inventor and Thunkable.

Here are different solutions to help you get inspired!

Activity: Write Pseudocode

Before you start coding, it will be helpful to write out some pseudocode to describe what  you want your app to do. Remember that pseudocode is  writing out an algorithm in plain language, instead of in code. Here’s an example that we wrote out before creating our solution.

  • There will be 3 buttons on the screen
  • When a button is clicked, an image appears
  • When another button is clicked, a different image appears

One Possible Solution - App Inventor

If you're getting stuck, you can take a peek at the solution here. Give it a shot before you look though!

One Possible Solution - Thunkable

If you're getting stuck, you can take a peek at the solution here. Give it a shot before you look though!

Reflection

You just completed your first coding challenge! Here are three reflection questions for you to consider with your team.

  • Can you suggest any improvements that could be made to slideshow app that would make it more fun and useful?
  • How might you redesign this app for a user that did not have the ability to touch a button?
  • Is it possible to add a picture to your slideshow by taking a picture with the phone’s camera? What App Inventor programming features would you need? How do you learn to go build that into your app?  

Hint: Do a google search and share with your team what you discover.

Additional Resources

Motivation

See what past Technovation participants have to say about their coding experience. Learn how they overcame challenges along the way.



Debugging

If you cannot get your app to work correctly, you might have what is called a bug. A bug is just an error that you need to fix. Debugging is the process of finding and fixing that error. If  you want some debugging tips to help you find errors, check out Coding 14 - Debugging your App from Week 10.

Using Multiple Screens in App Inventor

You may have noticed that the App Inventor solution does not rely on creating multiple screens. App Inventor makes it easy to add more screens to an app, but you’ll need to be cautious about adding too many screens. This is because using a lot of screens in App Inventor uses a lot of memory. Once you create more than 10 screens, it is possible that your app won’t work anymore.

Instead of adding more screens, you should find parts of your user interface that you can reuse, just like the solution to this code challenge. Keep this in mind when designing your app. You will also get to see more examples of how to reuse parts of your user interface in the other code challenges.