Introduction
Operators are special symbols in Python that perform specific operations on one or more values or variables. These operations can include arithmetic calculations, assignment, comparison, and logical operations. Expressions are combinations of values and operators that Python can evaluate to produce a result.
Operators and expressions are an essential part of Python programming, and understanding how to use them effectively is a key part of becoming a proficient Python developer. In this article, we will explore the various types of operators available in Python and how to use them in expressions. We will also discuss operator precedence and provide some tips and best practices for working with operators and expressions in Python.
Basic arithmetic operators
Python provides several basic arithmetic operators that can be used to perform calculations on numeric values. These include:
- Addition: The addition operator (+) adds two values together. For example,
5 + 7
evaluates to 12. - Subtraction: The subtraction operator (-) subtracts one value from another. For example,
5 - 7
evaluates to -2. - Multiplication: The multiplication operator (*) multiplies two values together. For example,
5 * 7
evaluates to 35. - Division: The division operator (/) divides one value by another. For example,
7 / 5
evaluates to 1.4. - Modulus: The modulus operator (%) returns the remainder of dividing one value by another. For example,
7 % 5
evaluates to 2. - Exponentiation: The exponentiation operator (**) raises one value to the power of another. For example,
7 ** 5
evaluates to 16,807.
Here are some examples of using these operators in Python:
>>> 5 + 7
12
>>> 5 - 7
-2
>>> 5 * 7
35
>>> 7 / 5
1.4
>>> 7 % 5
2
>>> 7 ** 5
16807
Comparison operators
Comparison operators allow you to compare two values and determine if they are equal, not equal, greater than, less than, greater than or equal to, or less than or equal to each other. Python provides the following comparison operators:
- Equal to: The equal to operator (==) returns
True
if two values are equal, andFalse
if they are not. For example,5 == 5
evaluates toTrue
, and5 == 6
evaluates toFalse
. - Not equal to: The not equal to operator (!=) returns
True
if two values are not equal, andFalse
if they are. For example,5 != 5
evaluates toFalse
, and5 != 6
evaluates toTrue
. - Greater than: The greater than operator (>) returns
True
if the value on the left is greater than the value on the right, andFalse
if it is not. For example,5 > 6
evaluates toFalse
, and6 > 5
evaluates toTrue
. - Less than: The less than operator (<) returns
True
if the value on the left is less than the value on the right, andFalse
if it is not. For example,5 < 6
evaluates toTrue
, and6 < 5
evaluates toFalse
. - Greater than or equal to: The greater than or equal to operator (>=) returns
True
if the value on the left is greater than or equal to the value on the right, andFalse
if it is not. For example,5 >= 5
evaluates to Continue - Greater than or equal to: The greater than or equal to operator (>=) returns
True
if the value on the left is greater than or equal to the value on the right, andFalse
if it is not. For example,5 >= 5
evaluates toTrue
, and5 >= 6
evaluates toFalse
.
- Less than or equal to: The less than or equal to operator (<=) returns
True
if the value on the left is less than or equal to the value on the right, andFalse
if it is not. For example,5 <= 5
evaluates toTrue
, and5 <= 4
evaluates toFalse
.
Here are some examples of using comparison operators in Python:
>>> 5 == 5
True
>>> 5 == 6
False
>>> 5 != 5
False
>>> 5 != 6
True
>>> 5 > 6
False
>>> 6 > 5
True
>>> 5 < 6
True
>>> 6 < 5
False
>>> 5 >= 5
True
>>> 5 >= 6
False
>>> 5 <= 5
True
>>> 5 <= 4
False
Logical operators
Logical operators allow you to perform logical operations on Boolean values (True
and False
). Python provides the following logical operators:
- And: The and operator returns
True
if both values areTrue
, andFalse
if either value isFalse
. For example,True and True
evaluates toTrue
, andTrue and False
evaluates toFalse
. - Or: The or operator returns
True
if either value isTrue
, andFalse
if both values areFalse
. For example,True or True
evaluates toTrue
, andTrue or False
evaluates toTrue
. - Not: The not operator returns the opposite of a Boolean value. For example,
not True
evaluates toFalse
, andnot False
evaluates toTrue
.
Here are some examples of using logical operators in Python:
>>> True and True
True
>>> True and False
False
>>> True or True
True
>>> True or False
True
>>> not True
False
>>> not False
True
Assignment operators
Assignment operators allow you to assign a value to a variable. Python provides the following assignment operators:
- Equals: The equals operator (=) assigns a value to a variable. For example,
x = 5
assigns the value 5 to the variablex
. - Addition assignment: The addition assignment operator (+=) adds a value to a variable and assigns the result to the variable. For example,
x += 5
is equivalent tox = x + 5
. - Subtraction assignment: The subtraction assignment operator (-=) subtracts a value from a variable and assigns the result to the variable. For example,
x -= 5
is equivalent tox = x - 5
. - Multiplication assignment: The multiplication assignment operator (*=) multiplies a variable by a value and assigns the result to the variable. For example,
x *= 5
is equivalent tox = x * 5
. - Division assignment: The division assignment operator (/=) divides a variable by a value and assigns the result to the variable. For example,
x /= 5
is equivalent tox = x / 5
. - Modulus assignment: The modulus assignment operator (%=) calculates the remainder of dividing a variable by a value and assigns the result to the variable. For example,
x %= 5
is equivalent tox = x % 5
. - Exponentiation assignment: The exponentiation assignment operator (**=) raises a variable to the power of a value and assigns the result to the variable. For example,
x **= 5
is equivalent tox = x ** 5
.
Here are some examples of using assignment operators in Python:
>>> x = 5
>>> x += 5
>>> x
10
>>> x -= 5
>>> x
5
>>> x *= 5
>>> x
25
>>> x /= 5
>>> x
5.0
>>> x %= 5
>>> x
0.0
>>> x **= 5
>>> x
0.0
Augmented assignment operators
Augmented assignment operators are a shorthand version of the assignment operators. They perform the same operation as the regular assignment operators, but the operator and the value being assigned are combined into a single operator. Python provides the following augmented assignment operators:
- Addition augmented assignment: The addition augmented assignment operator (+=) adds a value to a variable and assigns the result to the variable. For example,
x += 5
is equivalent tox = x + 5
. - Subtraction augmented assignment: The subtraction augmented assignment operator (-=) subtracts a value from a variable and assigns the result to the variable. For example,
x -= 5
is equivalent tox = x - 5
. - Multiplication augmented assignment: The multiplication augmented assignment operator (*=) multiplies a variable by a value and assigns the result to the variable. For example,
x *= 5
is equivalent tox = x * 5
. - Division augmented assignment: The division augmented assignment operator (/=) divides a variable by a value and assigns the result to the variable. For example,
x /= 5
is equivalent tox = x / 5
. - Modulus augmented assignment: The modulus augmented assignment operator (%=) calculates the remainder of dividing a variable by a value and assigns the result to the variable. For example,
x %= 5
is equivalent tox = x % 5
. - Exponentiation augmented assignment: The exponentiation augmented assignment operator (**=) raises a variable to the power of a value and assigns the result to the variable. For example,
x **= 5
is equivalent tox = x ** 5
.
Here are some examples of using augmented assignment operators in Python:
>>> x = 5
>>> x += 5
>>> x
10
>>> x -= 5
>>> x
5
>>> x *= 5
>>> x
25
>>> x /= 5
>>> x
5.0
>>> x %= 5
>>> x
0.0
>>> x **= 5
>>> x
0.0
Operator precedence
Operator precedence determines the order in which Python evaluates expressions. Some operators have higher precedence than others, which means they are evaluated before operators with lower precedence. For example, in the expression 5 + 7 * 3
, the multiplication operator (*
) has higher precedence than the addition operator (+
), so the multiplication is performed first and the result is added to 5.
Here is the order of precedence for Python operators, from highest to lowest:
- Exponentiation (
**
) - Unary operators (e.g.,
+
,-
) - Multiplication, division
- Addition, subtraction
- Comparison operators (e.g.,
<
,>
,==
,!=
) - Logical operators (
and
,or
,not
) - Assignment operators (e.g.,
=
,+=
,-=
) - You can use parentheses to override the default operator precedence and specify the order in which operations should be performed. For example, in the expression
(5 + 7) * 3
, the addition is performed first because it is enclosed in parentheses. - Examples of operator and expression use
- Here are some examples of using operators and expressions in Python:
>>> 5 + 7
12
>>> 5 - 7
-2
>>> 5 * 7
35
>>> 7 / 5
1.4
>>> 7 % 5
2
>>> 7 ** 5
16807
>>> 5 == 5
True
>>> 5 == 6
False
>>> 5 != 5
False
>>> 5 != 6
True
>>> 5 > 6
False
>>> 6 > 5
True
>>> 5 < 6
True
>>> 6 < 5
False
>>> 5 >= 5
True
>>> 5 >= 6
False
>>> 5 <= 5
True
>>> 5 <= 4
False
>>> True and True
True
>>> True and False
False
>>> True or True
True
>>> True or False
True
>>> not True
False
>>> not False
True
>>> x = 5
>>> x += 5
>>> x
10
>>> x -= 5
>>> x
5
>>> x *= 5
>>> x
25
>>> x /= 5
>>> x
5.0
>>> x %= 5
>>> x
0.0
>>> x **= 5
>>> x
0.0
>>> (5 + 7) * 3
24
>>> 5 + (7 * 3)
26
Tips and best practices
Here are some tips and best practices for working with operators and expressions in Python:
- Use parentheses to specify the order of operations.
- Use whitespace to make your code more readable. For example, you can use a space around operators to make expressions easier to read, like
5 + 7
instead of5+7
. - Use variables to store values that you will use multiple times, rather than recalculating them each time.
- Use appropriate data types for your values. For example, use integers for whole numbers and floating point numbers for decimal values.
- Use Python’s built-in functions and modules to perform common tasks, rather than writing your own code.
Complete example using basic operator and expressions
# Calculate the area of a rectangle
# Get the length and width from the user
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
# Calculate the area
area = length * width
# Print the result
print("The area of the rectangle is", area)
# Check if a number is even or odd
# Get a number from the user
num = int(input("Enter a number: "))
# Use the modulus operator to check if the number is even or odd
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
# Find the largest number
# Get three numbers from the user
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
num3 = int(input("Enter a number: "))
# Use the max function to find the largest number
largest = max(num1, num2, num3)
# Print the result
print("The largest number is", largest)
Conclusion
Operators and expressions are a crucial part of Python programming, and understanding how to use them effectively is an important part of becoming a proficient Python developer. In this article, we have explored the different types of operators available in Python and how to use them in expressions. We have also discussed operator precedence and provided some tips and best practices for working with operators and expressions in Python.