How to use Control Flow (Conditionals & Loops) in Julia | Tutorial 5 of 13 | Julia for Beginners

Oct 11, 2020 14:23 · 4548 words · 22 minute read whatever j concept two kinds

Welcome to Julia for Talented Amateurs where I make wholesome Julia tutorials for talented amateurs everywhere. I am your host, the Dabbling Doggo. I dabble Last week we learned about the different Data Structures in Julia: Dictionaries, Tuples, Named Tuples and Arrays. Until now we’ve been learning the basics and creating everything manually. Starting today we will begin to create things programmatically which will allow us to automate some of our tasks. The first step towards automation is to learn about Control Flow.

Control Flow is the order in which program instructions 00:32 - are executed. There are several ways programming languages allow this but the two that I will be discussing in this tutorial are Conditionals and Loops. A Conditional looks at a Boolean expression and evaluates whether it’s true or false. Depending on the result the program will perform a different set of instructions depending on whether the expression is true or false. It’s like coming to a fork in the road and then deciding to go either left or right based on a certain condition.

00:57 - A Loop is a set of instructions that is specified once but may be carried out multiple times in succession. Using a Loop allows the programmer to automate mundane, repetitive tasks on a massive scale. We’re going to learn about Control Flow primarily by looking at a lot of different examples so let’s get right into Atom. Double-click on the Atom icon to launch Atom. Before you start up Julia look at the bottom right corner. You may have noticed in the last few tutorials that there is an update notification in the lower right corner of my Atom screen.

If you don’t see an update notification 01:29 - don’t worry about it. It means you’re using the latest versions of everything. However, if you started this tutorial series with me back in September you may see this update notification from Atom. If you do see it click on it to begin the update process. Click on “Update All.” Click “Restart” to relaunch Atom. After it relaunches, close Atom. As long as we’re updating Atom we should check to see if we need to update Julia. Open up your browser and go to julialang.org.

02:03 - Notice the green box states “Download version 1.5.2.” Click on that. You’ll notice that version 1.5.2 was released on September 23rd which is after this tutorial series started. We’re using version 1.5.1 so do we need to update? There are three numbers in Julia’s version numbering system. That last digit is the least significant. A change from version 1.5.1 to 1.5.2 indicates a minor change between versions so updating is not necessary. This may happen every month or every other month.

A change to the middle number indicates a more significant change 02:41 - so updating is recommended at that time. Version 1.0 was released in the Fall of 2018. As of this recording it’s the Fall of 2020 and we’re on version 1.5 so you can see that the middle number only changes a few times per year. Although updating is not required let’s go ahead and update Julia so I can show you the updating process. Find your operating system and click on it to begin the download. I’m using the 64-bit installer for Windows.

03:08 - Once the download is complete click on the link in the lower left corner to begin the installation process. Remember to note the directory location of where your files are being installed. Click on “Next” to install. Click “Next.” Click “Finish” when complete. You should have two Julia REPL shortcuts on your desktop now – one for version 1.5.1 and another one for version 1.5.2. You can delete the shortcut for version 1.5.1 now. Refresh your desktop. Double-click on the shortcut for version 1.5.2. Go to the top bar and right-click to select Properties.

Under the Options tab select the large cursor size. Under the Font tab select 28 or whatever setting you like. Click “OK.” In the REPL notice that version 1.5.2 is now showing. Type in println(“Hello, World!”). Type in 1 + 1. Type in exit(). Double-click on the Atom shortcut to relaunch Atom. Don’t start Julia yet. Go to File, Settings. Go to Packages. Go to Julia Client Settings. In the black box under Julia path change 1.5.1 to 1.5.2. Click anywhere outside the box. Close the Setting tab. Click anywhere in the REPL panel. Hit Enter to launch Julia. It may take a few minutes. Notice that the REPL now shows version 1.5.2. Type in println(“Hello, World!”). Type in 1 + 1. Type in exit(). Close Atom. Double-click on the Atom shortcut again. Adjust the side panels. Click in the REPL panel. Hit Enter. And you should be good to go. Now back to the show! Conditionals are also known as Branching.

