Python Operators
Whenever you want to do something with variables and values, you reach for an operator, which carries out the operation.
The next example adds two values together with the + operator:
Example
Prompt
Write a Python program that prints the result of adding 10 and 5 using the + operator.
Output: complete Python program
main.py
print(10 + 5)
Example
The + operator isn't limited to two plain values. It can also add a variable to a value, or one variable to another:
Prompt
Write a Python program that demonstrates adding values with variables:
sum1 = 100 + 50, sum2 = sum1 + 250, sum3 = sum2 + sum2.
Output: complete Python program
main.py
sum1 = 100 + 50 # 150 (100 + 50)
sum2 = sum1 + 250 # 400 (150 + 250)
sum3 = sum2 + sum2 # 800 (400 + 400)
Operator Groups
Python sorts its operators into these groups:
- Arithmetic
- Assignment
- Comparison
- Logical
- Identity
- Membership
- Bitwise