{ xTurtle Tutorial Example #2: Variables. A variable is a name that can be used to hold a value. Variables must be declared before they are used. A variable can be assigned a value with an assignment statement. Variables and functions can be used to compute values from complex expressions such as 3 * sin(x+3). } DECLARE x, y { Allows you to use the variables named x and y. } x := 2 { Assignment statement, puts the value 2 into into the variable x. } y := 2*sqrt(x) { Computes sqrt(2), multiplies it by 2, and assigns the resulting value to y. Sqrt computes the square root. There are other predefined functions. } forward(x) { Variables can be used in commands. } turn(-135) { Negative turn rotates the turtle in a clockwise direction. } forward(y) turn(135) forward(x) { These commands have drawn a Z-shape. } DECLARE Rate { Declares another variable. They don't have to be declared at the start of the program. Names can be any number of characters. } Rate := 0.07 { Decimal numbers are OK. } DECLARE money, interest { More variables. } money := 1000 interest := Rate * money PenUp MoveTo(-8,8) PenDown DrawText("Interest on $#money is #interest.") { The value of a variable can be included in a string. Just include the character #, followed by the name of the variable. When the string is actually printed, the value of the variable is shown. } x := random { Assign a random value in the range 0.0 to 1.0 to x. The value will be different every time the program is run. Note that x was already declared, so I don't have to declare it again. In fact, it would be an error to do so. } y := randomInt(100) { y is assigned a random integer in the range 1 to 100. } DrawText("Here's a random number: #x") DrawText("Here's a random integer: #y")