Getting Familiar With Loops In Julia | by Emmett Boudreau | Towards Data Science

Github repo
Notebook
If one seeks to further their skills in software engineering, it can be rather difficult to learn just by viewing. Even if all of the concepts within literature or multimedia are well-understood, it could be quite difficult to learn without actually creating the code and seeing how the code interacts with the data. Around fifteen years ago, I dove into the beautiful language of C++. In order to learn C++, I would spend hours researching and copy-pasting code in order to find out what it does. The problem is that I wasn’t writing the code myself, even if it was copied directly.
To be clear — I am not saying that copy and pasting code is a bad thing, I copy and paste snippets all the time from my previous notebooks, my current project, or even the world wide web. However, a lot of engineering is about learning how to learn. Part of this is knowing when to copy and paste as opposed to when you need to study the material further. In my C++ example, I can remember using things like the STD library and using operators like <<, but not realizing that those were operators and thinking they were just random symbols because I didn’t know what they did put a significant hole in the approach-ability of C++.
Interestingly, with all of the languages on Earth, I had never really had an interest in Python until about three years ago. While yes — it certainly was a lot easier to learn than C++, I found a lot of the differences to be appalling. Regardless of how easy the language might be compared to its ancestor, I found myself falling into a trap of moving huge blocks of code from Google that I didn’t really understand, and that hindered my learning ability in this new language.
All of this evidence is presented to back up a single claim:
If you want to learn programming, you need to write code.
I had a mentor who referenced a book called “ Learn Python The Hard Way” by Zed Shaw. The ideas in this book reflect the importance of what I discussed, and really opened my eyes to how much easier education is whenever interaction is involved. I consider myself a visual learner, as well, so to me, this could apply across the board with anyone trying to learn in terms of computer programming.
With these ideas in mind, I thought that if I was going to provide concrete and adequate tutorials that will take one from an absolute beginner to an absolute professional, then I should certainly include resources for the students to learn with themselves. An empty copy of the notebook is now provided in the Github repo, and I insist that newer programmers type the code themselves!
Within the world of programming, there a few different operations that a developer can use to work with data. The two operations that are most commonly used are looping and conditionals. Looping is a programming technique that allows for not only the examination, comparison, and computation of elements inside of types, but also is the base of a program itself.
There are three main types of loops used in programming, with some unique applications pertaining to specific languages, such as syntactical looping for Julia. In Julia, we have the following loop applications at our disposal:
Iterative Looping
While Looping
Recursive Looping
Syntactical Looping
That being said, syntactical looping still uses an iterator, only using syntactical expressions alongside it to make a faster loop with more expression — so is still iteration.
Let’s take a look at an iterative loop. Iterative loops are different from recursive and while loops in that they need dims to loop over. An example of a type that will contain such dims is an array. In the example of an array, we can loop through each element continuously one by one using an iterative loop. This can also be done using a generator type, which is just a type that is able to create types out of itself. A basic example of this is a range, where the range type generates an array of dims found in between the given bounds of the range. In this example, we will loop through a generated array of all integers between 10 and 20:
for number in 10:20    println(number)end
A while loop will take a bool type, which is a conditional that will read either true or false, and use it as a break for the loop. Whenever the provided condition is not met, the loop will stop. While loops are actually the basis for most applications that are ran on a machine. This is because they can perform tasks at every tick consistently so long as you want those tasks performed. To create a while loop, we will, of course, use the key-word “ while,” followed by a condition.
# while loopnumber = 1while number <= 5    number += 1    print(number)end
Another thing to look at is the ability to break a loop. This is usually done with conditions, but it done using the key-word “ break.” For example, while the loop above will print each number between 1 and 6, if we were to break it, we would get no prints at all.
# while loopnumber = 1while number <= 5    break    number += 1    print(number)end
Finally, there are recursive loops. Recursion and when to use it is an entirely different discussion. In general, recursion kills performance, however, there are a lot of functional algorithms that are the foundation of modern computing that utilize recursion. That being said, there are some great uses for recursion where iteration and while looping cannot get the job done. The calculation of a factorial is a perfect example of a reasonable application of recursion for scientific, high-level computing. Most recursive algorithms are going to use a condition to determine as to whether or not a loop should be broken with a return. The first thing we are going to do in our factorial function is check if the number we want the factorial of is 1. If this were to be the case, the factorial of 1 is of course just one, so we will return 1.
function fact(n)    if n == 1        return(1)
This will break our loop. A great way to think about recursive looping is to imagine that the function itself is both the loop and the initialization of the loop. Next, we are going to multiply the number by the factorial of itself minus one. This is by nature mathematically very recursive, so it makes sense that an application in computing would be recursive, as well.
else        return n * fact(n-1)
This function is going to be calling itself whenever this else condition is met. If n-1 is not equal to 1, then it will be calling itself again — and that is what recursion is. Here is our final result:
function fact(n)    if n == 1        return(1)    else        return n * fact(n-1)    endend
Fun fact:
Julia’s base factorial function, factorial() actually does not use recursion to calculate factorials. Instead, it uses a lookup table to match values to corresponding factorial. This means that values above a number, which is 22 in Julia’s example aren’t able to be calculated. While that might be a negative, it also means that operations with numbers less than 22 are a lot faster than they would be otherwise.
A zip loop is a great tool that can be whenever you want to loop through multiple arrays at the same time. This is useful for both thresholds and comparing or manipulating values across arrays. The zip syntax in Julia is a little different to most languages, so it is important to ensure that you put apply the proper syntax, using zip as a method and your two dims as a pair.
array2 = [30, 40, 50, 60]for (i, w) in zip(array, array2)    println(i, w)end
Now that we have a solid foundational knowledge of loops, conditionals, and functions, let’s combine all of those skills together.
newarray = []for element in array    if element == 10        append!(newarray, element)    elseif element == 20        append!(newarray, element)    endend
In this example, we loop through an array. If it meets the condition of being equal to ten, then we will append it to our new empty array. We will also do the same if the number is both not equal to ten and equal to twenty. However, if it were to be equal to 10 and 20, then it would only run the initial if.
Can you create a function that will go through every letter in the string “ Hello World” and only print a letter if it is an H, W, l, r, o, or D?
The first thing we are going to do is of course define our hello world string variable.
Hello = "hello world"
Next, let’s write a function.
function filterstring(input)
The next step in the approach is going to be looping through each individual char inside of the string. To do this, we can just call the string with a for loop.
for character in input
Next, we need to check if the value is in our list of values that we want to print. Anytime we want to check something, we are likely going to be using a conditional. So for this example, you could use to approaches. One of these will be the rookie approach, and the other will be far simpler. Either create a list of the values that are acceptable and check if the looped element is in that list, or create a condition for each individual char. Either way, the same result is produced, one is just a lot simpler and easier, frankly.
function filterstring(input)    validchars = ['H', 'W', 'l', 'r', 'o', 'd']    for character in input        if character in validchars            print(character)        end    endend
Congratulations! You are on your way to being a great Julia developer. Though things certainly could seem complicated very early on, the bulk of the knowledge you are going to need to obtain, at least initially, is going to be learning more ways to work with data using operators, conditions, types, and loops. While there might be a lot more to learn, the foundational basics of programming in the Julia language have already been gone through in these tutorials.