Different Operators and Operands in Python
Python has many operators and operands. Python supports arithmetic, assignment, comparison, and logical operators. The precedence of Arithmetic Operators and Boolean expressions are discussed.
By the end of this page, you will understand the following:
- What are Arithmetic Operators and how they are used to do arithmetic in Python.
- What are Comparison Operators and how they are used to campare two values to help the program in decision making.
- You will learn also about the Logical Operators. these operators produce Boolean result (True or False).
- What is precedence of operators.
Arithmetic Operators
We got an introduction to Arithmetic Operators in the Python Arithmetic chapter.
Introduction to Comparison Operators
Apart from doing the arithmetic operations that you learned in the Python Arithmetic chapter, the computer can also do a comparison between the values stored in two variables. Comparison operators are used for finding the smaller of the two values (“less than”), finding the greater of two values (“greater than”), or finding if the value of two variables is equal (==). These operations enable the computer program to make decisions on what branch of code to execute next depending on the results of the comparison test.
Introduction to Logical Operators
Another type of operator is the Logical Operator. These logical operators produce a Boolean result of the values stored in two variables. Boolean result refers to a result that is either ‘true’ or ‘false’.
Examples of the logical operators are ‘AND’, ‘OR’, and ‘NOT’ operators.
We will write several programs using the logical operators when we introduce program flow control concepts.
As mentioned above, there are several different types of operators (arithmetic operators, logical operators, comparison operators, and assignment operators). Let us first review each of them one at a time. Let’s start with the Arithmetic Operators.
Operators and Operands – Arithmetic Operators
In this section, we will discuss more details on the arithmetic operators over what we learned in the Python Arithmetic chapter.
For the Table below, let us assume the two operands X and Y have the values below.
Operand X = 6
Operand Y = 3
OPERATOR | DESCRIPTION | EXAMPLE |
---|---|---|
Addition (+) | Add two numbers on either side of + operator. | X + Y = 9 |
Subtraction (-) | Subtract right-hand operand from the left-hand operand. | X – Y = 3 |
Multiplication (*) | Multiply the operands on either side of multiply operator. | X * Y = 18 |
Division (/) | Divide left hand operator by right hand operand. | X / Y = 2 |
Division (//) | Divide left hand operator by right hand operand, ignore the remainder. | X//Y = 2 |
Modulus (%) | Divide left hand operator by right hand operand and find the remainder. | X % Y = 0 |
Exponent (**) | Raise to the power | X**y = 6 raised to power 3 = 6*6*6 = 216 |
Note:
1) For any combination of +, -, and * arithmetic operators, if the operands are of type int
, the result is of type int.
2) If the expression has a division operator (/), then the result is float data type.
3) If either of the operands is of float
data type, the result is of float
data type.
Precedence of Arithmetic Operators
In this section, we introduce the concept of precedence of operators. Precedence defines which of the arithmetic operators are higher priority than the others.
Generally, the programs have several operators like +, -, *, /, **, and parenthesis in the same expression.
To evaluate expressions involving several different types of operators, Python assigns an order for which an operator must be evaluated first, which operator will be solved second, and so on. This is called the precedence of arithmetic operators.
The precedence order is:
- Parenthesis
- Exponentiation
- Multiply and divide
- Add and subtract
Expression With No Parenthesis and No Exponentiation
If there are no parentheses and no exponentiation in the expression, the first operation to be done is the multiply and/or divide operation. The result of this multiply or divide operation is then used to evaluate other operators like add and subtract. Multiply and divide are thus said to have higher precedence than add and subtract.
>>> 5 +10*2 – 3.
In the above expression, Python will first multiply 10 and 2 to get the result of 20.
The expression will then look like 5 + 20 – 3
Python will then use add and subtract operator to get the final result = 22.
Expression with Exponentiation
For expressions with exponentiation and multiply and divide, exponentiation has higher precedence than multiply and divide. Therefore exponentiation is evaluated first. The below expression explains this.
2**3*4 + 5
Exponention is higher priority than multiply or add. Therefore, 2**3 is evaluated first resulting in answer = 8. The resulting expression is 8*4 + 5.
Multiply has higher precedence than add. Therefore, 8 is then multiplied by 4 resulting in 32. The resulting expression is 32 + 5. Then, 5 is added to 32 to give the result = 37.
Expression With Parenthesis
Parenthesis has higher precedence than multiplication and division. Therefore, parenthesis is evaluated before the multiply operation.
In the below expression
(5 + 6) * 2
Python will first evaluate the parenthesis (5 + 6) to get the result = 11. The resulting expression will become 11 * 2. Then, 11 is multiplied by 2 to get the result of 22.
In the next chapter, we will use the above arithmetic operators to solve simple arithmetic problems with integers and floating-point data type.
Next, we introduce the Python Comparison Operators.
Operators and Operands – Comparison Operators
The Comparison operators compare two operands. The value of operands on the left side and the right side of the operator are compared to test a condition on two operands. If the test of the condition passes, it returns a true (yes), else it returns a false (no).
Let us use the example of your friend’s age to explain Comparison Operators.
Michael_age = 7
Steve_age = 8
Robert_age = 7
The table below shows the result of several comparison operations using the friends’ ages.
Comparison Operators Example
Operator | Description | Example |
== | Equal. If the value of the operands on the two sides of operator are equal, then condition is true | Michael_Age == Steve_Age returns false. Michael_Age == Robert_Age returns true. |
!= | Not equal | Michael_Age != Steve_Age returns true. Michael_Age != Robert_Age returns false. |
> | Greater than. If the operand on left of > operator is greater than operand on right side of operator, it returns true, otherwise returns false. | Michael_Age > Steve_Age returns false. Michael_Age > Robert_Age returns false. |
< | Less than. If he operand on left of < operator is less than operand on right side of the operator, it returns true, otherwise returns false. | Michael_Age < Steve_Age returns true. Michael_Age < Robert_Age returns false. |
>= | Greater than OR equal. If the operand on left of >= operator is greater than OR equal to operand on right side of operator, it returns true, otherwise returns false. | Michael_Age >= Robert_Age returns true. Michael_Age >= Steve_Age returns false. |
<= | Less than OR equal. If he operand on left of <= operator is less than OR equal to operand on right side of the operator, it returns true, otherwise returns false. | Michael_Age <= Robert_Age returns true. Steve_Age <= Robert_Age returns false. |
<> | Greater than OR Less than. If the values of the operand on the left of <> operator is not equal to operand on the right, then it returns a true. | Michael_Age <> Steve_Age returns true. Michael_Age <> Robert_Age returns false. |
There are many Assignment Operators in Python, There is one assignment operator we use in the our program examples below. It is described below.
Assignment Operator
Assignment operator is used to assign a value to a variable.
OPERATOR | DESCRIPTION | EXAMPLE |
---|---|---|
Operator | Description | Example |
= | Assigns the value on the right of operator to the variable on the left of the operator | Sum_of_ages = Michael_age + Steve_age + Robert_age. 7 + 8 + 7 = 22. The value 22 is assigned to the variable “Sum_of_ages” on the left side of the = sign. |
Finally, we describe what the Python Logical Operators are.
Operators and Operands – Logical Operators
Logical operators in Python are based on Boolean Algebra (see Enrichment section at the end of this chapter). Python has three Boolean operators (also called logical operators). There are:
- AND logical operator,
- OR logical operator, and
- NOT logic operator
Python has a Boolean variable bool,
which is a subclass of type int
. The bool
type can take only two values True
or False
. These values are built-in constants in the Python language and are implemented as integers with the value 1 for True
and 0 for False. True
and False
are keywords of the language; so be careful to not use them as identifiers.
The following are details of the three logic operators: AND logical operator, OR logical operator, and NOT logical operator.
Before we start to discuss the AND, OR, and NOT logical operators in detail, let us describe what Boolean Expressions are.
Boolean Expressions
Any comparison condition is a Boolean expression. The comparison test may evaluate to a “True” result or it may evaluate to a “False” result.
A few examples of Boolean expressions are:
>>> 6 != 5
# 6!= 5 is a Boolean expression. Since 6 is not equal to 5, this expression will evaluate to True
.
>>> 5 > 1
# 5 > 1 is a Boolean Expression. Since 5 is greater than 1, this Boolean expression will also evaluate to True
.
>>> “Good morning” == “G’morning”
This Boolean Expression does a comparison test to check if the string “Good morning” is equal to the string “G’morning”. This Boolean Expression will evaluate to False
since the expression on the left side of the == symbol is not equal to the expression on the right side of the == sign.
Now that we know what a Boolean expression is, let us see how the AND Logical operator evaluates the condition in the Boolean expressions and produce the “True” or “False” result.
The AND Logical Operator:
Python’s AND operator works with two operands that are on either side of the AND logical operator. These operands are Boolean expressions, objects, or a combination. The operands in an AND expression are commonly known as conditions.
The AND logical operator tests the two Boolean expressions for a test condition specified in the Boolean expression to see if the test is True or False. If both Boolean expressions’ test results are True, then the logical AND operation gives a True result.
If either of the two Boolean expressions’ test results is False, the AND operation gives a False result.
Examples of AND Logical Operator With Boolean Expressions
Example 1:
>>> 7 > 3
7> 4 and
Since the Boolean expression 7 > 3 is true and the expression 7 > 4 is also True, both expressions are True. Since both expressions on either side of the AND logical operator are True, the result of the AND operation is True
. Note that both Boolean expressions on either side of the AND operator must be True for the AND operator to result in a True
result.
Example 2:
>>> 8 != 8 and
7 == 7
Since 8 is equal to 8, the Boolean expression 8 !=8 evaluates to False. The second expression 7 == 7 evaluates to True. As described above, for the logical operator AND to produce a True
result, both Boolean expressions on either side of the AND operator must evaluate to True. If any one of the two Boolean expressions is False, the AND operation results in a False
result. In this example, the result evaluates to False
.
The OR Logical Operator:
On the other hand, if the Boolean expression on either side of the OR logical operator evaluates to true
, then the result of the OR Logical operation is True
. For the OR logical operation to provide a False
result, BOTH the Boolean expressions must evaluate to False.
In summary, if either of the Boolean expression condition tests is True, the OR logical operator gives a True result. Only if BOTH of the Boolean expression test results are False, then the OR operation gives a False result.
The NOT Logical Operator:
The NOT operator is a negation of an expression.
For example, let us say the variables a and b are as follows:
a = 5
b = 3.
So, expression (a > b) is True.
Using the negation operator NOT, the expression NOT( a > b) will evaluate to False
.
Summary Of Logical Operators
The Table below summarizes how the three logical operators work.
OPERATOR | DESCRIPTION | EXAMPLE |
---|---|---|
Operator | Description | Example |
AND | It is a logical AND of two operands. Both operands must be true for the condition to be true. | See below |
OR | It is logical OR. If either one of the operands is true, then the condition is true. | See below |
NOT | Negates the expression. If (a>b) is true, then NOT(a>b) evaluates false | See below |
These three logical operators allow us to build complex Boolean expressions. For information on Boolean logic, refer to Enrichment: Boolean Algebra at the end of the chapter.
Logical operators are used in program flow control. They are normally used with if, or while control statements. They allow a program to make a decision based on the results of a test condition regarding what to do next in the program flow.
How Do We Use Logical Operators
The following examples demonstrate different ways that logical conditions can be used.
Suppose, we have the following data:
Michael_age = 9
Steve_age = 8
Catherine_age = 7
Then, the expression (Michael_age > Steve_age) is true.
(Steve_age > Catherine_age) is also true.
(Michael_age < Steve_age) is false.
The expressions below show the result of logical operations.
(Michael_age > Steve_age) AND (Steve_age > Catherine_age) is evaluated as true.
(Michael_age < Steve_age) AND (Steve_age > Catherine_age) is evaluated as false.
(Michael_age < Steve_age) OR (Steve_age > Catherine_age) is evaluated as true.
Logical Operator Example with Modulus Operator (%)
As another example, let us use an expression with the modulus operator (%). You will recall that the % arithmetic operator tells us that the numerator is completely divisible by the denominator (that is, there is no remainder). Let us look at the expression,, n % 2 == 0 OR n % 3 == 0.
This logical expression will evaluate true if either or both of the conditions are true, that is, if the number n is divisible by 2 OR n is divisible by 3.
Now let us look at an expression that has an AND operator, n % 2 == 0 AND n % 3 == 0.
This expression will evaluate to true if both expressions evaluate to true. If either of the two expressions is false, then the expression n % 2 == 0 AND n % 3 == 0 will evaluate as false.
In the Flow Control chapter, you will see how the Comparison Operators and Logical Operators are used to helping the program make decisions in the program flow control. The Program Flow Control controls (decides) which branch of code to execute next depending on the result of a previous comparison operation test or a logical operation test.
Enrichment: Boolean Algebra
What you have studied in school math and algebra deals with numbers based on a number system called the decimal system. This system uses digits from 0 through 9. The computers are constructed using transistors, which are essentially switches, meaning the switches are either ON or OFF. Thus, computers use a number system that consists of only two numbers ‘0’ and ‘1’ or also referred to as ‘OFF’ and ‘ON’. This number system is called the Binary System. The algebra based on a binary system is called Boolean Algebra. You can make simple or very complex logical expressions using the three logic operators, AND, OR, and NOT. The table below shows a very simple example of the logic you can do using the logical operators. This table is called a Truth Table.
Truth Table
A truth table allows us to list all the possible combinations of inputs and the corresponding output for the logical operators. The table shows two variables x and y. Each of these two variables can be True or False. Therefore, there are four possible combinations of the variables x and y. These combinations are False-False, False-True, True-False, and True-True. For each of these combinations of inputs x and y, the third column of the table lists the output of the logic operation of AND. The fourth column of the table lists the output of the logic operation OR.
Boolean Algebra TRUTH TABLE
x | y | x AND y | x OR y |
---|---|---|---|
False | False | False | False |
False | True | False | True |
True | False | False | True |
True | True | True | True |
If there were three inputs x, y, and z, the table will have 8 combinations. The table will then have 8 rows in the truth table.
Source: https://en.wikipedia.org/wiki/George_Boole
George Boole (1815 – 1864) was a self-taught English mathematician, philosopher, and logician. He was the first professor of mathematics at Queen’s College, Cork in Ireland. He worked in the field of differential equations and algebraic logic and is best known as the author of The Laws of Thought (1854), which contains Boolean Algebra. Boolean logic is credited with laying the foundations of the information age.
Source: Wikipedia
Copyright © 2019 – 2024 softwareprogramming4kids.com
All Rights Reserved