The following operators are very similar to math: they calculate two numbers and result as a number.
|add||a + b||a + b|
|minus||a - b||a - b|
|multiply||a × b||a * b|
|divide||a ÷ b||a / b|
|power||ab||a ** b|
Warning: the result of the math operation with decimal number is not always 100% accurate, for example,
print (0.2+0.1) will give you
+ can also used to combine two string, for example
print ("Hello" + " World!") will give you
There are some operators used to compare two values, they result as a Boolean value.
|==||If a and b are same|
|!=||If a and b are not same|
|>||If a is greater than b|
|>=||If a is greater than or equal to b|
|<||If a is less than b|
|<=||If a is less than or equal to b|
Comparison operators can also used between strings:
...also used in Booleans:
Logical Operators are operators for Boolean values.
|and||If a and b are all true|
|or||If at least one of a and b is true|
You don’t need to remember all of this, when you are confused of precedence, just use brackets to tell python which part you want to calculate first:
An important thing to know is
a = 10 doesn’t mean “variable a equals to 10”, but “give value 10 to variable a”.
When you are assigning a variable for example
a = 2 + 3, python calculates the right side of the equal sign first (the result is 5), then assign 5 to the variable.
This is very important when you are trying to add one number to a variable. For example if you want to add 2 to
a, you can write
a = a + 2 (
a is 5 before running this code). Python will calculate right side first (
a + 2), the result is 7, then python will assign 7 to
Reading other’s code is very important on your road of learning programming. Following are some lines of code and their output. Read, run and change the code, try to understand them.
Next: Basic Function