How to use in python

What are operators in python?

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

For example:

>>> 2+3
5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.

Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.

OperatorMeaningExample
+ Add two operands or unary plus x + y+ 2
- Subtract right operand from the left or unary minus x - y- 2
* Multiply two operands x * y
/ Divide left operand by the right one [always results into float] x / y
% Modulus - remainder of the division of left operand by the right x % y [remainder of x/y]
// Floor division - division that results into whole number adjusted to the left in the number line x // y
** Exponent - left operand raised to the power of right x**y [x to the power y]

Example 1: Arithmetic operators in Python

x = 15
y = 4

# Output: x + y = 19
print['x + y =',x+y]

# Output: x - y = 11
print['x - y =',x-y]

# Output: x * y = 60
print['x * y =',x*y]

# Output: x / y = 3.75
print['x / y =',x/y]

# Output: x // y = 3
print['x // y =',x//y]

# Output: x ** y = 50625
print['x ** y =',x**y]

Output

x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

Comparison operators

Comparison operators are used to compare values. It returns either True or False according to the condition.

OperatorMeaningExample
> Greater than - True if left operand is greater than the right x > y
< Less than - True if left operand is less than the right x < y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y
y] # Output: x < y is True print['x < y is',x= y is False print['x >= y is',x>=y] # Output: x = y is False x > Bitwise right shift x >> 2 = 2 [0000 0010]
= x >>= 5 x = x >> 5

Chủ Đề