MicroPython Assignment Statements

Contents

Introduction

Anybody with any coding experience will be familiar with assignment statements. They provide the "guts" to any programming algorithm. Mostly, an assignment is a list or expression on the right hand side of the statement that is evaluated with the result assigned - often with the familiar = assignment operator - to a named variable on the left hand side.

An assignment, in addition to the = operator, often involves the use of other operators to perform some form of calculation, data manipulation or comparison. The MicroPython operators used in the examples below are similar to the operators of many other languages and should present no difficulties to most readers.

Other MicroPython operators are discussed in the following pages of this series.

Assignment Examples

The following are all simple assignment statements in MicroPython:

Example 1


str = "spam"
str1 = str2 = str3 = "SPAM"
x = 5
y = x + 10
          

Copy the above four lines of code into the Mu Editor, Save and Flash to the micro:bit. Since these are assignment statements there is no program output.

Add the following as the final line and re-run the program:


print(str, str1, str2, str3, x, y)
          

Output:


spam SPAM SPAM SPAM 5 15
          

Since MicroPython is a concise language, multiple assignments are possible in a single statement line.


x, y, z = 1, 2, 3
          

This is equivalent to:


x = 1 
y = 2 
z = 3
          

Augmented Assignments

MicroPython also has the ability to evaluate augmented assignments. Wikipedia defines augmented assignments as:

An assignment (that) is generally used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable.

Augmented assignments are ubiquitous in many other popular programming languages such as C, C++, Java and so. The best explanation is usually by example.

For example: x += y evaluates as x = x + y

Table 1: MicroPython's Augmented Assignments
Operation Assignment Meaning
Addition x += y x = x + y
Subtraction x -= y x = x - y
Multiplication x *= y x = x * y
Division x /= y x = x / y
Integer Division x //= y x = x // y
Modulus x %= y x = x % y
Power x **= y x = x ** y
Bitwise Shift Right x >>= y x = x >> y
Bitwise Shift Left x <<= y x = x << y
Bitwise AND x &= y x = x & y
Bitwise OR x |= y x = x | y
Bitwise XOR x ^= y x = x ^ y

Copy the following program into the Mu Editor, Save and Flash to the micro:bit. Click the REPL button to see the output.

Example 2


alpha = 10
beta = 3
delta = "Big"
delta += "Spam" #delta = "Big" + "Spam"
print("delta = ", delta)
alpha -= beta #alpha = 10 - 3
print("alpha =", alpha)
print("beta =", beta)
          

Output:


delta =  BigSpam
alpha = 7
beta = 3