Skip to content

Question 9

What is the output of the following code? [3 marks]

1
2
3
4
5
6
7
a, b, c = 'apple', 'bear', 'carrot'
if a and c:
    a = a[:2] + a[-1]
    c = c[:2] + c[-1]
elif not b:
    b = b[1:]
print(a, b, c)
Solution

Begin with variables a, b and c containing values 'apple', 'bear' and 'carrot' respectively. Immediately, the program flow is greeted with a series of if-else branches:

  • a and c: True and True = True \(\Rightarrow\) enter if block
  • ignore elif branch not b

Inside this if block, variable a is now redefined to be a string concatenation of a[:2] and a[-1]. Here, a[:2] is a substring of a up until before index 2, i.e., 'ap'. a[-1] evaluates to the last character in a, that being 'e'. Hence, we now have a be 'ap' + 'e' ='ape'`.

Variable c is redefined to be a string concatenation of c[:2] and c[-1] as well. Here, c[:2] is a substring of c up until before index 2, i.e., 'ca'. c[-1] evaluates to the last character in c, that being 't'. Hence, we now have c be 'ca' + 't' = 'cat'.

At the end, the values of a, b and c are printed, with a space between each of their values. Here, the values of a, b and c are 'ape', 'bear', and 'cat' respectively.

Answer
ape bear cat