Logo
Syntax and Basics

Operators

As a software engineer, you understand that operators are the tools that allow you to manipulate data and make decisions in your code. Python offers a wide range of operators, from basic arithmetic to complex logical operations. This section aims to provide you with a thorough understanding of how to use these operators effectively.

Arithmetic Operators

Arithmetic operators perform mathematical operations on numbers. The basic arithmetic operators in Python are:

  • Addition (+): Adds two numbers.
  • Subtraction (-): Subtracts the right-hand operand from the left-hand operand.
  • Multiplication (*): Multiplies two numbers.
  • Division (/): Divides the left-hand operand by the right-hand operand.
  • Modulus (%): Returns the remainder of division.
  • Floor Division (//): Divides and rounds down to the nearest integer.
  • Exponentiation (**): Raises the left-hand operand to the power of the right-hand operand.
# Arithmetic operators in action
sum_result = 5 + 3  # 8
difference = 5 - 3  # 2
product = 5 * 3  # 15
quotient = 5 / 3  # 1.6667

Comparison Operators

Comparison operators are used to compare two values and return a Boolean result (True or False):

  • Equal (==): Checks if two values are equal.
  • Not Equal (!=): Checks if two values are not equal.
  • Greater Than (>): Checks if the left-hand operand is greater than the right-hand operand.
  • Less Than (<): Checks if the left-hand operand is less than the right-hand operand.
  • Greater Than or Equal (>=): Checks if the left-hand operand is greater than or equal to the right-hand operand.
  • Less Than or Equal (<=): Checks if the left-hand operand is less than or equal to the right-hand operand.
# Comparison operators in action
is_equal = (5 == 3)  # False
is_greater = (5 > 3)  # True

Logical Operators

Logical operators are used to combine conditional statements:

  • AND (and): Returns True if both conditions are true.
  • OR (or): Returns True if at least one condition is true.
  • NOT (not): Reverses the result of a condition.
# Logical operators in action
result_and = (5 > 3) and (5 < 10)  # True
result_or = (5 < 3) or (5 > 3)  # True
result_not = not (5 == 3)  # True

Book a conversation with us for personalize training today!

Was this helpful?
Logo