Operators are special symbols that designate that some sort of computation should be performed. The values that an operator acts on are called operands.
An operator is a character or set of characters that can be used to perform the desired operation on the operands and produce the final result.
Suppose you want to perform a mathematical calculation of 5 + 3
5 and 3 are called operands, +
is the operator that performs addition and the final result is 8.
a = 10
b = 20
a + b
# operand operator operand
30
Operator | Example | Meaning | Result |
---|---|---|---|
+ | c = a + b | Addition | c = sum of a and b |
- | c = a - b | Subtraction | c = a less b |
* | c = a * b | Multiplication | c = product of a and b |
/ | c = a / b | Division | c = a divided b times |
% | c = a % b | Modulo | c = does division of a/b then returns the remainder |
// | c = a // b | Floor/Integer Division | c = does division of a/b returns integer. removes decimal |
** | c = a ** b | Exponent | c = a raised to power b |
a = 20; b = 5;
print(+a) # unary operator
print(-b) # unary operator
# addition
print('a + b = ', a + b)
# subtraction
print('a - b = ', a - b)
# multiplication
print('a * b = ', a * b)
# division
print('a / b = ', a/b)
# modulus
print('a % b = ', a%b)
# floor/integer division
print('a // b = ', a // b)
# exponent
print('a ** b = ', a ** b)
20 -5 a + b = 25 a - b = 15 a * b = 100 a / b = 4.0 a % b = 0 a // b = 4 a ** b = 3200000
Note: The result of standard division (/
) is always a float even if the dividend is evenly divisible by the divisor
div = 10/5
print(div)
print(type(div))
2.0 <class 'float'>
When the result of floor division (//) is positive, it is as though the fractional portion is truncated off, leaving only the integer portion. When the result is negative, the result is rounded down to the next smallest (greater negative) integer
print('10 / 4 = ', 10 / 4)
print('10 // 4 = ', 10 // 4)
print('10 // -4 = ', 10 // -4)
print('-10 // 4 = ', -10 // 4)
print('-10 // -4 = ', -10 // -4)
10 / 4 = 2.5 10 // 4 = 2 10 // -4 = -3 -10 // 4 = -3 -10 // -4 = 2
If you divide any number by 0 then you will be prompted by a ZeroDivisionError. Don't divide anything by zero (0)
The result generated by the division operator will always by of type float (i.e) has decimal point.
Floor/Integer Division returns the quotient (answer or result of division) in which the digits after the decimal point are removed. If one of the operands (dividend or divisor) is negative, then the result is floored i.e rounded away from zero, towards negative infinity
Comparison operators or relational operators are used in comparing the objects.
The return type of these operators are either True
or False
Operator | Example | Name | Result |
---|---|---|---|
> | a > b | Greater than | a=15,b=5, True |
< | a < b | Less than | a=15,b=5, False |
== | a == b | Equal to | a=5,b=5, then True |
!= | a != b | Not equal to | a=10,b=5 then True |
>= | a >= b | Greater than or equal to | a=15, b=2, then True |
<= | a <= b | Less than or equal to | a=15, b=2, False |
# assign values to variables
a = 10; b = 5
print('a',a)
print('b',b)
# Greater than
print('a > b', a > b)
# less than
print('a < b', a < b)
# equal to
print('a == b ', a == b)
# not equal to
print('a != b ', a != b)
# greater than or equal to
print('a >= b ', a >= b)
# less than or equal to
print('a <= b', a <= b)
a 10 b 5 a > b True a < b False a == b False a != b True a >= b True a <= b False
The value stored in memory for a float object may not be precisely what you'd think it would be.
It is poor practice to compare float data types for exact equality.
Consider the following scenario:
x = 1.1 + 2.2
print(x)
# test for exact equality
print(x == 3.3)
3.3000000000000003 False
The preferred way to determine whether two floating-point values are “equal” is to compute whether they are close to one another, given a margin of error.
err_margin = 0.00001
x = 1.1 + 2.2
print(abs(x - 3.3) < err_margin)
# value within range of error. So we determine the two are equal
True
abs()
returns absolute value. If the absolute value of the difference between the two numbers is less than the specified margin or tolerance, they are close enough to one another to be considered equal.
Comparison Operators are also called relational operators
The comparison operator can be used to compare more than two values. For example 5 < x <= 10
# assign value to variable
x = 10
# check if value falls in the range (5,10) --bound exclusive
print(5 < x < 10)
# check if value falls in the range [5,10] --bound inclusive
print(5 <= x <= 10)
# chack if value falls in the range [5,10)
print(5 <= x < 10)
# check if value falls in the range (5,10]
print(5 < x <= 10)
False True False True
Logical operators are used to evaluate the conditions between the operands.
The different types of logical operators are:
and
or
not
The logical operators not
, or
, and
and modify and join together expressions evaluated in Boolean context to create more complex conditions.
Interpretation of logical expressions involving not
, or
and and
is straightforward when the operands are Boolean
Operator | Example | Meaning |
---|---|---|
not | not x | True if x is False False if x is True |
or | x or y | True if either x or y is True. False otherwise |
and | x and y | True if both x and y are True. False otherwise |
not
and Boolean operands¶Logically reverses the sense of expression
x = 5
print(not x < 10) # x < 10 is True
print(not x == 10) # x == 10 is False
False True
or
and Boolean operands¶x = 5
print(x < 10 or bool(x)) # bool(x) is True
print(x < 0 or bool('')) # bool('') is False
True False
#### `and` and Boolean operands
x = 5
print(x < 10 and bool(x))
print(x < 10 and bool('')) # empty string is False
True False
To make things more clear, refer to the truth table provided below
A | B | (A and B) | (A or B) | not(A and B) | not(A or B) |
---|---|---|---|---|---|
True | True | True | True | False | False |
True | False | False | True | True | False |
False | True | False | True | True | False |
False | False | False | False | True | True |
# assign values to variables
a = True; b = False
# logical and
print('a and b is', a and b)
# logical or
print('a or b is', a or b)
# logical not
print('not a is', not a)
a and b is False a or b is True not a is False
Logical operators are also called Boolean Operators
If the operands are not boolean, then it would be automatically converted to a boolean data type for the evaluation
The logical operators can be applied to any of value. For example, they can be applied to strings
You can evaluate any expression in Python, and get one of two answers, True or False
Non boolean objects may still be evaluated in Boolean context and determined to be "truthy" or "falsy"
In Python, all the following are considered False when evaluated in Boolean context
The Boolean value False
Any value that is numerically zero (0, 0.0)
An empty string
An empty sequence example empty list
The special value denoted by the Python keyword None
Virtually any other object built into Python is regarded as True
You can determine the "truthiness" of an object or expression with the built-in bool()
function. bool()
returns True
if its argument is Truth and False
if it is falsy
Non-boolean values, example strings, can also be modified and joined by not
, or
and and
. The result depends on the truthiness of the operands.
not
operator on Non-Boolean¶here is what heppens for a non-Boolean value x
if x is | not x is |
---|---|
"truthy" | False |
"falsy" | True |
not
operator on Strings¶a = "" # empty string
print("not empty string is ",not a)
a = "Python" # string
print("not Python is ",not a)
not empty string is True not Python is False
not
operator on numeric data types¶x = 3
print('bool(3) is', bool(x))
print('not 3 is', not x)
bool(3) is True not 3 is False
x = 0.0
print("bool(0.0) is ", bool(x))
print("not 0.0 is ", not x)
bool(0.0) is False not 0.0 is True
or
operator on Non-Boolean Operands¶This is what happens for two non-boolean values x and y
if x is | x or y is |
---|---|
"truthy" | x |
"falsy" | y |
Note that in this case, the expression x or y does not evaluate to either True or False, but instead to one of either x or y
In both cases of and
and or
the evaluation is done from left to right
a = "" # empty string
b = "Python"
print("'' or Python is ",a or b)
'' or Python is Python
or
operator on numeric data types¶# assigning values
x = 3; y = 4
print("3 or 4 is",x or y)
x = 0.0
y = 4.4
print("0.0 or 4.4 is",x or y)
3 or 4 is 3 0.0 or 4.4 is 4.4
here's what you'll get for two non-boolean values x and y
if x is | x and y is |
---|---|
"truthy" | y |
"falsy" | x |
a = "" # emtpy string
b = "Python"
print('empty string and Python is ', a and b) # returns falsy val
a = "p" # non-empty string
b = "Python"
print("non-empty string and Python(another non empty string) is ", a and b)
empty string and Python is non-empty string and Python(another non empty string) isn Python
x = 3
y = 4
print("3 and 4 is ", x and y)
x = 0.0
y = 4.4
print('0.0 and 4.4 is ', x and y)
3 and 4 is 4 0.0 and 4.4 is 0.0
As with or, the expression x and y does not evaluate to either True or False, but instead to one of either x or y. x and y will be truthy if both x and y are truthy, and falsy otherwise.
Python provides two operators, is
and is not
, that determine whether the given operands have the same identity—that is, refer to the same object.
This is not the same thing as equality, which means the two operands refer to objects that contain the same data but are not necessarily the same object.
In other words, the identity operator can also be used to compare if the objects share the same memory location.
Operator | Description | Syntax | Example |
---|---|---|---|
is | Compares two or more operands and returns True if they have the same id or pointing to the same memory location or else returns False | a is b | a = 5, b = a returns True |
is not | Reverse the is. Returns True if both the objects have different ids or not pointing to the same memory location or else returns False | a is not b | a=6,b=5 returns True |
Here is an example of two objects that are equal but not identical:
x = 10001
y = 10000 + 1
print(x)
print(y)
print("equality: ", x==y)
print("identity: ", x is y)
10001 10001 equality: True identity: False
Here, x
and y
both refer to objects whose value is similar. They are equal but not identical , that is, they do not reference the same object.
# x and y do not have the same identity
x_id = id(x)
print("id of x : ", x_id)
y_id = id(y)
print("id of y: ", y_id)
id of x : 1715124304880 id of y: 1715124305104
# more examples
a = 'I am a string'
b = a
a_id = id(a); b_id = id(b)
print("id of a is: ", a_id)
print("id of b is: ", b_id)
print("identity: ",a is b)
print("equality: ",a == b)
id of a is: 1715124264304 id of b is: 1715124264304 identity: True equality: True
# example with list objects
lst1 = [i for i in range(5)] # using list comprehension
lst2 = [0,1,2,3,4]
print("the first list is: ", lst1)
print("the second list is: ", lst2)
# test for equivalence
equality = (lst1 == lst2)
# test for identity
identity = lst1 is lst2
print("equality is: ", equality)
print("identity is: ", identity)
the first list is: [0, 1, 2, 3, 4] the second list is: [0, 1, 2, 3, 4] equality is: True identity is: False
# example with string objects
str1 = "Hello"
str2 = "hello"
str3 = str1.lower()
# check for equality
equality = str1 == str2
equality_str3 = (str2 == str3)
print("Equality of str1 and str2: ", equality)
print("Equality of str1.lower() and str2: ", equality_str3)
# check for identity
id1 = str1 is str2
id2 = str2 is str3 # str1.lower()
# print a new line
print("")
print("Identity of str1 and str2: ", id1)
print("Identity of st1.lower() and str2: ", id2)
#print a new line
print("")
# the same using f-strings
print(f"Equality of {str1} and {str2}: ", equality)
print(f"Equality of {str1.lower()} and {str2}: ", equality_str3)
#print a new line
print("")
print(f"Identity of {str1} and {str2}: ", id1)
print(f"Identity of {str1.lower()} and {str2}: ", id2)
Equality of str1 and str2: False Equality of str1.lower() and str2: True Identity of str1 and str2: False Identity of st1.lower() and str2: False Equality of Hello and hello: False Equality of hello and hello: True Identity of Hello and hello: False Identity of hello and hello: False
Membership operators are used to verifying whether a particular element is a part of a sequence or not. Now a sequence can be a list, string, sets, dictionary, and tuples. The two membership operators are:
in
not in
Operator | Description | Syntax | Example |
---|---|---|---|
in | Compares two or more operands and returns True if the value operand is found in the sequence operand or else returns False | a in b | a = 'c', b = 'ace' returns True |
not in | Reverse the in. Returns True if the value operand is not found in the sequence operand or else returns False | a not in b | a=6,b=[2,4,6,8] returns False |
# assign a string to a variable
a = "Python"
# Type of the variable
print(type(a))
# checking whether character 'y' is in the string a or not
print('y' in a)
# checking whether 'p' is present in the variable a or not
print('p' not in a) # True because the character in the variable is uppercase
<class 'str'> True True
# dictionary with key as 1, 2 and values as 'A' and 'B'
a = {1:'A', 2:'B'}
# using 'in' operator
print(2 in a)
# using 'not in' operator
print(3 not in a)
True True
a = 10
a = a + 5
print(a)
15
a = 10
a += 5
print(a)
15
The next tutorial will explore conditional expressions in python in much more detail.