expressions

Now we’re going to talk about tweetle beetles how the computer thinks. For example, what will the following block of code output? Try to figure it out without running the code in Thonny.

x = 4 + 2 * 7
y = x / 2 - 3
z = (x + y) * 2
print(z)

If the answer is obvious to you, then you can probably skip this section. Otherwise, I hope you enjoy my explanation of expressions.

An expression is a piece of code that can be simplified to a single value. On the first line, 4 + 2 * 7 is an expression. It simplifies to 18. But in programming, we say the expression evaluates to 18.

Technically, 42 is also an expression—it evaluates to 42. After the first line, x is an expression that evaluates to 18.

When the computer sees x = 4 + 2 * 7, it evaluates the expression the same way a human would:

    x = 4 + 2 * 7
 -> x = 4 + 14
 -> x = 18

Then the next line gets evaluated like this:

    y = x / 2 - 3
 -> y = 18 / 2 - 3
 -> y = 9 - 3
 -> y = 6

And finally we have:

    z = (x + y) * 2
 -> z = (18 + 6) * 2
 -> z = 24 * 2
 -> z = 48

previous: arithmetic next: number input