Python Operators

by Pyrastra Team
Python Operators

Python supports many types of operators. The table below lists Python operators from highest to lowest priority. With variables and operators, we can construct various expressions to solve practical problems. In computer science, an expression is a syntactic entity in a computer program that consists of one or more constants, variables, functions, and operators combined together, which the programming language can interpret and calculate to obtain another value. It doesn’t matter if you don’t understand this sentence, but you must know that constructing expressions is very important regardless of what programming language you use.

OperatorDescription
[], [:]Index, slice
**Power
~, +, -Bitwise NOT, positive sign, negative sign
*, /, %, //Multiply, divide, modulo, floor division
+, -Add, subtract
>>, <<Right shift, left shift
&Bitwise AND
^, ``
<=, <, >, >=Less than or equal, less than, greater than, greater than or equal
==, !=Equal, not equal
is, is notIdentity operators
in, not inMembership operators
not, or, andLogical operators
=, +=, -=, *=, /=, %=, //=, **=, &=, `=, ^=, >>=, <<=`

Note: Priority refers to the order in which operations should be executed when multiple operators appear in an expression. When writing code, if you’re unsure about operator priority in an expression, you can use parentheses to ensure the execution order.

Arithmetic Operators

Python has very rich arithmetic operators. Besides the most familiar addition, subtraction, multiplication, and division, there are also floor division, modulo (remainder), and power operators. The following example demonstrates the use of arithmetic operators.

