Operators

Arithmetic Operators

The following operators are very similar to math: they calculate two numbers and result as a number.

 MathPython
adda + ba + b
minusa - ba - b
multiplya × ba * b
dividea ÷ ba / b
poweraba ** b

For example:

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 0.30000000000000004, not 0.3.

+ can also used to combine two string, for example print ("Hello" + " World!") will give you Hello World!.

 

Comparison Operators

There are some operators used to compare two values, they result as a Boolean value.

OperatorExampleMeaning
==a == bIf a and b are same
!=a != bIf a and b are not same
>a > bIf a is greater than b
>=a >= bIf a is greater than or equal to b
<a < bIf a is less than b
<=a <= bIf a is less than or equal to b

For example:

Comparison operators can also used between strings:

...also used in Booleans:

Logical Operators

Logical Operators are operators for Boolean values.

OperatorExampleMeaning
anda and bIf a and b are all true
ora or bIf at least one of a and b is true
notnot aReverse true/false

For example:

Operators Precedence

  1. **
  2. *, /
  3. +, -
  4. <=, <, >, >=
  5. ==, !=
  6. not, or, and

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:

Assign a Variable with an Operator

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 a.

Example Code

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

https://img.shields.io/badge/By-Pegasis-green.svg