# Operators in Python

In this lesson, we will learn about expressions and various operators provided by Python.

Operator: An operator is a symbol which specifies a specific action.

Operand: An operand is a data item on which operator acts. Some operators require two operands while others require only one.

Expression: An expression is nothing but a combination of operators, variables, constants and function calls that results in a value. For example:

## Arithmetic Operators

Arithmetic operators are commonly used to perform numeric calculations. Python has following arithmetic operators.

Operator Description Example
`+` Addition operator `100 + 45 = 145`
`-` Subtraction operator `500 - 65 = 435`
`*` Multiplication operator `25 * 4 = 100`
`/` Float Division Operator `10 / 2 = 5.0`
`//` Integer Division Operator `10 // 2 = 5`
`**` Exponentiation Operator `5 ** 3 = 125`
`%` Remainder Operator `10 % 3 = 1`

We use `+`, `-`and `*` operators in our daily life, so they don’t deserve any explanation. However, the important thing to note is that `+` and `-` operators can be binary as well as unary. A unary operator has only one operand. We can use `-` operator to negate any positive number. For example: `-5`, in this case `-` operator is acting as a unary operator, whereas in `100 - 40`, `-` operator is acting as a binary operator. Similarly, we can use a unary `+` operator. For example, `+4`. As expression `4` and `+4` are same, applying unary `+` operator in an expression generally has no significance.

### Float Division Operator (/)

The `/` operator performs a floating point division. In other words, it returns a floating point result. For example:

### Integer Division Operator (//)

The `//` operator works similar to `/` operator, but instead of returning a float value it returns an integer. For example:

Unlike `/` operator, when the result is negative the `//` operator rounds the result away from zero to the nearest integer.

### Exponentiation Operator (**)

We use `**` operator to calculate `a^b`. For example:

### Remainder Operator (%)

The `%` operator returns the remainder after dividing left operand by the right operand. For example: The remainder operator `%` is a very useful operator in programming. One common use of `%` operator is to determine whether a number is even or not.

A number is even if it is exactly divisible by `2`. In other words, a number is even if when divided by `2`, leaves `0` as remainder. We will learn how to write such program in lesson If-else statement in Python.

## Operator Precedence and Associativity

Consider the following expression:

What will be its result?

If multiplication is performed before addition then the answer will be `59`. On the other hand, if the addition is performed before multiplication then the answer will be `140`. To solve this dilemma, we use Operator Precedence.

Operators in Python are grouped together and given a precedence level. The precedence of operators is listed in the following table.

Operator Description Associativity
`[ v1, … ]`, `{ v1, …}`, `{ k1: v1, …}`, `(…)` List/set/dict/generator creation or comprehension, parenthesized expression left to right
`seq [ n ]`, `seq [ n : m ]`, `func ( args… )`, `obj.attr` Indexing, slicing, function call, attribute reference left to right
`**` Exponentiation right to left
`+x`, `-x`, `~x` Positive, negative, bitwise not left to right
`*`, `/`, `//`, `%` Multiplication, float division, integer division, remainder left to right
`+`, `-` Addition, subtraction left to right
`<<`, `>>` Bitwise left, right shifts left to right
`&` Bitwise and left to right
`|` Bitwise or left to right
`in`, `not in`, `is`, `is not`, `<`, `<=`, `>`, `>=`, `!=`, `==` Comparison, membership and identity tests left to right
`not x` Boolean NOT left to right
`and` Boolean AND left to right
`or` Boolean OR left to right
`if-else` Conditional expression left to right
lambda lambda expression left to right

The operators in the upper rows have the highest precedence and it decreases as we move towards the bottom of the table. Whenever we have an expression where operators involved are of different precedence, the operator with higher precedence is evaluated first. So, in the expression `10 * 5 + 9`, the evaluation of `*` operator is performed first followed by the evaluation of `+` operator.

### Associativity of Operators

In the precedence table operators in the same group have the same precedence, for example, (`*`, `/`, `//`, `%`) have the same precedence. Now consider the following expression:

From the precedence table, we know that both `/` and `*` have higher precedence than `+`, but the precedence of `/` and `*` is same, so which operator do you think will be evaluated first, `/` or `*`?

To determine the order of evaluation when operator precedence is same we use Operator Associativity. Operator Associativity defines the direction in which operators of the same precedence are evaluated, it can be either from left to right or right to left. Operators within the same group have the same associativity. As you can see in the table, the associativity of `/` and `*` is from left to right. So in the expression:

The `/` operator will be evaluated first, followed by the `*` operator. At last, the `+` operator is evaluated.

