Operations: A Comprehensive Guide
Understanding basic operations in Python is crucial for any programmer. These operations form the foundation of more complex logic and algorithms. In this guide, we’ll explore various basic operations in Python, from arithmetic and assignment to comparison and logical operations.
Arithmetic operations are used to perform mathematical calculations. Python supports several arithmetic operators:
Operator | Description | Example | Output |
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 5 / 2 | 2.5 |
// | Floor Division | 5 // 2 | 2 |
% | Modulus | 5 % 2 | 1 |
** | Exponentiation | 5 ** 2 | 25 |
Example:
Assignment operators are used to assign values to variables. Python supports various assignment operators:
Operator | Example | Equivalent to |
= | x = 5 | Assign 5 to x |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
//= | x //= 3 | x = x // 3 |
%= | x %= 3 | x = x % 3 |
**= | x **= 3 | x = x ** 3 |
Example:
Comparison operators are used to compare two values. They return a boolean result (True or False).
Operator | Description | Example | Output |
== | Equal to | 5 == 2 | False |
!= | Not equal to | 5 != 2 | True |
> | Greater than | 5 > 2 | True |
< | Less than | 5 < 2 | False |
>= | Greater than or equal to | 5 >= 2 | True |
<= | Less than or equal to | 5 <= 2 | False |
Example:
Logical operators are used to combine conditional statements. Python supports and, or, and not operators.
Operator | Description | Example | Output |
and | Logical AND | True and False | False |
or | Logical OR | True or False | True |
not | Logical NOT | not True | False |
Example:
Bitwise operators perform operations on the binary representations of integers. Python supports & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).
Operator | Description | Example | Output |
& | Bitwise AND | 5 & 3 | 1 |
| | Bitwise OR | 5 | 3 | 7 |
^ | Bitwise XOR | 5 ^ 3 | 6 |
~ | Bitwise NOT | ~5 | -6 |
<< | Left shift | 5 << 1 | 10 |
>> | Right shift | 5 >> 1 | 2 |
Example:
Create a simple calculator that performs basic arithmetic operations.
Use logical operators to check if a number is within a specified range.
Write a program to check if a number is even or odd.
Write a program to check if a year is a leap year.
In this comprehensive guide, we've covered the basics of Python operations, including arithmetic, assignment, comparison, logical, and bitwise operations. These operations are fundamental to any programming task and are essential for writing more complex code. Make sure to practice these concepts with the provided examples and exercises to strengthen your understanding. Happy coding!