In fact, both are very descriptive of how this Control 05:33 - Flow works. A Conditional evaluates a Boolean expression and determines whether it’s true or false. Depending on the result the program will then branch in one direction or another which allows the programmer the ability to give a different set of instructions to those expressions evaluating as true versus those expressions evaluating as false. Conditionals are implemented by using an if…end block. Some variations to the if…end block include the if…else…end block and the if…elseif…else…end block. Let’s take a look at a couple of examples. This initializes the variables x and y. In this example x is less than y so the program chose the second branch which told it to print 1 is less than 2.

Let’s swap the variable values using the 06:37 - Tuple method that we learned in the last tutorial and rerun the code. You can use the up arrow to bring up the code rather than retyping it. Since x is now greater than y the program chose the first branch which told it to print 2 is greater than 1. Now let’s set x and y equal to each other and rerun the code. Since x is not greater than y and x is not less than y the program chose the third branch which told it to print that 1 is equal to 1.

07:08 - In computing a Ternary operator is an operator that takes three arguments. Julia allows for the use of the question mark…colon Ternary operator sometimes called a Conditional operator. It’s a shorthand version of the Conditional control flow that we just learned. A Ternary operator uses the general format “a question mark b colon c”. In this format a is a Boolean expression that is to be evaluated. b and c are separate instructions to be executed forming two branches. If a is true then b is executed. If a is false then c is executed. Let’s reinitialize the variables x and y and take a look at an example. Spacing is very important here. Be sure to leave spaces between the question mark and the colon. This is read “Is x greater than y?” If true then print x is greater than y.

If false 08:12 - then print x is less than or equal to y. For that last part I used the Unicode character for “less than or equal to” which is entered “backslash le tab”. Because x is not greater than y the program chose the second branch which told it to print 1 is less than or equal to 2. Let’s swap the variable values and rerun the code. Because x is now greater than y the program chose the first branch which told it to print 2 is greater than 1.

Finally let’s set x and y equal to each other and rerun the code. In this case there is no third branch so the program chose the second branch which told it to print that 1 is less than or equal to 1. Pretty neat, right? A Loop is a set of instructions that is specified once but may be carried out multiple times in succession. We will be covering two categories of Loops: 1) the While Loop and 2) the For Loop. A While Loop allows code to be executed repeatedly based on a given Boolean condition.

While Loops 09:23 - are generally used when the number of iterations is unclear to the programmer so the code repeatedly evaluates the Boolean expression to evaluate whether or not the condition has been met. Once the condition has been met the While Loop ends and the program continues to the next step. A While Loop is constructed using a while…end block and it’s made of two parts: 1) a header, specifying the Boolean expression to evaluate and 2) a body, which is executed once per iteration. While Loops require the use of an external counter. The convention is to use the variable lowercase-i as the counter, although any variable name may be used. Here’s an example of a While Loop.

10:09 - Recall that i += 1 is the same as i = i + 1. This example introduces the concept of Scope of Variables. According to the Julia documentation the Scope of a variable is the region of code within which a variable is visible. There are two kinds of Scope: Global and Local. The Julia documentation goes into a lot of detail about the different classifications of Scope and how they are used within Julia. However, in practical terms the Global Scope is anything that shows up in your Workspace panel. When you create a Loop the variables included within that Loop are considered Local variables. They are treated as temporary variables that are used during the Loop and then discarded once the Loop has completed. If you just want to refer to the value of a variable in the Global Scope within the body of your Loop, there’s no problem with doing that. The problem starts if you want to change the value of a Global variable from within the body of your Loop, as in the case with i += 1.

11:10 - Because changing the value of a Global variable can have unintended consequences, altering the value of a Global variable from within your Loop is not encouraged. The designers of Julia have implemented a safety measure to ensure that if a programmer wants to change the value of a Global variable, they need to be explicit when doing so by using the keyword “global”. Notice in the Workspace panel that the value of i, which was initially set at 1, has now changed to 11. Here’s another example of a While Loop. This is an example of an Infinite Loop. Since i will always be greater than or equal to 1 this Loop will never stop repeating. In order to stop this program, hit ctrl-c to abort. Be careful when using While Loops.

