Skip to content

Latest commit

 

History

History
245 lines (189 loc) · 12.7 KB

File metadata and controls

245 lines (189 loc) · 12.7 KB

Operators in Python

Python supports many kinds of operators. The table below lists Python operators from high precedence to low precedence. With variables and operators, we can build all kinds of expressions to solve real problems. In computer science, an expression is a syntax unit in a computer program. It is made up of one or more constants, variables, functions, and operators, and the programming language can interpret and calculate it to get another value. It does not matter if you do not understand this sentence for now, but you must know one thing: no matter what programming language you use, building expressions is very important.

Operator Description
[], [:] indexing, slicing
** exponentiation
~, +, - bitwise NOT, unary plus, unary minus
*, /, %, // multiplication, division, modulo, floor division
+, - addition, subtraction
>>, << right shift, left shift
& bitwise AND
^, ` `
<=, <, >, >= less than or equal to, less than, greater than, greater than or equal to
==, != equal to, not equal to
is, is not identity operators
in, not in membership operators
not, or, and logical operators
=, +=, -=, *=, /=, %=, //=, **=, &=, ` =, ^=, >>=, <<=`

Note: Precedence means the order of execution when an expression contains multiple operators. When writing code, if you are not sure about the precedence of operators in an expression, you can use parentheses to make sure the order is what you want.

Arithmetic Operators

Python has many arithmetic operators. Besides the familiar addition, subtraction, multiplication, and division, there are also the floor-division operator, the modulo operator (remainder), and the exponentiation operator. The example below shows how to use arithmetic operators.

"""
Arithmetic operators

Version: 1.0
Author: Luo Hao
"""
print(321 + 12)     # addition -> 333
print(321 - 12)     # subtraction -> 309
print(321 * 12)     # multiplication -> 3852
print(321 / 12)     # division -> 26.75
print(321 // 12)    # floor division -> 26
print(321 % 12)     # modulo -> 9
print(321 ** 12)    # exponentiation -> 1196906950228928915420617322241

In arithmetic operations, multiplication and division are done before addition and subtraction. This is the same as in mathematics. In other words, multiplication and division have higher precedence than addition and subtraction. If there is exponentiation too, exponentiation has higher precedence than multiplication and division. If you want to change the execution order of arithmetic operations, you can use parentheses in English input mode. The expression inside the parentheses will be executed first, as shown below.

"""
Operator precedence in arithmetic

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

The assignment operator is probably the most common operator. Its job is to assign the value on the right side to the variable on the left side. The assignment operator can also be combined with the arithmetic operators above to form compound assignment operators. For example, a += b is equal to a = a + b, and a *= a + 2 is equal to a = a * (a + 2). The example below shows the use of assignment operators and compound assignment operators.

"""
Assignment 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)      # try to work out the result yourself

An expression built with the assignment operator does not produce any value by itself. In other words, if you put an assignment expression into the print function and try to print the value of that expression, it will cause a syntax error. To solve this problem, Python 3.8 introduced a new assignment operator, :=. We call it the walrus operator. You can guess why it has this name. The walrus operator also assigns the value on the right side of the operator to the variable on the left side. The difference is that the value on the right side is also the value of the whole expression. Look at the code below and it will be clear.

