![]()
INTRODUCTION |
In the previous chapter, you drew squares with side lengths that were firmly implemented in the program. There may also be times when you want to enter the side length with an input dialog. In order to do this, the program needs to store the entered number as a variable. You can see the variable as a container, the content of which you can access with a name. So, in short, a variable has a name and a value. You can freely choose the name of a variable, but they cannot be keywords or names with special characters. Moreover the name cannot start with a number.
So then what happens when you write a = a + 5? You take the number that is currently in the container, accessed with the name a, and therefore the number 3 is added to the number 5. The result adds up to 8 and it is again saved under the name a.
Therefore, the equal sign does not mean the same thing in computer programming as it does in mathematics. It does not define an equation, but rather a variable definition or an assignment [more...In some programming languages are used therefore for assigning a different notation, for example, : = or MAKE]. |
READING AND MODIFYING VARIABLE VALUES |
from gturtle import * makeTurtle() x = inputInt("Enter a number between 5 and 100") repeat 10: forward(x) left(120) x = x + 20 |
MEMO |
|
With variables you can store values that you are able to read and change in the course of the program. Every variable has a name and a value. You can define a variable and assign a value to it using an equal sign
[more...
Values of variables are stored in the computer's memory and will be lost
when the program ends or the computer is turned off.]. |
DISTINGUISHING VARIABLES AND PARAMETERS |
You should be aware of the differences between a variable and a parameter. Parameters transport data into a function and are only valid within that function, whereas variables are possible anywhere. When calling a function, you give each of its parameters values that can be used as variables within the function's scope [more... A parameter is an entrance gate to transfer data into the interior of the function].
from gturtle import * def square(sidelength): repeat 4: forward(sidelength) right(90) makeTurtle() s = inputInt("Enter the side length") square(s) |
MEMO |
|
You have to distinguish between the variable s and the parameter sidelength. In the definition of a function parameters are placeholders and can be regarded as variables that are only known inside of the function each time it is called. If you call the function with a variable, the variable's value is used in the function. Thus, square(length) draws a square with a side length of length [more... The variable value is used as the parameter value (pass-by-value)]. |
THE SAME NAME FOR DIFFERENT THINGS |
from gturtle import * def square(sidelength): repeat 4: forward(sidelength) right(90) makeTurtle() sidelength= inputInt("Enter the side length") square(sidelength) |
MEMO |
EXERCISES |
|