==============================
x := 4
y := 3
x := y
==============================
We give a brief discussion on the use of variables.
Variables
Variables act as containers for data. Together with functions, covered in a later section, variables help us generalize our algorithms. While you may be used to variables such as x or y from your math courses, variable names in programming languages can be longer with the aim of being descriptive. When choosing variable names in Python, be sure to keep in mind the following guidelines:
- variable names should be descriptive
- variable names cannot begin with a number
- other than the first letter restriction, variable names can contain any alphanumeric character or _
- variable names are case sensitive, for example, myVar and myvar are not the same
We use the assignment operator to associate data or a particular value with a variable. Reminder: when writing an algorithm that is independent of a particular programming language, the assignment operator is given by :=, however, in Python (and other programming languages), the assignment operator is typed as =.
We give a few examples below of how variables may be used.
Basic assignment of a value to a variable:
A variable used in an expression:
Assignment with a variable on the right hand side of the assignment operator:
Assignment with the same variable on both sides of the assignment operator:
Descriptive variable names:
Problems
==============================
x := 5
y := 3
x := y + 1
x := x + 6
==============================
==============================
x := -3
y := 5
x := y
y := x
==============================
==============================
x := -3
y := 5
t := x
x := y
y := t
==============================
==============================
x := 3
y := 7
x := 2 * x + y
==============================