Operators
In any programming language we can do operations on data and, in most, for the basic operations an operator syntax is defined.
Resources
- Real python tutorial on operators and statements.
- Official documentation for expressions and operators.
Basic numeric operations
For instance, in Python we can sum to numbers using the + operator.
With integers and floats we can use the basic arithmetic operators: +, -, /, *, .
There is also an operator for power: **.
Create a program that calculates the area of a circle.
Integer division
For integers Python defines two other special operators: integer division (//), and remainder (%).
print("9 % 3 ", 9 % 3)
print("14 % 2 ", 14 % 2)
print("14 % 3 ", 14 % 3)
print("9 // 3 ", 9 // 3)
print("14 //2 ", 14 //2)
print("14 % 3 ", 14 % 3)Find out if the numbers 10938 and 9893 are divisible by 3.
Use the mod operator %, and the type casting to bool.
Common unary operators
The operators that we have seen so far take two elements. For instance the add operator (+) takes two numbers and returns the sum of both. These operators are called binary because they take two items. But there are also unary operators; they only act over one element. The one most commonly used is the += operator.
There are other unary operators, like -=, *=, \= but they are not used as much.