Operators
Each operator in python has a corresponding magic method of corresponding class. When you use operator, it calls the magic method under the hood. In python, some operators are symbols and some are text.
Assignment operators
= to assign value to a variable
Arithmatic operators
used for arithmatic operations
+to addition-to subtraction*to multiplication/to division%to modulo//to floor division**to exponentiation
Comparison operators
==!=><>=<=
Logical operators
return boolean value, True or False
and: check if both operands are trueor: check if either operand is truenot: check if operand is falsein: check if element is present in a sequencenot in: check if element is not present in a sequenceis: check if two objects are the same objectis not: check if two objects are different object|: check if either operand is true&: check if both operands are true^: check if either operand is true
WARNING
del is not an operator, it is a statement to delete elements from a list and dictionary.
my_guitar = {
'brand': 'Ibanez',
'price': 10000,
}
print('color' not in my_guitar)
# TrueFalsy values
values that evaluate to False in boolean context. bool(value) return False. In python, the following values are falsy.
FalseNone0,0.0,0j(int, float, complex)''(empty string)[](empty list){}(empty dictionary)set()(empty set)()(empty tuple)range(0)(empty range)
short circuit operation
and operator
If left operand is false, right operand is not evaluated. Goal is here to find 1st falsy value.
is_new = False
price = 1000
print(is_new and price < 1500)
# False (price is not evaluated)or operator
If left operand is true, right operand is not evaluated. Goal is to find 1st truthy value.
name = 'Kibria'
age = 41
print(name == 'Kibria' or age > 40)
# True (age is not evaluated)Unary operators
has just one operand. they are prefix operator.
+: use to convert a number to positive, boolean to integer-: use to negate a number~: use to invert a numbernot: use to negate a booleanabs: use to get absolute value of a number
is_new = True
print(+is_new)
# 1
num_1 = 5
print(-num_1)
# -5
name = ''
print(not name)
# True
name = 'Kibria'
print(not name)
# False
print(not not name)
# True
num_4 = 23.98
num_5 = -23.98
print(abs(num_4))
# 23.98
print(abs(num_5))
# 23.98Binary operators
has 2 operands. They are infix (between operands) operator.
a = 5a + ba += 4a == ba and b