"""
Arithmetic operators

Version: 1.0
Author: Luo Hao
"""
print(321 + 12)     # Addition operation, output 333
print(321 - 12)     # Subtraction operation, output 309
print(321 * 12)     # Multiplication operation, output 3852
print(321 / 12)     # Division operation, output 26.75
print(321 // 12)    # Floor division operation, output 26
print(321 % 12)     # Modulo operation, output 9
print(321 ** 12)    # Power operation, output 1196906950228928915420617322241

Arithmetic operations require multiplication and division before addition and subtraction, which is no different from what’s taught in math textbooks. That is, the priority of multiplication and division is higher than addition and subtraction. If there’s also a power operation, the power operation has higher priority than multiplication and division. If you want to change the execution order of arithmetic operations, you can use parentheses in English input mode. Expressions written in parentheses will be executed first, as shown in the following example.

"""
Priority of arithmetic operations

Version: 1.0
Author: Luo Hao
"""
print(2 + 3 * 5)           # 17
print((2 + 3) * 5)         # 25
print((2 + 3) * 5 ** 2)    # 125
print(((2 + 3) * 5) ** 2)  # 625

Assignment Operators

Assignment operators should be the most common operators. Their role is to assign the value on the right to the variable on the left. Assignment operators can also be combined with the arithmetic operators above to form compound assignment operators. For example: a += b is equivalent to a = a + b, and a *= a + 2 is equivalent to a = a * (a + 2). The following example demonstrates the use of assignment operators and compound assignment operators.

"""
Assignment operators and compound assignment operators

Version: 1.0
Author: Luo Hao
"""
a = 10
b = 3
a += b        # Equivalent to: a = a + b
a *= a + 2    # Equivalent to: a = a * (a + 2)
print(a)      # Calculate what will be output here

Assignment expressions themselves don’t produce any value. That is, if you put an assignment expression in the print function trying to output the expression’s value, it will produce a syntax error. To solve this problem, Python 3.8 introduced a new assignment operator :=, which we call the walrus operator. You can guess why it’s called that. The walrus operator also assigns the value on the right side of the operator to the variable on the left, but unlike the assignment operator, the value on the right side of the operator is also the value of the entire expression. Look at the code below and you’ll understand.

"""
Walrus operator

Version: 1.0
Author: Luo Hao
"""
# SyntaxError: invalid syntax
# print((a = 10))
# Walrus operator
print((a := 10))  # 10
print(a)          # 10

Tip: If line 8 in the above code isn’t commented out, running the code will show a SyntaxError: invalid syntax error message. Note that in this line of code, we added parentheses around a = 10. If you accidentally write print(a = 10), you’ll see a TypeError: 'a' is an invalid keyword argument for print() error message. When we get to functions later, you’ll understand what this error message means.

Comparison and Logical Operators

Comparison operators, also called relational operators, include ==, !=, <, >, <=, >=. I believe everyone can understand these at a glance. It’s worth reminding that comparing equality uses == - note these are two equal signs, because = is the assignment operator we just covered. Comparing inequality uses !=, which is different from the $\small{\neq}$ used in math textbooks. Python 2 once used <> to represent not equal, but using <> in Python 3 will cause a SyntaxError (syntax error). Comparison operators produce boolean values, either True or False.

There are three logical operators: and, or, and not. and literally means “and”, so the and operator connects two boolean values or expressions that produce boolean values. If both boolean values are True, then the operation result is True; if one of the boolean values on either side is False, the final operation result is False. Of course, if the boolean value on the left of the and operator is False, regardless of what the boolean value on the right is, the final result is False. At this time, the boolean value on the right will be skipped (professionally called short-circuit processing; if there’s an expression on the right of and, that expression won’t be executed). or literally means “or”, so the or operator also connects two boolean values or expressions that produce boolean values. If either of the boolean values on both sides is True, then the final result is True. Of course, the or operator also has short-circuit functionality. When the boolean value on its left is True, the boolean value on the right will be short-circuited (if there’s an expression on the right of or, that expression won’t be executed). The not operator can be followed by a boolean value. If the boolean value or expression after not is True, then the operation result is False; if the boolean value or expression after not is False, then the operation result is True.

"""
Using comparison and logical operators

Version: 1.0
Author: Luo Hao
"""
flag0 = 1 == 1
flag1 = 3 > 2
flag2 = 2 < 1
flag3 = flag1 and flag2
flag4 = flag1 or flag2
flag5 = not flag0
print('flag0 =', flag0)     # flag0 = True
print('flag1 =', flag1)     # flag1 = True
print('flag2 =', flag2)     # flag2 = False
print('flag3 =', flag3)     # flag3 = False
print('flag4 =', flag4)     # flag4 = True
print('flag5 =', flag5)     # flag5 = False
print(flag1 and not flag2)  # True
print(1 > 2 or 2 == 3)      # False

Note: The priority of comparison operators is higher than assignment operators, so in the above flag0 = 1 == 1, 1 == 1 is done first to produce the boolean value True, then this value is assigned to variable flag0. The print function can output multiple values, and multiple values can be separated by ,. The output content is separated by spaces by default.

Applications of Operators and Expressions

Example 1: Converting Fahrenheit to Celsius

Requirement: Input a Fahrenheit temperature and convert it to Celsius. The conversion formula from Fahrenheit to Celsius is: $\small{C = (F - 32) / 1.8}$.

"""
Convert Fahrenheit temperature to Celsius temperature

Version: 1.0
Author: Luo Hao
"""
f = float(input('Enter Fahrenheit temperature: '))
c = (f - 32) / 1.8
print('%.1f Fahrenheit = %.1f Celsius' % (f, c))

Note: The input function in the above code is used to receive user input from the keyboard. Since all input is strings, if you want to process it as a floating-point decimal for subsequent operations, you can use the type conversion method we explained in the previous lesson, using the float function to process the str type into float type.

In the above code, we formatted the output content of the print function. There are two %.1f placeholders in the string output by print. These two placeholders will be replaced by the two float type variable values in (f, c) after %, with floating-point numbers keeping 1 significant digit after the decimal point. If there’s a %d placeholder in the string, we’ll replace it with an int type value. If there’s a %s placeholder in the string, it will be replaced by a str type value.

Besides the above formatted output method, Python can also format output in the following way. We provide a string with placeholders, and the f before the string indicates that this string needs formatting. The {f:.1f} and {c:.1f} can first be seen as {f} and {c}, indicating that the values of variables f and c will replace these two placeholders during output. The :.1f after indicates this is a floating-point number, keeping 1 significant digit after the decimal point.

"""
Convert Fahrenheit temperature to Celsius temperature

Version: 1.1
Author: Luo Hao
"""
f = float(input('Enter Fahrenheit temperature: '))
c = (f - 32) / 1.8
print(f'{f:.1f} Fahrenheit = {c:.1f} Celsius')

Example 2: Calculate Circle Circumference and Area

Requirement: Input a circle’s radius ($\small{r}$), calculate its circumference ($\small{2 \pi r}$) and area ($\small{\pi r^{2}}$).

"""
Input radius to calculate circle circumference and area

Version: 1.0
Author: Luo Hao
"""
radius = float(input('Enter circle radius: '))
perimeter = 2 * 3.1416 * radius
area = 3.1416 * radius * radius
print('Circumference: %.2f' % perimeter)
print('Area: %.2f' % area)

Python has a built-in module named math, which defines a variable named pi whose value is the value of pi. If we want to use Python’s built-in pi, we can slightly modify the above code.

"""
Input radius to calculate circle circumference and area

Version: 1.1
Author: Luo Hao
"""
import math

radius = float(input('Enter circle radius: '))
perimeter = 2 * math.pi * radius
area = math.pi * radius ** 2
print(f'Circumference: {perimeter:.2f}')
print(f'Area: {area:.2f}')

Note: The import math in the above code means importing the math module. After importing this module, you can use math.pi to get the value of pi.

There’s actually another formatted output method, which is a new feature added in Python 3.8. Just look at the code below and you’ll understand.

"""
Input radius to calculate circle circumference and area

Version: 1.2
Author: Luo Hao
"""
import math

radius = float(input('Enter circle radius: '))  # Input: 5.5
perimeter = 2 * math.pi * radius
area = math.pi * radius ** 2
print(f'{perimeter = :.2f}')  # Output: perimeter = 34.56
print(f'{area = :.2f}')       # Output: area = 95.03

Note: If variable a has a value of 9.87, then the string f'{a = }' has a value of a = 9.87; and the string f'{a = :.1f}' has a value of a = 9.9. This formatted output method outputs both the variable name and variable value.

Example 3: Determine Leap Year

Requirement: Input a year after 1582 and determine whether it’s a leap year.

"""
Input year, output True for leap year, False for common year

Version: 1.0
Author: Luo Hao
"""
year = int(input('Enter year: '))
is_leap = year % 4 == 0 and year % 100 != 0 or year % 400 == 0
print(f'{is_leap = }')

Note: For the Gregorian calendar, which is the calendar we use today, the rules for determining leap years are: 1. Years not divisible by 4 are common years; 2. Years divisible by 4 but not by 100 are leap years; 3. Years divisible by 400 are leap years. The Gregorian calendar was introduced by Pope Gregory XIII in October 1582 as a modification and replacement of the Julian calendar. We should note this when entering years. The above code uses % to determine whether year is a multiple of 4, 100, or 400, then uses and and or operators to assemble the three conditions together. The first two conditions must be satisfied simultaneously, and the combination of the first two conditions only needs to satisfy one with the third condition.

Summary

Through the above explanations and examples, I believe everyone has felt the power of operators and expressions. Many problems in actual programming need to be solved by constructing expressions, so variables, operators, and expressions are extremely important foundations for any programming language. If there’s anything you don’t understand in this lesson, don’t rush to the next lesson. Leave a comment in the discussion area first, and I’ll answer your questions promptly.