Code-2 Variables and =

This is a short section, to add the idea of variables to the code.


variable x as a box holding the value 7


code2-1

 

Variables work as a shorthand -- we use = to assign a value into a variable, and then use that variable on later lines to retrieve that value. In the simplest case, this just works to avoid repeating a value: we store the value once, and then can use it many times. All computer languages have some form of variable like this, storing and retrieving values.

You Try It

Change the code below so it produces the following output. Use a variable to store the string "Aardvark" in a variable on the first line like x = "Aardvark";, then use the variable x on the later lines. In this way, changing just the first line to use the value "Zebra" or "Alice" or whatever changes the output of the whole program. The print() function automatically puts spaces between multiple items.

Aardvark Aardvark Aardvark
Here is Aardvark
Aardvark has arrived

code2-2

 

x = "Aardvark"
print(x, x, x);
print("Here is", x);
print(x, "has arrived");