"""
The walrus operator

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

Tip: If you remove the comment from print((a = 10)), Python will raise SyntaxError: invalid syntax. If you accidentally write print(a = 10), you will get TypeError: 'a' is an invalid keyword argument for print(). When we talk about functions later, this error will make more sense.

Comparison and Logical Operators

Comparison operators are also called relational operators. They include ==, !=, <, >, <=, and >=, and I believe everyone can understand them at a glance. One thing to remember is that checking equality uses ==. Please note that there are two equal signs here, because = is the assignment operator we just talked about. Checking inequality uses !=, which is different from the $\small{\neq}$ symbol used in math textbooks. Python 2 once used <> to mean not equal. In Python 3, using <> raises SyntaxError. Comparison operators produce Boolean values, either True or False.

There are three logical operators: and, or, and not.

  • The literal meaning of and is "and", so the and operator connects two Boolean values or expressions that produce Boolean values. If the Boolean values on both sides are both True, then the result is True. If one of them is False, then the final result is False.
  • If the Boolean value on the left side of the and operator is False, then no matter what the right side is, the final result is False. At this time, the right side is skipped. The professional name for this is short-circuit processing. If the right side of and is an expression, then that expression will not be executed.
  • The literal meaning of or is "or", so the or operator also connects two Boolean values or expressions that produce Boolean values. If either side is True, then the final result is True.
  • The or operator also has short-circuit behavior. When the value on its left side is True, the right side will be skipped. If the right side of or is an expression, then that expression will not be executed.
  • The not operator can be followed by a Boolean value. If the Boolean value or expression after not is True, then the result is False. If the Boolean value or expression after not is False, then the result is True.
"""
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: Comparison operators have higher precedence than assignment operators, so flag0 = 1 == 1 first evaluates 1 == 1 and produces the Boolean value True, and then assigns that value to the variable flag0. The print function can output multiple values. The values can be separated by ,, and they are separated by spaces in the output by default.

Applying Operators and Expressions

Example 1: Convert Fahrenheit to Celsius

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

"""
Convert Fahrenheit to Celsius

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

Note: The input function is used to receive user input from the keyboard. Because the input is always a string, if you want to treat it as a floating-point number in later calculations, you can use the type conversion method we learned in the previous lesson and use the float function to convert the str value to a float.

In the code above, we formatted the content output by the print function. The output string has two %.1f placeholders. These two placeholders will be replaced by the two float values in (f, c) after %, and one digit is kept after the decimal point. If a string contains a %d placeholder, we will use a value of type int to replace it. If it contains a %s placeholder, it will be replaced with a value of type str.

Besides the formatting method above, Python can also use the method below for formatted output. We give a string with placeholders, and the f before the string means the string needs formatting. For now, you can first treat {f:.1f} and {c:.1f} as {f} and {c}. This means the values of variables f and c will replace these two placeholders when the string is printed. The :.1f means this is a floating-point number, and one digit is kept after the decimal point.

"""
Convert Fahrenheit to Celsius

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

Example 2: Calculate the Circumference and Area of a Circle

Task: Enter the radius $\small{r}$ of a circle, and calculate its circumference $\small{2 \pi r}$ and area $\small{\pi r^{2}}$.

"""
Calculate the circumference and area of a circle

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

Python has a built-in module named math, and that module defines a variable named pi. Its value is the mathematical constant pi. If we want to use Python's built-in pi, we can make a small change to the code above.

"""
Calculate the circumference and area of a circle

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

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

Note: import math means importing the math module. Only after importing that module can we use math.pi to get the value of pi.

There is actually another formatting method here. It is a new feature added in Python 3.8. Just look at the code below and it will be clear.

"""
Calculate the circumference and area of a circle

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

radius = float(input('Enter the 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 the value of variable a is 9.87, then the value of the string f'{a = }' is a = 9.87; and the value of the string f'{a = :.1f}' is a = 9.9. This formatting method prints the variable name and the variable value at the same time.

Example 3: Determine Whether a Year Is a Leap Year

Task: enter a year after 1582 and determine whether that year is a leap year.

"""
Read a year and output True for a leap year, False otherwise

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

Note: In the Gregorian calendar, which is the civil calendar we use today, the rule for determining a leap year is: 1. A year that is not divisible by 4 is a common year. 2. A year that is divisible by 4 but not divisible by 100 is a leap year. 3. A year that is divisible by 400 is a leap year. The Gregorian calendar was introduced by Pope Gregory XIII in October 1582 as a revision and replacement of the Julian calendar, so keep that in mind when entering a year. The code above uses % to determine whether year is a multiple of 4, 100, and 400, and then uses the and and or operators to combine the three conditions together: the first two conditions must both be satisfied, while the third condition only needs one side of the combined condition to be satisfied.

Summary

Through the explanation and examples above, I believe everyone has already felt the power of operators and expressions. Many real programming problems need to be solved by building expressions, so variables, operators, and expressions are extremely important foundations in any programming language. If there is anything in this lesson that you do not understand, do not rush into the next lesson. First make sure you understand this part.