Accueil Blog Projets CV Contact

Cet article n'est pas encore disponible en français. Vous lisez la version anglaise.

Mastering Python Operators: From Basic Arithmetic to Shorthand Syntax

Sidali Assoul Sidali Assoul 9 min de lecture

Dernière mise à jour le

Introduction

Variables by themselves are just data bags, to build a useful program you need to manipulate the values that are stored in the variables, compare them, and make decisions based on the results.

In this chapter, you’ll learn Python’s arithmetic, comparison, logical, and assignment operators, along with a few useful shortcuts that you’ll use in almost every Python program.

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:

  1. None get casted to False.
  2. Any float or int that is non equal to zero gets casted to True, while zero gets casted to False.
  3. An empty String gets casted to False, while a non-empty one gets casted to False.
  4. Basically any empty value or data structure ([], set(), {},…) gets casted to False.
  5. 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
# ...

Summary

Arithmetic Operators

+   # Addition
-   # Subtraction
*   # Multiplication
/   # Division
//  # Floor division
%   # Modulo (remainder)
**  # Exponentiation

Comparison Operators

==  !=  <  >  <=  >=

All comparison operators evaluate to either True or False.

Assignment Operators

x = 10

x += 3
x -= 2
x *= 2
x /= 4
x //= 2
x %= 3
x **= 2

Logical Operators

and
or
not

For multiple conditions:

all([...])   # True if every value is truthy
any([...])   # True if at least one value is truthy

Repetition Operator

"-" * 10

Key Notes for Memorization

  • Arithmetic operators manipulate numeric values.
  • Comparison operators always produce a boolean (True or False).
  • Shorthand assignment operators (+=, *=, etc.) update a variable without repeating its name.
  • and requires all conditions to be truthy, while or requires at least one.
  • not simply reverses a boolean value.
  • Python short-circuits boolean expressions, stopping evaluation as soon as the final result is known.
  • Empty values (None, 0, "", [], {}, set(), …) are falsy, most non-empty values are truthy.

Conclusion

You now know how to manipulate values with arithmetic operators, compare them to produce boolean results, and combine conditions using Python’s logical operators.

In the next chapter, we’ll put these operators into practice by using them inside conditional statements to make our programs choose between different execution paths.

Continue to Python Conditional Statements: If-Else, Expressions, and Match-Case

Cet article vous a plu ?

Je suis ouvert à de nouveaux postes, en télétravail ou à l'international. Si quelque chose vous a parlé ou si vous souhaitez collaborer, j'adorerais en discuter.

Se connecter sur LinkedIn
Sidali Assoul

Écrit par

Sidali Assoul

Ingénieur logiciel avec 5 ans d'expérience en développement web et mobile full stack, un bilan éprouvé en data science, recherche et solutions IA modernes, avec une approche orientée business pour livrer des produits à forte valeur ajoutée.