Let’s be clear from the outset—this isn’t a blog post advocating for or against AI. We have enough of those already. Instead, what I hope to share here is a technical reflection grounded in personal experience. I’ve spent considerable time working with modern tools in the cloud ecosystem, and Python has consistently stood out—not because of hype, but because of its sheer practicality.
In this post, I’ll walk through why Python remains the dominant language in cloud computing, the tools that make it indispensable, and a few key use cases that exemplify its power. Whether you’re new to the space or seasoned in software engineering, this is a look at Python through the lens of real-world application—not marketing brochures.
Introduction
Cloud computing has fundamentally redefined how we build and scale systems. Gone are the days of over-provisioned, on-premise servers. We now operate in an era of elastic infrastructure, where compute, storage, and network resources can be spun up in seconds.
Amid this transformation, Python has become a cornerstone language—not just for its syntax, but for its practical utility. It's cross-platform, widely supported, and incredibly well-suited for both simple scripting and building large, production-grade systems. From automating infrastructure to training and deploying ML models, Python’s presence is undeniable in today’s cloud-native development landscape.
Why Python for Cloud Computing?
Python is often the first choice for cloud developers—and not without reason. It strikes a rare balance between simplicity and capability. Here’s why that matters.
Ease of Use
Python’s syntax is readable, intuitive, and expressive. Developers can focus on solving core business problems rather than wrestling with verbose code structures. This clarity translates to faster development cycles and easier onboarding for new engineers.
Versatility
Python supports multiple programming paradigms—procedural, object-oriented, and functional—allowing developers to approach problems in ways that suit their architectural goals. This flexibility is particularly useful in cloud environments where diverse workloads (e.g., automation scripts, web apps, machine learning) coexist.
Community and Ecosystem
Python has one of the most active open-source communities in tech. That means more tutorials, better documentation, and an ever-expanding set of libraries. Whether you're dealing with AWS, GCP, Azure, or private cloud setups, chances are someone has already written a Python library to help.
Seamless Integration with Cloud Platforms
All major cloud providers offer robust Python SDKs. This integration enables developers to interact directly with services like AWS Lambda, Google Cloud Functions, or Azure Storage, using clean and concise Python code.
Key Libraries and Tools for Cloud Development
A big part of Python’s dominance in the cloud comes down to its tools. Here are some libraries I frequently use in production:
Boto3 (AWS)
Boto3 is the standard SDK for AWS in Python. It simplifies interactions with services like EC2, S3, and Lambda. You can automate infrastructure with just a few lines of code:
import boto3
s3_client = boto3.client('s3')
bucket_name = "my-unique-bucket-name-example"
try:
response = s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': 'us-west-2'}
)
print(f"Bucket '{bucket_name}' created successfully.")
except Exception as e:
print(f"Error creating bucket: {e}")
import boto3
s3_client = boto3.client('s3')
bucket_name = "my-unique-bucket-name-example"
file_name = "example.txt"
object_key = "uploaded/example.txt"
try:
s3_client.upload_file(file_name, bucket_name, object_key)
print(f"File '{file_name}' uploaded to '{bucket_name}/{object_key}' successfully.")
except Exception as e:
print(f"Error uploading file: {e}")
Google Cloud Client Libraries
These libraries allow Python applications to interact with GCP services like BigQuery, Cloud Storage, and Compute Engine with native support and efficient abstractions.
Azure SDK for Python
Microsoft’s SDK enables developers to programmatically manage Azure resources. It's comprehensive, supporting everything from virtual machines to identity management.
Flask and Django
For building cloud-native applications, Flask and Django are the go-to frameworks. Flask is minimalist and modular—ideal for microservices—while Django offers a batteries-included approach that accelerates large-scale development.
Apache Libcloud
When working in a multi-cloud environment, Libcloud is invaluable. It provides a unified API that abstracts cloud provider differences, enabling greater portability across infrastructure vendors.
Python Data Types — A Quick Refresher
Python treats everything as an object. Understanding its data types is essential, especially when dealing with dynamic data in the cloud.
Core Built-in Data Types:
Numeric – int, float, complex
Sequence Types – str, list, tuple
Mapping Type – dict
Boolean – bool
Set Types – set, frozenset
Binary Types – bytes, bytearray, memoryview
Here's a quick example demonstrating Python's dynamic typing and how a variable can take on different types throughout its lifecycle:
x = 50 # int
x = 60.5 # float
x = "Hello World" # string
x = ["Scas", "for", "Scas"] # list
x = ("Scas", "for", "Scas") # tuple
Understanding Python Data Types Like a Pro
Data types are fundamental to any programming language, and Python is no exception. As a dynamically typed language, Python offers a wide variety of built-in data types that simplify how we represent and manipulate data. Whether you're processing numbers, organizing data collections, or managing complex structures, understanding these data types is essential.
Let’s walk through Python’s core data types, exploring practical usage with concise examples.
- Numeric Data Types in Python Python’s numeric types are versatile and capable of representing everything from simple integers to complex numbers. These are implemented via the built-in classes int, float, and complex.
Integer (int): Represents whole numbers, both positive and negative. Python integers have arbitrary precision, meaning they can grow as large as your memory allows.
Float (float): Represents real numbers using floating-point arithmetic. Python supports scientific notation as well, using e or E.
Complex (complex): A less frequently used but powerful type when working with mathematics and engineering problems. A complex number consists of a real and an imaginary part.
a = 5
print(type(a)) #
b = 5.0
print(type(b)) #
c = 2 + 4j
print(type(c)) #
- Sequence Data Types in Python Sequence types represent collections of ordered elements. Python provides several built-in sequence types, including str, list, and tuple.
String (str)
Strings in Python are Unicode-based and immutable. You can define them using single, double, or triple quotes. Indexing allows access to specific characters.
s = 'Welcome to the Sca World'
print(s) # Welcome to the Sca World
print(type(s)) #
print(s[1]) # e
print(s[2]) # l
print(s[-1]) # d
List (list)
Lists are mutable, ordered collections that can hold elements of different types. Python lists are one of the most flexible and widely used data types.
Various ways to define lists
a = [] # Empty list
a = [1, 2, 3] # List of integers
b = ["Sca", "For", "Sca", 4] # Mixed types
print(a) # [1, 2, 3]
print(b) # ['Sca', 'For', 'Sca', 4]
Accessing list items:
a = ["Sca", "For", "Sca"]
print(a[0]) # Sca
print(a[2]) # Sca
print(a[-1]) # Sca
print(a[-3]) # Sca
Tuple (tuple)
Tuples are similar to lists but are immutable—ideal for fixed data collections. They support heterogeneous values and can be nested.
tup1 = () # Empty tuple
tup2 = ('Sca', 'For')
print("Tuple with strings:", tup2)
Accessing tuple items
tup3 = (1, 2, 3, 4, 5)
print(tup3[0]) # 1
print(tup3[-1]) # 5
print(tup3[-3]) # 3
Note: A single-element tuple must include a trailing comma: t = (5,)
- Boolean Data Type (bool) Booleans in Python are simple: True and False. They’re often used in conditional expressions and logical operations.
print(type(True)) #
print(type(False)) #
Attempting to use true (lowercase) will result in an error, as Python is case-sensitive:
print(type(true)) # NameError: name 'true' is not defined
- Set Data Type (set) Sets are unordered collections of unique, hashable elements. They're useful for membership testing, eliminating duplicates, and performing set operations. # Creating sets s1 = set("ScaForSca") print("Set from string:", s1)
s2 = set(["Sca", "For", "Sca"])
print("Set from list:", s2)
Accessing set elements requires iteration:
set1 = set(["Sca", "For", "Sca"])
for item in set1:
print(item, end=" ") # Unordered output
print("Sca" in set1) # True
- Dictionary Data Type (dict) Dictionaries are Python’s built-in hash maps, storing key-value pairs. Keys must be immutable, but values can be of any type. This structure is ideal for representing structured data.
Creating dictionaries
d = {1: 'Sca', 2: 'For', 3: 'Sca'}
print(d)
d1 = dict({1: 'Sca', 2: 'For', 3: 'Sca'})
print(d1)
Accessing dictionary items:
d = {1: 'Sca', 'name': 'For', 3: 'Sca'}
print(d['name']) # For
print(d.get(3)) # Sca
Python Data Type Exercise Questions
Working with data structures like lists and tuples is foundational in Python development. Below are two hands-on exercises designed to reinforce basic operations with these types. These examples serve as simple yet effective demonstrations for manipulating Python collections.
For more practice questions on Python data types, refer to the extended exercise set linked at the end of this post.
Q1. Basic List Operations
In this example, we perform a sequence of operations on a list of fruits—initialization, appending an item, and removing an item.
fruits = ["apple", "banana", "orange"]
print(fruits)
fruits.append("grape")
print(fruits)
fruits.remove("orange")
print(fruits)
Output:
['apple', 'banana', 'orange']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'grape']
Here, we start with a basic list of fruits, append "grape" using append(), and remove "orange" with remove(). These operations reflect typical use cases in real-world data manipulation tasks.
Q2. Basic Tuple Operations
Tuples are immutable sequences, making them ideal for fixed data such as coordinate pairs. This example demonstrates how to define a tuple and access its elements by index.
coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])
Output:
(3, 5)
X-coordinate: 3
Y-coordinate: 5
Since tuples don’t support item assignment, they are often used for values that shouldn’t change throughout a program. Indexing allows direct access to individual components, as shown above.
Python Slice: Useful Methods for Everyday Coding
Slicing in Python is a powerful and elegant technique to extract, manipulate, and analyze data. Whether you're working with strings, lists, or large multidimensional arrays, slicing offers a consistent, high-performance way to access subsets of your data. In this post, we’ll explore both basic and advanced slicing techniques, including how they extend to libraries like NumPy and pandas.
What is Slicing in Python?
At its core, slicing is Python's built-in mechanism to access portions of a sequence—whether that’s a list, tuple, string, or range. The syntax [start:stop:step] is concise and expressive, making it ideal for data manipulation tasks. Python also provides a slice() function, which allows for reusable slice logic. Both forms are foundational tools that you’ll encounter in production-level code and external libraries like NumPy and pandas.
Why Master Python Slicing?
Slicing isn't just a convenience—it’s a best practice for efficient coding. Here’s why it matters:
Concise, readable code: Eliminates boilerplate loops and verbose conditions.
Performance optimized: Python’s internal optimizations make slicing faster and more memory-efficient than manual iteration.
Universally applicable: From built-in types to NumPy arrays and pandas DataFrames, slicing is everywhere.
Essential for real-world tasks: Subsetting datasets, reversing strings, extracting log entries—all benefit from slicing.
Basic Slicing Syntax
The most familiar slicing method uses the colon syntax:
sequence[start:stop:step]
Where:
start – Beginning index (inclusive, defaults to 0)
stop – Ending index (exclusive, defaults to sequence length)
step – Interval between elements (defaults to 1)
Examples with Lists:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[::2]) # [10, 30, 50]
Examples with Strings:
text = "Python Slicing"
print(text[7:]) # 'Slicing'
print(text[::-1]) # 'gnicilS nohtyP'
Skipping Elements:
data = [100, 200, 300, 400, 500]
print(data[::2]) # [100, 300, 500]
Real-World Example: Efficient Log Parsing
logs = load_large_dataset()
recent_logs = logs[-1000:] # Efficient access to the last 1000 records
The slice() Function
Python’s slice() function allows the same slicing logic as bracket notation but encapsulated in an object, which is ideal for reusability:
slice_obj = slice(1, 4)
numbers = [10, 20, 30, 40, 50]
print(numbers[slice_obj]) # [20, 30, 40]
text = "Python"
print(text[slice_obj]) # 'yth'
Why Use slice()?
It makes your code DRY and improves maintainability. You can define a slice once and apply it across multiple data types:
my_slice = slice(2, 5)
data_list = [100, 200, 300, 400, 500]
data_string = "SlicingExample"
print(data_list[my_slice]) # [300, 400, 500]
print(data_string[my_slice]) # 'ici'
Slicing in NumPy
NumPy extends Python’s slicing to support efficient operations on large arrays.
Slicing 1D Arrays:
import numpy as np
array = np.array([10, 20, 30, 40, 50])
print(array[1:4]) # [20 30 40]
print(array[::2]) # [10 30 50]
Slicing 2D Arrays:
array_2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(array_2d[:2, :2]) # [[1 2]
# [4 5]]
print(array_2d[:, -1]) # [3 6 9]
Benefits:
Performance: NumPy returns views (not copies) for most slicing operations.
Control: Axis-specific slicing allows precise data access.
Slicing in pandas
pandas builds on core slicing concepts with intuitive, label- and index-based slicing for Series and DataFrames.
Basic Row and Column Slicing:
import pandas as pd
student_data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Score': [85, 90, 95]}
students = pd.DataFrame(student_data)
print(students[:2])
Name Age Score
0 Alice 25 85
1 Bob 30 90
print(students[['Name', 'Score']])
Name Score
0 Alice 85
1 Bob 90
2 Charlie 95
Using .iloc[] and .loc[]:
Index-based
print(students.iloc[1:, 1:])
Age Score
1 30 90
2 35 95
Label-based
print(students.loc[:1, ['Name', 'Age']])
Name Age
0 Alice 25
1 Bob 30
Slicing Across Data Types
Strings:
text = "Python Slicing"
print(text[7:14]) # 'Slicing'
print(text[::-1]) # 'gnicilS nohtyP'
slicer = slice(7, 14)
print(text[slicer]) # 'Slicing'
Use Cases:
Parsing structured text
Reversing or trimming strings
Lists and Tuples:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[::2]) # [10, 30, 50]
colors = ("red", "green", "blue", "yellow")
print(colors[:2]) # ('red', 'green')
Filtering and Reordering:
data = [5, 10, 15, 20, 25]
filtered = data[1::2]
print(filtered) # [10, 20]
Slicing in Data Analysis
Slicing plays a critical role in preprocessing and exploring datasets:
With NumPy:
import numpy as np
data = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(data[:2, :])
[[1 2 3]
[4 5 6]]
With pandas:
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Score': [85, 90, 95]
})
print(df.loc[:1, ['Name', 'Score']])
Name Score
0 Alice 85
1 Bob 90
Tips for multi-dimensional slicing:
Use commas to separate slicing for each dimension.
Avoid mixing negative indices and default slicing : in ways that create ambiguity.
Debugging Tip: Always print intermediate slices when debugging multi-dimensional slicing to ensure you’re targeting the correct subset.
Common Python Slice Mistakes
Python's slicing syntax is elegant and expressive, but it's also prone to subtle bugs if not used with care. Even seasoned developers occasionally fall into these common traps. Here's a look at frequent slicing pitfalls and how to avoid them.
Off-by-One Errors
One of the most common slicing mistakes is the classic off-by-one error—usually caused by misunderstanding Python's exclusive stop index.
numbers = [1, 2, 3, 4, 5]
Intending to extract [2, 3, 4]
slice_result = numbers[1:3]
print(slice_result)
Output: [2, 3]
In this example, the stop index 3 is excluded, resulting in [2, 3] instead of the intended [2, 3, 4].
Best Practices:
Understand exclusivity: Remember, the stop index is not included in the result. If you want to include an item at a given index, add 1 to the stop index.
Be explicit: When defining a range, double-check your start and stop logic to ensure it aligns with the intended output.
Corrected version:
numbers = [1, 2, 3, 4, 5]
slice_result = numbers[1:4]
print(slice_result)
Output: [2, 3, 4]
Misunderstanding Step Values
Step values in slicing define the stride between elements. Misjudging them—especially when dealing with negative steps—can lead to hard-to-spot logic errors.
Example: Skipping too many elements
numbers = [1, 2, 3, 4, 5]
Expecting every second element
step_result = numbers[::3]
print(step_result)
Output: [1, 4]
A step of 3 skips too much. A more common mistake appears when using negative steps to reverse a list:
numbers = [1, 2, 3, 4, 5]
step_result = numbers[::-2]
print(step_result)
Output: [5, 3, 1]
Guidelines for Step Usage:
Plan your intervals: For every second element, use step=2.
Experiment with negatives: Negative steps reverse the list and skip elements. Try small test cases to understand how start/stop values interact with reverse stepping.
Use boundaries wisely: Start and stop indices can help limit the range even while using a step.
Correct usage examples:
Every second element
numbers = [1, 2, 3, 4, 5]
print(numbers[::2])
Output: [1, 3, 5]
Reverse with step
print(numbers[4::-2])
Output: [5, 3, 1]
General Best Practices
To reduce slicing mistakes:
Visualize your slices: Print intermediate results to verify logic.
Work with small data samples: Try examples on shorter lists before scaling up.
Consider slice() objects: When clarity matters, using the slice() function can make intent more readable.
Conditional Statements in Python
Control flow in Python is governed by conditional statements. These statements allow programs to execute different code paths based on logical conditions.
Basic if Statement
The if statement is the simplest form of condition checking.
age = 20
if age >= 18:
print("Eligible to vote.")
Output:
Eligible to vote.
Shorthand if
Python allows single-line if statements for simple logic.
age = 19
if age > 18: print("Eligible to Vote.")
Output:
Eligible to Vote.
if-else Statement
The else clause provides an alternate execution path when the condition fails.
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output:
rust
Travel for free.
Shorthand if-else (Ternary Operator)
Python offers a concise syntax for simple if-else expressions.
marks = 45
res = "Pass" if marks >= 40 else "Fail"
print(f"Result: {res}")
Output:
makefile
Result: Pass
This is Python’s version of the ternary operator, often used for inline conditions.
elif Statement
When multiple conditions need to be evaluated, elif provides clean branching logic.
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output:
Young adult.
Nested if...else
You can nest conditionals inside one another to evaluate complex logic.
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output:
30% senior discount!
Ternary Conditional Expression
A compact alternative to traditional if...else.
age = 20
s = "Adult" if age >= 18 else "Minor"
print(s)
Output:
Adult
The value of s depends on the condition: if age >= 18, it gets "Adult"; otherwise "Minor".
Match-Case in Python
Introduced in Python 3.10, the match-case statement offers pattern matching similar to switch-case constructs in other languages.
number = 2
match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three
match-case is particularly useful for readable multi-condition branching.
Numbers in Python
Python supports various numeric data types, the most common being int and float.
Integers (int): Whole numbers without a decimal component. Examples: 5, -10, 0.
Floating-point numbers (float): Numbers with decimals or exponential notation. Examples: 3.14, 2.5e-3.
These types are the backbone of numerical computation in Python and are used in everything from simple arithmetic to advanced scientific processing.
Numbers: Some Other Operators
In addition to basic arithmetic operations, Python provides other operators for working with numbers. Here are two commonly used number operators:
Modulo Operator (%)
The modulo operator, represented by %, calculates the remainder when one number is divided by another. For example:
result = 9 % 2
The result variable will contain the value 1 because 9 divided by 2 leaves a remainder of 1.
Power Operator (**)
The power operator, represented by **, raises a number to a specified exponent. For instance:
result = 2 ** 3
The result variable will contain the value 8 because 2 raised to the power of 3 is 8.
These operators expand the range of mathematical operations you can perform in Python, allowing for tasks like finding remainders and calculating exponents in your numerical computations.
Incrementing Counters
When working with counters in Python, you can increment or decrement their values in various ways. Here are some common methods to do so:
Using Assignment
You can initialize a counter with an initial value, and then increment it using the assignment operator. For example:
i = 0 # Initialize i to 0
i = i + 1 # Increment i by 1
After these operations, the variable i will hold the value 1.
Using Augmented Assignment
A more concise and common way to increment a counter is to use the augmented assignment operator (+=). For example:
i = 0 # Initialize i to 0
i += 1 # Increment i by 1
This code achieves the same result as the previous example, with the variable i also holding the value 1.
Decrementing a Counter
The process of decrementing a counter is similar to incrementing, but you subtract a value instead. For example:
i = 10 # Initialize i to 10
i = i - 1 # Decrement i by 1
After these operations, the variable i will hold the value 9.
You can achieve the same result using the augmented assignment operator for decrement:
i = 10 # Initialize i to 10
i -= 1 # Decrement i by 1
In this case, the variable i also ends up with the value 9.
These techniques are commonly used for maintaining and updating counters in loops, tracking progress, and controlling the flow of your code when you need to count or iterate through a series of values.
Python Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format.
Note: Python bitwise operators work only on integers.
Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
Bitwise right shift x >> n
<< Bitwise left shift x << n
Bitwise AND Operator
Python Bitwise AND (&) operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2. Take Bitwise AND of both X & Y.
Note: Here, (111)2 represent binary number.
a = 10
b = 4
Print bitwise AND operation
print("a & b =", a & b)
Output
a & b = 0
Bitwise OR Operator
The Python Bitwise OR (|) Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2. Take Bitwise OR of both X, Y.
a = 10
b = 4
Print bitwise OR operation
print("a | b =", a | b)
Output
a | b = 14
Bitwise XOR Operator
The Python Bitwise XOR (^) Operator also known as the exclusive OR operator, is used to perform the XOR operation on two operands. XOR stands for "exclusive or", and it returns true if and only if exactly one of the operands is true. In the context of bitwise operations, it compares corresponding bits of two operands. If the bits are different, it returns 1; otherwise, it returns 0.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2. Take Bitwise XOR of both X & Y.
a = 10
b = 4
print bitwise XOR operation
print("a ^ b =", a ^ b)
Output
a ^ b = 14
Bitwise NOT Operator
The preceding three bitwise operators are binary operators, necessitating two operands to function. However, unlike the others, this operator operates with only one operand.
Python Bitwise Not (~) Operator works with a single value and returns its one’s complement. This means it toggles all bits in the value, transforming 0 bits to 1 and 1 bits to 0, resulting in the one’s complement of the binary number.
Example: Take two bit values X and Y, where X = 5 = (101)2. Take Bitwise NOT of X.
a = 10
b = 4
Print bitwise NOT operation
print("~a =", ~a)
Output:
~a = -11
Bitwise Shift
These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two.
Bitwise Right Shift
Shifts the bits of the number to the right and fills 0 on voids left (fills 1 in the case of a negative number) as a result. Similar effect as of dividing the number with some power of two.
Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
a = 10
b = -10
print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
Output:
a >> 1 = 5
b >> 1 = -5
Bitwise Left Shift
Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of multiplying the number with some power of two.
Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
a = 5
b = -10
print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)
Output:
a << 1 = 10
b << 1 = -20
Bitwise Operator Overloading
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example, operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because the ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading.
Below is a simple example of Bitwise operator overloading.
Python program to demonstrate
operator overloading
class Sca():
def init(self, value):
self.value = value
def __and__(self, obj):
print("And operator overloaded")
if isinstance(obj, Sca):
return self.value & obj.value
else:
raise ValueError("Must be a object of class Sca")
def __or__(self, obj):
print("Or operator overloaded")
if isinstance(obj, Sca):
return self.value | obj.value
else:
raise ValueError("Must be a object of class Sca")
def __xor__(self, obj):
print("Xor operator overloaded")
if isinstance(obj, Sca):
return self.value ^ obj.value
else:
raise ValueError("Must be a object of class Sca")
def __lshift__(self, obj):
print("lshift operator overloaded")
if isinstance(obj, Sca):
return self.value << obj.value
else:
raise ValueError("Must be a object of class Sca")
def __rshift__(self, obj):
print("rshift operator overloaded")
if isinstance(obj, Sca):
return self.value >> obj.value
else:
raise ValueError("Must be a object of class Sca")
def __invert__(self):
print("Invert operator overloaded")
return ~self.value
Driver's code
if name == "main":
a = Sca(10)
b = Sca(12)
print(a & b)
print(a | b)
print(a ^ b)
print(a << b)
print(a >> b)
print(~a)
Output:
And operator overloaded
8
Or operator overloaded
14
Xor operator overloaded
6
lshift operator overloaded
40960
rshift operator overloaded
0
Invert operator overloaded
-11
Top comments (0)