Julia will not warn you when you’re about to create an Infinite Loop. As you just saw ctrl-c means abort in Julia. You may be used to ctrl-c and ctrl-v for copy and paste. This does not exist in Julia and neither does ctrl-z for undo. You can combine Control Flow blocks by including them within other Control Flow blocks. In computing this is called Nesting. This is an example of a While Loop with a Nested Conditional. Using the keyword “break” in the Loop body will break out of a Loop immediately. This next example comes from Dr. Ana Bell at MIT. I just took her Python code and converted it into Julia code. If you watch her lecture series you’ll be surprised by how similar the Python code looks compared to Julia code. This is an example of an Infinite Loop with a built-in escape.

12:56 - This example is from an old video game where the character can only go left or right. As long as the character keeps going right then the character is stuck in an Infinite Loop, or in the Lost Forest. In order to escape the Loop the character must go left. Actually, you could have typed in anything other than right in order to escape the program. Before we begin the next section type and exit to begin a new Julia session. A For Loop repeats code for a specified number of iterations. Unlike the While Loop, which continually evaluates a Boolean to determine whether or not it should repeat, the For Loop is told explicitly how many times it is to repeat. Once the number of iterations has been reached, the For Loop ends. Here’s an example of a For Loop. A For Loop is constructed using the for…end block. A For Loop is made up of two parts: 1) a header, specifying the iteration and 2) a body, which is executed once per iteration. In this example the header is “for i in 1 to 10”, meaning repeat the loop 10 times. The body is “println(i)”. Now try typing in i.

14:09 - You get an error because i is a temporary variable that exists only within the body of the Loop. It does not show up in the Global Scope since it was used Locally in the body of the Loop and then discarded. Notice that i does not appear in the Workspace panel. As we have seen in the previous tutorials, the colon in between numbers signifies a range of values. When using For Loops you are not limited to just one to ten. Here are some examples to get practice using different ranges of values. This iterates from 5 to 15. You can use negative numbers as well. This iterates from negative 10 to positive 10. You can skip numbers in a range. This iterates from 5 to 11 in increments of 2. You can count backwards. This iterates down from 10 to 1. You can use Characters as an iterator. Note that you do not have to use the variable name i. You can select any variable name. You can skip Characters in a range just like with Integers. This iterates from Characters ‘a’ to ‘z’ but skips every other Character.

15:18 - You can use Characters in descending order just like with Integers. You can use Unicode Characters as an iterator. Here’s how you can display a list of the ASCII characters along with their ASCII number. When using For Loops you are not limited to using Integers and Characters as iterators. You can use Data Structures as well. In this next section we’ll use the contents of Dictionaries, Tuples and Arrays as the iterator. Let’s set up a Dictionary for this example. You can use the contents of a Dictionary as the iterator in a For Loop. You can populate an empty Dictionary using a For Loop. Let’s set up an empty Dictionary for this example. Notice that the For Loop does not return anything so you have to type in the name of the Dictionary to view it – or you can view it in the Workspace panel. This created a Dictionary with integers 1 to 10 as the Keys and the integers-squared as the Values.

As you can see, using a For Loop 16:53 - to construct a Dictionary was a lot faster than trying to type all of this in manually. Like a Dictionary you can use the contents of a Tuple as an iterator in a For Loop. Let’s set up a Tuple for this example. Because Tupals are immutable you cannot use a For Loop to populate an empty Tuple. Like Dictionaries and Tuples, you can use the contents of an Array as an iterator in a For Loop. Let’s set up an Array for this example. You can populate an empty Array by using the push-bang function within a For Loop body. Let’s set up an empty Array for this example.

