Flow control

Introduction

With flow control, we try and take control of the path of execution of code in a program. It is like branches in the flow of a river, setting choices for a raft when traveling downstream. Other than a river's free flow, we can set conditions for the raft leading it to take different paths. This river also has loops in it, where the raft can just go around and around. These brances and loops add tremendous power and functionality to a program.

In this lesson, we will take a look at:

  • Ternary operators
  • Boolean switches
  • if-elseif-else-end conditions
  • for-end loops (iterations)
  • Compound expressions
  • while-end loops

Ternary expressions

  • This offers the quickest way to branch off in one direction
  • Look at this example with the tenary operator, ?:

In [ ]:
#Creating avariable called a and placing an integer value in it
a = 10

In [ ]:
#A ternary expression with a binary choice
#Instead of the string output, the program could do something else, such as call a function
a > 10 ? "Yes, it is!" : "No, it's not!"

In [ ]:
a >= 10 ? "Yes, it is!" : "No, it's not!"

In [ ]:
r = 1; s = 2;

In [ ]:
println(r < s ? "It is less!" : "No, it's not!")

In [ ]:
println(r > s ? "It is less!" : "No, it's not!")

Boolean switching

  • Here we make use of the Boolean operators and, denoted by && and or, denoted by ||

In [ ]:
#Julia will evaluate the first part
#If it is true, the second part will be excuted
a = 7
isprime(a) && a == 7

In [ ]:
#In this example the first part is not true and will return a false
a = 9
isprime(a) && a == 9

In [ ]:
#With the || operator the executions stops after the first part is true,
#because only one has to be true
a = 7
isprime(a) || a == 9

In [ ]:
a = 7
a == 9 || isprime(a)

In [ ]:
a = 9
isprime(a) || a == 9

For loop


In [ ]:
#Really self-explanatory
#Iterating through a range of numbers
#for i in 1:5 #1:5 is a range object, useful for iteration
#    println(i)
#end
for i in 1:5
    println(i)
end

In [ ]:
#Iterating through list of strings
for word in ["These", "are", "words"]
    print(word, "\t") #\t is a tab
end

In [ ]:
#Iterating through letters in a  word
for letter in "Julia"
    print(letter, "\t")
end

In [ ]:
#Iterating through stuff in a pair of curly braces
for stuff in {10, 20, "thirty", sqrt(1600)}
    println(stuff, "\t", typeof(stuff))
end

In [ ]:
#Does stuff exist outside the loop?
try
    stuff
    catch ex
    println(typeof(ex))
    showerror(STDOUT, ex)
end

In [ ]:
stuff = "I exist"

In [ ]:
stuff

In [ ]:
#Iterating through stuff in a pair of curly braces, now that stuff exists
for stuff in {10, 20, "thirty", sqrt(1600)}
    println(stuff, "\t", typeof(stuff))
end

In [ ]:
#What is stuff now?
stuff
  • The variable stuff will now contain whatever the last value was
  • By decalring it before the loop, it is explicit (global)

In [ ]:
#For loops inside of for loops
for a in 1:3
    for b in 1:2
        println(a, " and ", b)
    end
end

If-elseif-else-end branching

  • With these we can set a lot of conditions for execution or ignoring

In [ ]:
value = 10

if value < 10
    println("It is less than 10.")
    elseif value > 10
    println("It is more than 10.")
    elseif value == "Ten"
    println("It is ten.")
else
    println("The value is 10.")
end

Combining flow control


In [ ]:
#We can skip some of the iterations in a loop
#Here we place an if-elseif-else-end condition inside of a for loop
for i in 1:10
    if i % 3 == 0
        continue
    end
    println(i) #skipping these lines if i is a multiple of 3
end

Comprehensions

  • Comprehensions are a way of generting an collecting items

In [ ]:
A = [n for n in 1:5]

In [ ]:
#List comprehension
[i^3 for i in -3:3]

In [ ]:
#Creatring an array of integers
typeof([i^3 for i in -2:2])

In [ ]:
#Here, the objects will be of type Any
typeof({i^3 for i in -2:2})

In [ ]:
#Combining iterations in list comprehension
[(row, col) for row in 1:3, col in 1:3]

In [ ]:
#Using the enumerate() function for creating an iterable object that produces
#an index number and its value (at each index)
M = rand(0:9, 3, 3)

In [ ]:
[i for i in enumerate(M)]

In [ ]:
#Breaking out of a for loop
a = rand(1:5, 20) #creating 20 random values, each from 1 to 5
println(a) #print the list of 20 values and then a new line
lookforfirst = 4 #creating a number to search for
for (ix, curr) in enumerate(a)
    if curr == lookforfirst
        println("The index of the first occurrence of the searched value $lookforfirst is $ix.")
        break
    end
end

In [ ]:
#Working through two or more arrays at the same time
for i in zip(1:10, 101:110, 501:510)
    println(i)
end

In [ ]:
#Look at what happens if each one in turn is of different length than the other two
for i in zip(1:4, 11:15, 21:25)
    println(i)
end

In [ ]:
for i in zip(1:5, 11:14, 21:25)
    println(i)
end

In [ ]:
for i in zip(1:5, 11:15, 21:24)
    println(i)
end

Collecting values


In [ ]:
#Creating a range object, which is useful for iterations, i.e. for loop
#In future lesson we will see that [1:5] is an array
1:5

In [ ]:
typeof(1:5)

In [ ]:
[i for i in 1:5]

In [ ]:
collect(1:5)

In [ ]:
#Permutations gives a good example
permutations([1, 2, 3])

In [ ]:
collect(permutations([1, 2, 3]))

Compound expressions

  • This is useful for evaluating a bunch of expressions and returning the value of the last

In [ ]:
#Using begin
b = begin
    x = 10 #value
    y = 40 #value
    x / y #last expression will be returned
end

In [ ]:
#Another format of begin
begin x = 1; y = 4; x / y end #note the semi-colons

In [ ]:
#Not using begin
b = (x = 100; y = 400; x / y)

The while condition

  • Do stuff while something holds

In [ ]:
i = 1

In [ ]:
while i <= 5
    println(i)
    i += 1 #i = i + 1
end

In [ ]:
i

In [ ]: