Operators
Operators are used to perform operations on variables or literal values.
Comparison Operators
Comparison operators are used to compare two values. The comparison evaluates to either True
or False
.
Comparison operators include:
==
!=
>
<
>=
<=
[4]:
print("comparison operators example")
print("----------------------------")
x = 1
y = 2
print("x =", x)
print("y =", y)
print("-----")
print("x == y -> ", x == y)
print("x != y -> ", x != y)
print("x > y -> ", x > y)
print("x < y -> ", x < y)
comparison operators example
----------------------------
x = 1
y = 2
-----
x == y -> False
x != y -> True
x > y -> False
x < y -> True
Logical Operators
Logical operators are used to combine boolean values.
Logical operators include:
and
or
not
[3]:
print("logical operators")
print("--------------------")
x = True
y = False
print("x =", x)
print("y =", y)
print("---------")
print("x and y -> ", x and y)
print("x or y -> ", x or y)
print("not x -> ", not x)
print("not y -> ", not y)
logical operators
--------------------
x = True
y = False
---------
x and y -> False
x or y -> True
not x -> False
not y -> True
Warning
Use parenthesis to specify the order of operations!
[19]:
print(False and False == False)
print((False and False) == False)
False
True
Warning
The and
and or
operators may return unexpected results if applied to non-boolean types.
Arithmetic Operators
Arithmetic operators are used with numeric values to perform mathematical operations.
Arithmetic operations include:
+
-
*
/
%
**
//
[22]:
print("arithmetic operators")
print("--------------------")
x = 2
y = 3
print("x =", x)
print("y =", y)
print("-----")
print("x + y -> ", x + y)
print("x - y -> ", x - y)
print("x * y -> ", x * y)
print("x / y -> ", x / y)
print("x % y -> ", x % y)
print("x ** y -> ", x ** y)
print("x // y -> ", x // y)
arithmetic operators
--------------------
x = 2
y = 3
-----
x + y -> 5
x - y -> -1
x * y -> 6
x / y -> 0.6666666666666666
x % y -> 2
x ** y -> 8
x // y -> 0