17:44 - Notice again that the For Loop did not return anything so you have to type in the name of the Array to view it – or you can view it in the Workspace panel. This next example is a rather famous example of a For Loop with a Nested Conditional. FizzBuzz is the name of a children’s game used in math class to teach division. Players take turns counting up from 1. If a number is divisible by 3 then the player says “Fizz”. If a number is divisible by 5 then the player says “Buzz”. If a number is divisible by 3 and 5, or 15, then the player says “FizzBuzz”. Over the years this game has become a staple in computer programming classes as well. Let’s take a look at how to write FizzBuzz in Julia. There are a lot of lessons in this little example. It uses a For Loop. It uses a Nested Conditional. It uses the Remainder Operator. It uses the Equality Test. It uses the Boolean AND. It uses the println() function. Also note that the sequence in the Conditional block is important.

19:16 - For example, if the first condition evaluated was “i modulo 3” the program would print “Fizz” for 15 and not “FizzBuzz”. Let’s try to see what happens. Using the hashtag sign turns those lines into comments. Notice that 15 shows up as “Fizz” and not “FizzBuzz” so these conditions are evaluated in sequence and not as a whole. For such a simple example there are a lot of lessons to be learned here. You can see why FizzBuzz is such a well-known example regardless of the programming language. Here’s an example of a For Loop with a Nested For Loop. Let’s begin by initializing some variables and initializing an Array filled with zeros. Again the For Loop does not return anything so you need to type in the name of your Array in order to view it – or you can view it in the Workspace panel. This example created an addition table for the integers 1 to 5. Let’s take a look at a diagram that shows the sequence of steps that it used to create this table.

The first For Loop is called 20:36 - the Outer Loop and the Nested, second Loop is called the Inner Loop. In this example the Outer Loop is being used to index the rows and the Inner Loop is being used to index the columns. So when i equals 1 the Inner Loop populates all of the columns in row 1 and then it ends. This allows the Outer Loop to continue to i equals 2 which triggers the Inner Loop to go back to work and populate all the columns in row 2 and then it ends again – and so on until the Outer Loop has completed all of its iterations. When using For Loops with a Nested For Loop the convention is to use lowercase-i as the iterator for the Outer Loop and to use lowercase-j as the iterator for the Inner Loop, although you can use any variable names for the iterators.

21:20 - This next example will give you the same result as the previous example. However, it does it with fewer keystrokes because it uses something called Syntactic Sugar. Syntactic Sugar is allowed at Julia as a way to enter code with fewer keystrokes. However, it does not have any impact on your code’s performance. For example, code written in long-hand form will perform just as quickly as code written with Syntactic Sugar. We’ll learn more about this when we take a look under the hood of Julia later in this tutorial series. For now, let’s reinitialize the variables x and y and set up a new array B filled with zeros. In this example i is the Outer Loop and j is the Inner Loop – they just happen to be on the same line, separated by a comma. You can see in the Workspace panel that arrays A and B are identical. When using the Syntactic Sugar this is called a Double Loop rather than a Nested Loop.

22:15 - This next example is the same as the previous two examples but it takes Syntactic Sugar to another level. This format is called a Comprehension. We’ll see more examples of Comprehensions in a few minutes. However, for now, just note that using this format resulted in the same Array as the previous two examples but it did so by using just one line of code. This next example is a good way to visualize how a For Loop with a Nested For Loop works. This code calculates and displays all of the possible combinations rolling two dice.

The first column 22:55 - displays the counter from 1 to 36, showing that there are 36 combinations of rolling two dice. The second column displays d1, or the Outer Loop. The third column displays d2, or the Inner Loop. The fourth column is the sum of the two dice roll. You can see in the second column that d1 only cycles once from 1 to 6. You can see in the third column that d2 cycles from 1 to 6, six times. The more Nested Loops you add, the more the complexity of your program grows. Nested Loops can be useful but don’t get carried away. This next example shows a For Loop with a Nested For Loop with a Nested Conditional with a Nested Ternary. This code calculates and displays all the possible two dice rolls where the sum is divisible by 3. The first column displays the counter from 1 to 12, showing there are 12 combinations of rolling two dice where the sum is divisible by 3. The second column displays d1, or the Outer Loop.

