Operators and Expressions
Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 2 + 3. An expression can be broken down into operators and operands.
Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data is called operands. In this case, 2 and 3 are the operands.
Operators
We will briefly take a look at the operators and their usage.
Here is a quick overview of the available operators:
Arithmetic Operators
+(plus)- Adds two objects
3 + 5gives8."a" + "b"gives"ab".
-(minus)- Gives the subtraction of one number from the other; if the first operand is absent it is assumed to be zero.
-5.2gives a negative number and50 - 24gives26.
*(multiply)- Gives the multiplication of the two numbers or returns the string repeated that many times.
2 * 3gives6."la" * 3gives"lalala".
**(power)- Returns x to the power of y
3 ** 4gives81(i.e.3 * 3 * 3 * 3)
/(divide)- Divide x by y
13 / 3gives4.333333333333333
//(divide and floor)- Divide x by y and round the answer down to the nearest integer value. Note that if one of the values is a float, you'll get back a float.
13 // 3gives4-13 // 3gives-5
%(modulo)- Returns the remainder of the division
13 % 3gives1.-25.5 % 2.25gives1.5.
Comparison Operators
<(less than)- Returns whether x is less than y. All comparison operators return
trueorfalse. 5 < 3givesfalseand3 < 5givestrue.- Comparisons can be chained arbitrarily:
3 < 5 < 7givestrue.
- Returns whether x is less than y. All comparison operators return
>(greater than)- Returns whether x is greater than y
5 > 3returnstrue.
<=(less than or equal to)- Returns whether x is less than or equal to y
x = 3; y = 6; x <= yreturnstrue
>=(greater than or equal to)- Returns whether x is greater than or equal to y
x = 4; y = 3; x >= 3returnstrue
==(equal to)- Compares if the objects are equal
x = 2; y = 2; x == yreturnstruex = "str"; y = "stR"; x == yreturnsfalsex = "str"; y = "str"; x == yreturnstrue
!=(not equal to)- Compares if the objects are not equal
x = 2; y = 3; x != yreturnstrue
Note for Python Programmers:
Auto uses lowercase
trueandfalsefor boolean values, while Python usesTrueandFalse. Thea2ptranspiler convertstruetoTrueandfalsetoFalseautomatically.
Boolean Operators
!(boolean NOT)- If x is
true, it returnsfalse. If x isfalse, it returnstrue. x = true; !xreturnsfalse.- In the transpiled Python code, this becomes
not x.
- If x is
&&(boolean AND)x && yreturnsfalseif x isfalse, else it returns evaluation of y.x = false; y = true; x && yreturnsfalsesince x is false. This uses short-circuit evaluation.- In the transpiled Python code, this becomes
x and y.
||(boolean OR)- If x is
true, it returnstrue, else it returns evaluation of y. x = true; y = false; x || yreturnstrue. Short-circuit evaluation applies here as well.- In the transpiled Python code, this becomes
x or y.
- If x is
Note for Python Programmers:
Auto uses
!,&&, and||for boolean operations, while Python usesnot,and, andor. Thea2ptranspiler converts these automatically. This is similar to the syntax used in languages like JavaScript, Rust, and C.
Bitwise Operators
&(bit-wise AND)- Bit-wise AND of the numbers: if both bits are
1, the result is1. Otherwise, it's0. 5 & 3gives1(0101 & 0011gives0001)
- Bit-wise AND of the numbers: if both bits are
|(bit-wise OR)- Bitwise OR of the numbers: if both bits are
0, the result is0. Otherwise, it's1. 5 | 3gives7(0101 | 0011gives0111)
- Bitwise OR of the numbers: if both bits are
^(bit-wise XOR)- Bitwise XOR of the numbers: if both bits (
1 or 0) are the same, the result is0. Otherwise, it's1. 5 ^ 3gives6(0101 ^ 0011gives0110)
- Bitwise XOR of the numbers: if both bits (
~(bit-wise invert)- The bit-wise inversion of x is -(x+1)
~5gives-6.
<<(left shift)- Shifts the bits of the number to the left by the number of bits specified.
2 << 2gives8.2is represented by10in bits.- Left shifting by 2 bits gives
1000which represents the decimal8.
>>(right shift)- Shifts the bits of the number to the right by the number of bits specified.
11 >> 1gives5.11is represented in bits by1011which when right shifted by 1 bit gives101which is the decimal5.
Assignment Operators
You can combine an arithmetic operator with assignment for a convenient shortcut:
=-- assign a value+=-- add and assign (a += 1is the same asa = a + 1)-=-- subtract and assign*=-- multiply and assign/=-- divide and assign//=-- floor divide and assign%=-- modulo and assign**=-- power and assign
For example:
let a = 2
a *= 3Notice that var = var operation expression becomes var operation= expression.
Operator Precedence
If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first. This means that the multiplication operator has higher precedence than the addition operator.
The following table gives the precedence table for Auto, from the lowest precedence (least binding) to the highest precedence (most binding). This means that in a given expression, Auto will first evaluate the operators and expressions lower in the table before the ones listed higher in the table.
It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. This makes the program more readable. See Changing the Order of Evaluation below for details.
| Precedence | Operator | Description |
|---|---|---|
| Lowest | || | Boolean OR |
&& | Boolean AND | |
! | Boolean NOT | |
<, <=, >, >=, ==, != | Comparisons | |
| | Bitwise OR | |
^ | Bitwise XOR | |
& | Bitwise AND | |
<<, >> | Shifts | |
+, - | Addition and subtraction | |
*, /, //, % | Multiplication, Division, Floor Division and Remainder | |
+x, -x, ~x | Positive, Negative, bitwise NOT | |
** | Exponentiation | |
| Highest | x[index], x.attr, x(args) | Subscription, attribute reference, call |
Operators that have not yet been covered will be explained in later chapters.
Operators with the same precedence are listed in the same row in the above table. For example, + and - have the same precedence.
Note for Python Programmers:
The operator precedence in Auto is the same as in Python. The boolean operators
&&/||/!in Auto have the same precedence asand/or/notin Python.
Changing the Order of Evaluation
To make the expressions more readable, we can use parentheses. For example, 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4 which requires knowledge of the operator precedences. As with everything else, the parentheses should be used reasonably (do not overdo it) and should not be redundant, as in (2 + (3 * 4)).
There is an additional advantage to using parentheses -- it helps us to change the order of evaluation. For example, if you want addition to be evaluated before multiplication in an expression, then you can write something like (2 + 3) * 4.
Let's see this in action:
How It Works
The first expression 2 + 3 * 4 gives 14 because multiplication has higher precedence than addition, so 3 * 4 is evaluated first (giving 12), then 2 + 12 gives 14.
The second expression (2 + 3) * 4 gives 20 because the parentheses force the addition to be evaluated first: 2 + 3 gives 5, then 5 * 4 gives 20.
The mixed operations example 2 + 3 * 4 - 10 / 2 follows the precedence rules: multiplication and division first (3 * 4 = 12, 10 / 2 = 5.0), then addition and subtraction from left to right (2 + 12 - 5.0 = 9.0).
For the power example, 3 ** 2 is evaluated first (giving 9), then 2 * 9 gives 18.
The boolean examples show how && (and) and || (or) combine with comparison operators. Notice that in the transpiled Python code, && becomes and, || becomes or, and ! becomes not.
Associativity
Operators are usually associated from left to right. This means that operators with the same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4 is evaluated as (2 + 3) + 4.
Expressions
Let's put everything together and calculate the area and perimeter of a rectangle, as well as the area of a circle:
How It Works
The length and breadth of the rectangle are stored in variables by the same name. We use these to calculate the area and perimeter of the rectangle with the help of expressions. We store the result of the expression length * breadth in the variable area and then print it using an f-string with $area interpolation. In the second case, we use the value of the expression 2 * (length + breadth) and store it in perimeter.
For the circle area, we use the ** (power) operator to calculate radius ** 2 (radius squared), then multiply by pi. The result uses radius = 5.0 (a float) so the circle area is also a float.
Finally, we demonstrate the compound assignment operators (+=, -=, *=). These are shortcuts that combine an arithmetic operation with assignment. total += 5 is equivalent to total = total + 5, and so on.
Summary
We have seen how to use operators, operands and expressions -- these are the basic building blocks of any program. In this chapter, we covered:
- Arithmetic operators:
+,-,*,**,/,//,% - Comparison operators:
<,>,<=,>=,==,!= - Boolean operators:
!(not),&&(and),||(or) - Bitwise operators:
&,|,^,~,<<,>> - Assignment operators:
=,+=,-=,*=,/=,//=,%=,**= - Operator precedence determines the order in which operations are performed
- Parentheses can be used to explicitly change the order of evaluation
- Associativity means operators of the same precedence are evaluated left to right
Next, we will see how to make use of these in our programs using control flow statements.