In Python there are various types of operators, whose purpose is to perform operations on variables and data, but in this tutorial we’ll just be looking at those operators which are used in the example game.
ASSIGNMENT OPERATOR
The assignment operator = was looked at earlier in the tutorial, and it’s used to give a value to a variable. For example, here we give the value of 4 to the variable intNumber and then display it on the screen:
intNumber = 4
print (intNumber)
ARITHMETIC OPERATORS
The arithmetic operators are the same as the functions you’d find on a calculator, for example addition + subtraction – multiplication * division /
Here we add two numbers together and assign the result to the variable intResult, then display it:
intResult = 3+4
print (intResult)
This following code assigns values to two variables, subtracts one from the other and puts the result into a third variable, then displays it:
intNumber1 = 4
intNumber2 = 5
intResult = intNumber2 - intNumber1
print (intResult)
COMBINING ASSIGNMENT AND ARITHMETIC OPERATORS
It’s possible to use a shorthand format for an expression that performs an arithmetic operation and assigns it to a variable.
What happens in the following code is that the variable intNumber is first given the value of 5. On the next line the right hand side of the = operator is evaluated and results in the value of 11. This is then assigned to the same intNumber variable and printed on screen:
intNumber = 5
intNumber = intNumber + 6
print (intNumber)
In the second line of the above code intNumber simply adds 6 to itself to give the value 11, and it can be rewritten in a shorthand format as seen below:
intNumber = 5
intNumber += 6
print (intNumber)
The second line in each of the above 2 programs has exactly the same effect, and it’s a matter of personal preference which format you choose – use whichever one you’re most comfortable with. Personally I like the latter shortened method, simply because there’s less to type and it reduces the chance of a typo (typing mistake.)
OPERATOR PRIORITY
Arithmetic operators have different priorities, in the same way as they do in mathematics. For instance, multiplication and division have a higher priority than addition and subtraction.
Consider this:
intNumber = 1+2 * 4
print (intNumber)
Is the result 12? (1 + 2 = 3, and then 3 * 4 = 12)
Or is it 9? (2 * 4= 8, and then 1 + 8 = 9)
You might think it’s 12 because the 1 + 2 part comes first, but in fact the result is 9 due to the multiplication symbol having a higher priority than the addition operator (the computer calculates 2 * 4 first.)
If in the above example you wanted the computer to calculate 1 + 2 first you can use brackets, these have a priority higher than any operator:
intNumber = (1+2) * 4
print (intNumber)
The computer calculates 1 + 2 first and then multiplies it by 4, giving the result 12.