24:06 - The third column displays d2, or the Inner Loop. And the fourth combination displays the sum of the two dice roll. As you can see, there are lots of ways to combine Loops and Conditionals. As we discussed in the last tutorial, Strings are a collection of Characters, so Strings can be indexed like a Tuple or an Array. You’ll be happy to learn that you can iterate over Strings in a For Loop just like Tuples and Arrays. Before looking at some examples type in exit to start a new Julia session. Let’s use our old friend “Hello, World!” for this example. You can see that it iterates over the String just like a Tuple or an Array. This example shows a For Loop with a Nested Conditional to evaluate the Characters in your String. Because “Hello, World!” contains an ‘e’ it printed the line. This next example comes from Dr. Ana Bell at MIT.

All I did was convert her Python code into Julia 25:15 - code. This was an example of a Conditional with a Nested For Loop with another Nested For Loop with a Nested Conditional iterating over two different Strings. This is another example from Dr. Ana Bell at MIT. It’s a little longer than the other examples so I’m going to speed up the typing, but stick around to the end because the payoff will be worth it. It’s called “The Robot Cheerleader.” I’m going to use “Julia” but you can type in whatever you like. I’m going to use “5” for my Enthusiasm Level but you can use whatever you like.

26:40 - Pretty cool, right? It looks complicated but if you look closely at the code you’ll realize that you’ve seen everything in there, with the exception of the sleep() function. The sleep() function pauses your program in seconds. Otherwise, everything else should look familiar to you. Pause the video and type in the code yourself. You’ll be surprised to learn just how much you know. Before we conclude I want to revisit Comprehensions that I introduced earlier in this tutorial. Type in exit to start another Julia session. Julia supports the use of simple For Loops to construct Arrays and Dictionaries. For Array Comprehensions, the general format is to use square brackets like any other Array. Within the Array enter the body of the Loop first and then enter the header of the Loop immediately following it. For Dictionary Comprehensions, the general format is similar but you use the Dict() dictionary constructor rather than using the square brackets. Let’s take a look at some examples. This constructs a 1-dimensional Array with the Integers 1 to 5.

27:51 - This binds the 1-dimensional Array to a variable named “data”. This constructs a 1-dimensional Array with 1 to 5-squared and binds it to the variable named “data”. This constructs a 2-dimensional Array with i as the Outer Loop and j as the Inner Loop. In this example i is the row and j is the column. This constructs a 1-dimensional Array of the odd numbers between 1 and 10. This constructs a 2-dimensional Array with 10 rows and 3 columns.

The columns are constructed by the three separate Comprehensions 28:36 - and then horizontally concatenated using a blank space in between. This constructs a Dictionary of odd numbers between 1 to 10 as Values and uses the String version of those odd numbers as the Key. The benefit of using Comprehensions is that you can generate an Array or a Dictionary very quickly without having to set up an empty Array or empty Dictionary ahead of time. Recall earlier in this tutorial when we used For Loops to populate Arrays we had to set up an Array filled with zeros before we could use a For Loop to mutate it. The condensed format of the Comprehension may be a little confusing at first but just remember they are just compact versions of For Loops combined with a constructor syntax for Arrays and Dictionaries.

29:23 - Finally here’s a fun and frivolous example to wrap everything up. Remember the printstyled() function that allows you to print Strings in different colors? Let’s use what we’ve learned today to programmatically cycle through the different colors. Type in exit to start a new Julia session. Let’s use “Hello, World!” for this example but type in “backslash n” at the end. These are the available colors. oh Thank you, thank you…I’m here all week! Wasn’t that interesting? Today we learned about Control Flow, specifically Conditionals and Loops. Conditionals change the flow of the program based on whether a Boolean expression evaluates as true or false. Loops are a form of automation.

While Loops are best when the number of iterations is 30:30 - not known ahead of time. For Loops are best when the number of iterations is known beforehand. For reinforcement, we practiced coding with lots of different examples. Next week, we’ll tackle functions, which will pull everything together. You’ll learn to create your own custom functions. If you enjoyed this video and you feel like you learned something new, please give it a thumbs up. For more wholesome Julia tutorials, please be sure to subscribe and hit that bell. If you have any questions, please post them in the comments below. Feel free to spread the word by sharing this video since I’m sure you’ll all agree that this is the finest tutorial on all of YouTube. Worst. Tutorial. Ever .