The following are two noteworthy points to remember about the precedence table.

1. Associativity of most operators in the same group is from left to right except exponentiation operator (`**`). The associativity of exponentiation operator (`**`) is from right to left.
2. We sometimes use parentheses i.e `()` to change the order of evaluation. For example:

In the above expression, multiplication (`*`) will be performed first followed by addition (`+`). We can easily change the operator precedence by wrapping parentheses around the expression or sub-expression which we want to evaluate first. For example:

As the precedence of `()` operator is higher than that of `*` operator (see precedence table), the addition will be performed first followed by the multiplication.

Here are some expressions and order in which they are evaluated:

Example 1:

Example 2:

## Compound Assignment Operator

In programming, it is very common to increment or decrement the value of a variable and then reassign the value back to the same variable. For example:

Initially, the value of `x` is `10`. In the second expression, we have added `10` to the existing value of `x` and then reassign the new value back to `x`. So now the value of `x` is `15`.

The second statement i.e `x = x + 5` can be written in more succinctly manner using Compound Assignment Operator as follows:

Here `+=` is known as Compound Assignment Operator. The following table lists other Compound Assignment operators available in Python.

Operator Example Equivalent Statement
`+=` `x += 4` `x = x + 4`
`-=` `x -= 4` `x = x - 4`
`*=` `x *= 4` `x = x * 4`
`/=` `x /= 4` `x = x / 4`
`//=` `x //= 4` `x = x // 4`
`%=` `x %= 4` `x = x % 4`
`**=` `x **= 4` `x = x ** 4`

Unlike other C based languages likes like Java, PHP, JavaScript; Python doesn’t have Increment operator (`++`) and decrement operator (`--`). In those languages, `++` and `--` operators are commonly used to increment and decrement the value of the variable by `1` respectively. For example, to increment/decrement the value of a variable by `1` in JavaScript you would do something like this:

We can easily emulate this behavior using compound assignment operator as follows:

## Type Conversion

Upto this point, we haven’t given much thought about the type of data we have been using in expression in Python Shell as well as in our programs. When it comes to performing a calculation involving data of different types Python has following rules:

1. When both operands involved in an expression are `int`, then the result will be an `int`.
2. When both operands involved in an expression are `float`, then the result will be a `float`.
3. When one operand is of `float` type and other is of type `int` then the result will always be a `float` value. In such cases, the Python interpreter automatically converts the `int` value to `float` temporarily, then performs the calculation. This process is known as Type Conversion.

Here are some examples:

In the last expression literal `88` is first converted to `88.0`, and then the multiplication is carried out.

Sometimes, it is desirable to convert data from one type to a different type at our will. To handle such situations Python provides us the following functions:

Function Name Description Example
`int()` It accepts a string or number and returns a value of type `int`. `int(2.7)` returns `2`, `int("30")` returns `30`
`float()` It accepts a string or number and returns a value of type `float` `float(42)` returns `42.0`, `float("3.4")` returns `3.4`
`str()` It accepts any value and returns a value type `str` `str(12)` returns `"12"`, `str(3.4)` returns `"3.4"`

Here are some examples:

### int() function

Note that when `int()` function converts a float number to `int`, it simply removes the digits after the decimal point. If you want to round a number use the `round()` function.

## Breaking Statements into Multiple Lines

All the statements we have written until now are limited to one line. What if your statements become too long?

Typing long statements in one line is very hard to read on screen as well as on paper.

