Variables

Computer programs actually do two things:

In the previous exercises we have printed some text. What if we want to print it twice? Let's have a look:

text = 'What a Wonderful World!'
print(text)
print(text)

Here text is the name of variable. Think of it as of "named box" for putting some stuff into. The first line is assignment statement - it assigns value (this long string) to a variable with a short name. Then we call print function twice, each time giving it not the string itself, but variable which contains the string.

Note that assignment is written using single equals sign (=). To write equality itself we use something different, we'll learn this later.

There are more ways to duplicate the text. Copy-paste the following code into program area below and run it:

text = 'What a Wonderful World!'
print(text, text)
print(text .. text)

You'll see the first print outputs the string twice (with some gap between). It is because this function allows to pass more than one thing to be printed.

The second print is more interesting. Here we still pass only one value but this value is combined (or concatenated) of two usages of the same variable. The string is printed twice, without gap. This trick could be used to print text more than twice:

text = 'Laugh'
text2 = text .. text
text4 = text2 .. text2
print(text4)

Here we combine value from variable text with itself and assign it to another variable text2. Then we do this again duplicating text2 and storing result in text4. Try it.

Actually we don't need new variables in this example, we can re-write (or re-assign) value:

text = 'Wonder'
text = text .. text

I.e. value from variable text is duplicated and overwritten into the same variable!

For Practice here is a simple exercise. You are given some letter - and the goal is to print this letter 32 times without gaps! Hint: use the same approach but duplicate few more times!


Letter is: