Mastering Python Operators: From Basic Arithmetic to Shorthand Syntax
Last updated on
Arithmetic Operators:
Basically these are all the math related operators that you may need when dealing with numbers: addition, substraction, division, floor division, reminder (or modulo) and finally exponentiation.
print(10 + 3) # Addition (13)
print(10 - 3) # Substraction (7)
print(10 * 3) # Multiplication (30)
print(10 / 30) # Division (3.333)
print(10 // 3) # Floor Division (3)
print(10 % 3) # Reminder (modulo) (1)
print(2 ** 8) # Exponentiation (256)
Comparison Operators:
Comparision operators evaluates the relashionship between two values that can be of any value type, and return a boolean result: either True or False.
There are 6 operators in Python:
# Declaring two variables a and b
a = 1
b = 2
# 1. Equality
print(a == b) # False
# 2. inequality: not equal
print(a != b) # True
# 3. Strictly greater than
print(a > b) # False
# 4. Strictly lower than
print(a < b) # True
# 5. Lower than
print(a <= b) # True
# 6. Greater than
print(a >= b) # False
Assignment operators:
An assignment operator is a symbol (=), used to bind a value or the result of an expression to a variable name.
In other words, it’s used to override the content of a variable with a value or result of an expression such as:
# 5**2 + 5*2 is an expression that returns a value type of 'int'
x = 5**2 +5*2
The same operator = is used for both declaring and assigning a variable a value at the same time.
x = 10 # Create/override the variable content
When you want to modify a variable without overriding it, for example say that you want to increment x by 3. You’ll typically do something like this:
x = x + 3
Although it’s a valid and a more straight forward approach, we had to repeat the variable name twice. Python offers a shorthand syntax to avoid doing so.
x += 3 # Equivalent to x = x +3
You can use this shorthand syntax with any existing Python operator, as follow.
x <operator>= value # Equivalent to x = x <operator> value
For example:
x -= 2 # Equivalent to x = x - 1
x*= 2 # Equivalent to x = x * 2
x /= 4 # Equivalent to x = x / 4
x //= 2 # Equivalent to x = x // 2
x **= 3 # Equivalent to x = x ** 3
x %= 3 # Equivalent to x = x % 3
#...
Repetition Operator
The repetition operator is especially useful to print delimiters in CLI tools.
print("-" * 5) # -----
Boolean(logical) Operators
Boolean operators in Python are keywords used to combine or modify conditional expressions, evaluating to either True or False. Python has three logical Boolean operators: and, or, and not
“and” and “o” are binary, meaning that they operate on two boolean values or expressions.
While “not” is unary, meaning that it operates on a single boolean value or expression.
Logical “and”:
The “and” operator checks wether two requirements are simultaneously satisfied, if that’s the case then it evaluates to True, otherwise it evaluates to False.
For example, i’m currently writing this sentence, “and” i’m listening to some quite RPG music.
True and True evaluates to True.
writing = True # Can be a boolean expression as well such as (5 > 2)
listning_to_music = True # Can be a boolean expression as well such as (5 > 2)
print(writing and listning_to_music) # True
True and False evaluates to False.
writing = True
listning_to_music = False
print(writing and listning_to_music) # False
False and False evaluates to False.
writing = False
listning_to_music = False
print(writing and listning_to_music) # False
You can chain many ands together, in a long sequence of “and”s, as long as all the values are True,
print(True and True and True and True ) # True
print(False and True and True and True ) # False
Another convinient way to write a long sequence of chained “and” operator is using the “all” builtin, which works the same as chaining multiple “and”s over multiple boolean values or expressions.
print(all([True, True, True, True])) # True
print(all([False,True, True, True])) # False
“all” receives a list of boolean values or expressions, and evaluates to True, only if all of them are truthy.
v1,v2,v3,...,vN are boolean values (True, False) or boolean expressions.
all([v1,v2,v3,...,vN]) # True only if all the values are truthy.
Logical “or”:
The “or” operator checks wether at least one requirement among the two is satisfied, if that’s the case, then it evaluates to True, otherwise it evaluates to False.
For example, you can be either watch a Youtube video or take notes.
True or False evaluates to True:
watching_video = True
taking_notes = False
print( watching_video or taking_notes) # True
True or True evaluates to True:
watching_video = True
taking_notes = True
print( watching_video or taking_notes) # True
False or False evaluates to False:
watching_video = False
taking_notes = False
print( watching_video or taking_notes) # False
As long as one of the conditions is truthy, the “or” operator will always evaluate to True.
You can chain many “or”s together, the expression will evaluate to True, if at least one side of “or” evaluates to True,
print(True or False or False or False ) # True
print(False or False or False or False) # False
Another convinient way to write a long sequence of chained “or” operator is using the “any” builtin, which works the same as chaining multiple “or”s over multiple boolean values or expressions.
print(any([True , False , False , False ])) # True
print(any([False, False, False, False])) # False
“or” receives a list of boolean values or expressions, and evaluates to True, if any value is equal to True.
v1,v2,v3,...,vN are boolean values (True, False) or boolean expressions.
any([v1,v2,v3,...,vN]) # True only if all the values are truthy.
Logical “not”:
The logical “not” operator is quite simple compared to the last two. It simply flips the logical state of the boolean value or expression.
If it is True it becomes False, whereas if it is False, it becomes True.
For example, to flip the state of the watching_video boolean variable, we preceed it with the “not” operator.
watching_video = True # Can also be a boolean expression such as ( 1 == 1)
print( not watching_video) # False
watching_video = False # Can also be a boolean expression such as ( 1 == 3)
print( not watching_video) # True
More About Boolean Logic
Short Circuit Evaluation
the python interpreter is smart enough to stop the evaluation of a boolean expression when it’s obviously either Falsy or Truthy.
For example for the “and” operator False and True evaluation is short-circuited or stopped at the first falsy value, and evaluates to it (False).
print(False and True and True and True) # False: Evaluation Stops at False.
The same thing apply when all is used instead.
print(all([False ,True ,True , True])) # False: Evaluation Stops at False.
For the “or” operator the interpreter stops the evaluation at the first truthy value and then returns it.
For example for the “or” operator True and False evaluation is short-circuited or stopped at the first truthy value, and evaluates to it (True).
print(True or False or False or False) # False: Evaluation Stops at False.
The same thing apply when any is used instead.
print(any([True, False, False, False])) # False: Evaluation Stops at False.
Truthy and Falsy Values
Although logical operators are usually used with boolean values or expressions, they can actually be used with any value type because the interpreter will implicitly cast those values to booleans.
For example:
Noneget casted toFalse.- Any float or int that is non equal to zero gets casted to
True, while zero gets casted toFalse. - An empty String gets casted to
False, while a non-empty one gets casted toFalse. - Basically any empty value or data structure ([], set(), {},…) gets casted to
False. - A simple rule of thumb is asking this question “Does this value or data structure signal absence or emptiness?”, if the answer is yes, then that means that the interpreter will cast it to
False.
You can test it yourself, by using the bool builtin.
print(bool(None)) # False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool(50)) # True
print(bool(-50)) # True
print(bool(1.55)) # True
print(bool("")) # False
# We will learn more about these data structure later, all you need to know is that they evaluate to false when they are empty
print(bool([])) # False
print(bool(set())) # False
print(bool({})) # False
# ... Enjoyed this article?
I'm currently open to new roles — remote-first or international. If something resonated or you'd like to collaborate, I'd love to hear from you.
This article was originally published on https://sidaliassoul.com/blog/mastering-python-operators-from-basic-arithmetic-to-shorthand-syntax/. It was written by a human and polished using grammar tools for clarity.