Operators allow a language to combine, change, and compare variables. Mathematical operators produce a numerical result. Below are several mathematical operators you might frequently use.
Operator | Function | |
+ | Addition | |
– | Subtraction | |
* | Multiplication | |
/ | Division | |
** | Exponent |
There are several comparison operators. Unlike math operators, the result of a comparison operator is “true” or “false”. Below are several comparison operators you might frequently use.
Operator | Function | |
> | Is the first value greater the second value? | |
< | Is the first value less the second value? | |
== | Are the two values equal? | |
!= | Are the two values not equal? |
Here is another Python program that uses several operators.
x = 10 y = 5 print 'Inputs: x =', x, 'y =', y z = x + y if (z < 20): print 'Result:', z print 'Done.'
The first few lines create the variables x and y, and assign values to those variables. Strings to be printed should be enclosed in single quotes. Variables to be printed are simply indicated by their variable names. All of the different elements to be printed should be separated by variables. Math operations are straightforward. The results of a calculation can be assigned of a new variable. They can be assigned to an old variable, but doing so changes the value of the old variable (this is useful for updating variables).
White Space
One way that Python is readable is that it uses spaces (white space) for certain structures. This results in less jargon and well-organized program text. However, if you do not follow white space rules, your program will often not work. Some parts of control structures must be indented, such as parts of a control structure that are dependent upon the result of the condition. The result must be indented with four spaces (or one tab). Python is extremely particular about indenting. In the example above, a print statement is indented under the if statement.