Quiz 1.7: Scope, loops and conditional statements


Q1: Variables scope

Given the following code snippet:

x = 'a'
for c in "Hello World!"
  x = c
end
x

Which of the following sentences are true (assume a Julia version >= 1.5) ?

RESOLUTION

When the script is run interactively, the x within the for block is the global variable, while when the code is run in a non interactive way x is a new local variable that shadows the global x variable and a warning is provided.

The correct answers are:

  • "When the code is run in an non-interactive mode (e.g. the whole script is on an imported file) a warning is raised"
  • "When the code is run in an interactive mode (e.g. on the REPL) x is now !"
  • "When the code is run in an non-interactive mode (e.g. the whole script is on an imported file) x is now a"

Q2: Nested for loops

Given that the following code snippet:

for i = 2:6
  k = round(Int64,i/2)
  for j = 4:-1:XXX
    println(j)
  end
end

prints the sequence 4,3,2,4,3,4, what is XXX in the code ?


RESOLUTION

The inner loop starts at 4 and then continues in reverse order until it reaches the value of the outer loop, first 2, then 3 and finally 4. For is over 4, the inner loop is never executed. Remember that in a range, in Julia, both the extremes are included.

The correct answer is: i


Q3: Conditional statements

Given that c=10, which of the following statements, taken individually, would lead to v being equal to 100 ?

RESOLUTION

When we test for c >= 10, we obtain something already true and hence the second part (the v assignment) is evaluated only with and end operator (&&), and the converse is true when we check for c < 10 where the second part is evaluated only with an or operator (||).

The correct answers are:

  • v = (c < 10) ? 1 : 100
  • (c >= 10) && (v = 100)
  • (c < 10) || (v = 100)
  • if (c >= 10) v = 100 end