Logo
Unit 4 – Python Basics: Operators

Python Basics: Operators

Duration: 5 minutes

Operators are specialised symbols in Python that perform arithmetic or logical operations. These operators serve as the pivots of programming, assisting us in carrying out computations, manipulating data and coming to conclusions under specific circumstances.

Arithmetic OperatorsThese are used for operations such as **addition (+), subtraction (-), multiplication (*), division (/), modulus (%), floor division (//), **and exponentiation (). **For example:

a = 10
b = 3
print(a + b)  # Output: 13
print(a - b)  # Output: 7
print(a * b)  # Output: 30
print(a / b)  # Output: 3. 3333333333333335
print(a % b)  # Output: 1
print(a // b) # Output: 3
print(a ** b) # Output: 1000

Comparison Operators

These are used to compare values. It either returns True or False according to the condition. They include **equals (==), not equals (!=), greater than (>), less than (<), greater than or equal to (>=) **and less than or equal to (<=). For example:

print(a == b)  # Output: False
print(a != b)  # Output: True
print(a > b)   # Output: True
print(a < b)   # Output: False
print(a >= b)  # Output: True
print(a <= b)  # Output: False

Assignment Operators

These are used to give variable values. **Equals (=), plus equals (+=), minus equals (-=), multiplication equals (*=), divide equals (/=), modulus equals (%=), floor divide equals (//=), **and exponent equals (=)** are among them. For example:

a = 10
a += 2  # equivalent to a = a + 2
print(a)  # Output: 12

Logical Operators

Logical operators are** and, or, not **operators. For example:

a = True
b = False
print(a and b)  # Output: False
print(a or b)   # Output: True
print(not b)    # Output: True

Bitwise Operators

Bitwise operators conduct bit-by-bit actions on bits. **Bitwise AND (&), OR (|), NOT (), XOR (), right shift (>>), **and left shift () are among them. For example:

a = 10  # in binary: 1010
b = 4   # in binary: 0100
print(a & b)  # Output: 0 (0000 in binary)
print(a | b)  # Output: 14 (1110 in binary)
print(~a)     # Output: -11 (-(1011 in binary))
print(a ^ b)  # Output: 14 (1110 in binary)
print(a >> 2# Output: 2 (0010 in binary)
print(a << 2# Output: 40 (101000 in binary)

Assignment

It’s now your chance to practise with Python operators! Experiment with the various operators we discussed. Experiment with building complex expressions by combining several operators. When combining operators in a single expression, don’t forget to put your comprehension of precedence rules to the test.

Conclusion

As you begin to write more complicated Python programs, you’ll discover that these operators are really useful. Now, play around with other operators and expressions. Remember that practice is the key to programming excellence!

Next Tutorial: Python Data Structures: Lists and Tuples

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!