Python allows us to break long expression into multiple lines using the line continuation symbol ( `\` ). The `\` symbol tells the Python interpreter that the statement is continued on the next line. For example:

To expand a statement to multiple lines type the line continuation symbol ( `\` ) at the point where you want to break the statement and hit enter.

When Python Shell encounters a statement which expands to multiple lines, it changes the prompt string from `>>>` to `...`. When you are done typing the statement hit enter to see the result.

Here is another example which breaks the `print()` statement into multiple lines :

The following example shows how to write multi-line statements in a Python script.

python101/Chapter-06/multiline_statements.py

Output:

## bool Type

The `bool` data type represent two states i.e true or false. Python defines the values true and false using the reserved keywords `True` and `False` respectively. A variable of type `bool` can only contain one of these two values. For example:

An expression which evaluates to a `bool` value `True` `or` `False` is known as a boolean expression.

We commonly use `bool` variables as flags. A flag is nothing but a variable which signals some condition in the program. If the flag variable is set to `False` then it means that the condition is not true. On the other hand, if it is `True` then it means the condition is true.

Internally, Python uses `1` and `0` to represent `True` and `False` respectively. We can verify this fact by using `int()` function on `True` and `False` keywords as follows:

## Truthy and Falsy Values

Truthy values: Values which are equivalent to bool value `True` is known as Truthy values.

Falsy values: Values which are equivalent to bool value `False` is known as Falsy values.

In Python, the following values are considered as falsy.

1. `None`
2. `False`
3. Zero i.e `0`, `0.0`
4. Empty sequence, for example, `''`, `[]`, `()`
5. Empty dictionary i.e `{}`

Note: Sequence and dictionary are discussed in later chapters.

Everything else is considered as truthy. We can also test whether a value is truthy or falsy using the `bool()` built-in function. If value a truthy then `bool()` function returns True, otherwise it returns `False`. Here are some examples:

The significance of truthy and falsy values will become much more clear in the upcoming lessons.

## Relational Operators

To compare the values we use relational operators. An expression containing relational operators are known as relational expressions. If the expression is true then a bool value `True` is returned and if the expression is false a bool value `False` is returned. Relational operators are binary operators. The following table lists relational operators available in Python.

Operator Description Example Return Value
`<` Smaller than `3 < 4` `True`
`>` Greater than `90 > 450` `False`
`<=` Smaller than or equal to `10 <= 11` `True`
`>=` Greater than or equal to `31 >= 40` `False`
`!=` Not equal to `100 != 101` `True`
`==` Equal to `50==50` `True`

Beginners often confuse between `==` and `=` operators. Always remember, `=` is an assignment operator and is used to assign a value to the variable. On the other hand, `==` is an equality operator and is used to test whether two values are equal or not.

## Logical Operators

Logical operators are used to combine two or more boolean expressions and tests whether they are true or false. Expressions containing logical operators are known as Logical expressions. The following table lists logical operators available in Python.

Operator Description
`and` AND operator
`or` OR operator
`not` NOT operator

The `and` and `or` are binary operators, while `not` is unary.

## and Operator

The `and` operator returns a `bool` value `True` if both operands are true. Otherwise, it returns `False`.

Syntax: `operand_1 and operand_2`

The truth table for `and` operator is as follows:

operand_1 operand_2 Result
`False` `False` `False`
`False` `True` `False`
`True` `False` `False`
`True` `True` `True`

Here are some examples:

Expression Intermediate Expression Result
`(10>3) and (15>6)` `True and True` `True`
`(1>5) and (43==6)` `False and False` `False`
`(1==1) and (2!=2)` `True and False` `False`

The precedence of relational operators (i.e `>`, `>=`, `<`, `<=`, `==` and `!=`) is greater than that of `and` operator, so parentheses in the above expressions is not necessary, it is added here just to make the code more readable. For example:

As you can see, the expression `(10>3) and (15>6)` is much more clearer than `10 > 3 and 15 > 6`.

In `and` operator, if the first operand is evaluated to `False`, then the second operand is not evaluated at all. For example:

In this case, `(10>20)` is False, and so is the whole logical expression. Hence there is no need to evaluate the expression `(4==4)`.

## or operator

The `or` operator returns `False` when both operands are `False`. Otherwise, it returns `True`. It’s syntax is:

Syntax: `operand_1 or operand_2`

The truth table for `or` operator is as follows:

operand_1 operand_2 Result
`False` `False` `False`
`False` `True` `True`
`True` `False` `True`
`True` `True` `True`

Here are some examples:

Expression Intermediate Expression Result
`(100<200) or (55<6)` `True or False` `True`
`(11>55) or (6==6)` `False or True` `True`
`(1>12) or (2==3)` `False or False` `False`
`(10<22) or (20>3)` `True or True` `True`

In `or` operator, if the first operand is evaluated to `True`, then the second operand is not evaluated at all. For example:

In this case, `(100>20)` is `True`, and so is the whole logical expression. Hence there is no need to evaluate the expression `(90<30)`.

The precedence of `or` operator is less than that of `and` operator.

## not Operator

The `not` operator negates the value of the expression. In other words, if the expression is `True`, then the `not` operator returns `False` and if it is `False`, it returns `True`. Unlike the other two logical operators, the `not` operator is a unary. The precedence of the `not` operator is higher than that of `and` and `or` operator. Its syntax is:

Syntax: `not operand`

The truth table for `not` operator is as follows:

operand Result
`True` `False`
`False` `True`

Here are some examples:

Expression Intermediate Expression Result
`not (200==200)` `not True` `False`
`not (10<=5)` `not False` `True`