User Tools

Site Tools


code:variable

Variables

Variables allow you to store different values in the computer's memory. Variable names cannot contain spaces, should start with a letter or underscore (_), and should only contain letters, numbers, and underscores.

Creating Variables

JavaScript

var x;
var y = 123;

As we see here, variables can be declared (created) without having a value assigned. They can also be created and given a value at the same time.

Python

Python automatically creates variables the first time they are used. Thus,

x = 3

will create the variable x if it doesn't exist, and then set it to 3.

Types of variables

Integer

An Integer is a number without a fraction.

x = 123

Double

A Double is a number with a fraction.

x = 12.5

To remove the fraction part of a double, you can use it like this:

x = 12.5
y = (int) x

This will take x, remove the fraction part, and set y to the integer value of x.

String

A string stores text. In SyMAT they are also used to store formulas.

text = "hello world!"
formula = 'x^2+5'

In both JavaScript and Python, strings are set apart from regular code by single or double quotes. It is recommended for clarity to use one type of quotes for normal text and the other type for formulas.

Arrays

An array stores a list of values. The array can be one-dimensional (such as [1,2,3,4,5]), or multi-dimensional (like a grid).

Arrays are represented like this:

[1,2,3,7,5,4]

Creating arrays

Both JavaScript and Python allow array creation the same way.

myArray = [1,2,3,4,5]

Accessing arrays

To get the first item in an array:

myArray = [5,4,3,2,1]
print(myArray[0])

Output:

5

Note the array index (in the square brackets) is zero for the first item, 1 for the second, and so on.

To set the third item in the above myArray to the value of x:

x = 42
myArray[2] = x
code/variable.txt · Last modified: 2019/04/16 02:40 (external edit)