Home
About Us Privacy Policy
 

OPERATORS IN PYTHON PART 1

ADVERTISEMENT

Beginner Operators I



What are Operators, and why are they used?

In programming, operators are useful for manipulating data. But before we cover operators in Python, let us take a real-world example of what an operator is and what it does. Suppose you might want to go somewhere, what do you do? Compare prices of different travel means, book a ticket, board, and rest till you reach your destination. To you, the task of getting yourself to your travel destination doesn't seem that tedious. But the same cannot be said for the vehicle operator. Let us say that you choose to travel via. a Train. For the duration of the journey, the train operator(s) performed many operations such as changing tracks, coordinating with other trains, communicating the status to respective authorities, relaying current, monitoring the control panel, and all of this is unbeknownst to the passenger(s). Now, let's switch roles for a moment and assume that you, the programmer are the train operator, and the software users are the passengers. It is your responsibility to write programs to achieve the desired outcome. Fortunately, Python being a high-level programming language, provides you the tool to achieve exactly that.

You don't have to use every operator, just the required ones at the time necessary.


ADVERTISEMENT

Types of operators in Python

The operators defined in the Python programming language are as follows:

  • Arithmetic operators
  • Assignment operator
  • Comparison operators
  • Logical operators
  • Bitwise operators
  • Compound Operators
  • Identity operators
  • Membership operators
Let's cover every operator type in detail and understand their usage.


Arithmetic operators

Arithmetic operators are useful for manipulating numerical values. Examples of numerical values include your age, bank balance, credit score, number of external accounts linked, etc.

The following are the arithmetic operators:

Operator Description Example Output
+ The Addition Operator is used to perform the addition of two numbers.
print(1+7)
8
- The Subtraction Operator is used to perform the subtraction of two numbers.
print(9-1)
8
* The Multiplication Operator is used to perform the multiplication of two number s.
print(4*2)
8
/ The Division Operator is used to perform division on two numbers. This operator will return a value of float data type, if not wholly divisible.
print(15/2)
7.5
% The Modulus(Remainder) Operator performs modulus on two numbers.
print(15%2)
1
** The Exponential Operator is used to perform exponential on two numbers.
print(2**3)
8
// The Floor Division Operator is used to perform floor division on two numbers. It is different than "division" as it will always return an int value.
print(15//2)
7


Assignment Operator

The Assignment operator is an operator used to assign values to a variable. We have been using the "=" (assignment operator) to associate a value to a variable during the previous few examples. Its sole purpose is to assign a value to a variable.

Do not confuse this with the Mathematical equals operator. Despite using the same operator, they are very different.

# Assignment Example
my_name = "James Bond"
my_age = 40


ADVERTISEMENT

Comparison Operators

To compare two values against each other, Python provides the comparison operators. Think of it as comparing prices of two products, quality of the material, features, brand, etc., and then decide which to purchase; and that's is how we operate in daily life. To replicate this capability in software development, Python provides the comparison operators.

The following are the assignment operators:

Operator Description Example Output
== This operator is used to test two variable for equality.
x, y = 0, 1; x == y
False
!= This operator is used to test two variable for difference.
x, y = 0, 1; x != y
True
< This operator is used to test whether the value on the left is less than the value on the right.
x, y = 0, 1; x < y
True
> This operator is used to test whether the value on the left is more than the value on the right.
x, y = 0, 1; x > y
False
<= This operator is used to test whether the value on the left is less than or equal to the value on the right.
x, y = 0, 1; x <= y
True
>= This operator is used to test whether the value on the left is more than or equal to the value on the right.
x, y = 0, 1; x >= y
False

Here are some examples:

# Variables
x = 8
y = 7

# Equals Operator
print(x == y)

# Difference Operator
print(x !== y)

# Less Than Operator
print(x < y)

# More Than Operator
print(x > y)

# Less than or Equals to
print(x <= y)

# More than or equals to
print(x >= y)

False
True
False
True
False
True


ADVERTISEMENT

Logical Operators

To understand logical operators, we must first understand how humans typically think about decision-making. Suppose you are in the market looking to buy a car from a dealership, and your preferences are as follows:

  • all-wheel drive
  • automatic
  • in the budget bracket of $10,000 - $20,000
  • must have mileage less than 60,000
  • good condition
  • must have a panoramic sunroof
  • must be five-seater
What are you going to say to the dealership?

Give it a try yourself, and then click to reveal the answer.

Now let's represent the above as a Python expression.

# Requirements
all_wheel_drive = True
no_of_seats = 5
condition = "good"
has_panoramic_sunroof = True
total_miles = 55301
cost = 17000

# Check for requirement match
car_found = all_wheel_drive == True and no_of_seats == 5 and condition == "good"
and has_panoramic_sunroof and total_miles < 60000 and cost >= 10000 and cost <= 20000

# Print status
print(car_found)

True

Notice, "has_panoramic_sunroof" does not have any associated value comparison. When comparing boolean values, explicit comparison with "True" or "False" becomes optional. A variable of boolean data types can have only two values and is handled accordingly by Python. These two expressions are the same, just syntactically different.

credit_score = 800
score_excellent = credit_score >= 800
print("Is credit score excellent : ", score_excellent)    # TRUE
print("Is credit score excellent : ", score_excellent == True)   # TRUE, is explicit

True
True

However, it would be best always to mention the value you are comparing against to make the code readable and explicit.

Now let's go through all the logical operators that Python provides.


The and operator

The resulting value will be True when two expressions evaluate to True.

debt_amount = 0.00
credit_score = 813
print(debt_amount < 500.00 and credit_score >= 800)  # TRUE

True


The or operator

The resulting value will be True if either of the two expressions evaluates to True.

debt_amount = 0.00
credit_score = 813
print(debt_amount < 500.00 or credit_score >= 800)  # TRUE

True

In the above example, only one expression can be True for the resulting value to be True.


The not operator

This operator will reverse the boolean value of the expression. If the expression evaluates to the boolean value of True, it will convert it into a False and vice-versa.

debt_amount = 713.00
credit_score = 813
is_eligible = debt_amount < 500.00 or credit_score >= 800  
print("Are you eligible for credit : ", not is_eligible )  # FALSE

False

The not operator is usually well suited when used in conjunction with functions and will be revisited later.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.