Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Assignment Operators in Python – A Comprehensive Guide

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

Ever felt confused about assigning values to variables in Python? Wondering how to simplify operations like addition, subtraction, or even bitwise shifts?

 

Many of us face these questions when diving into Python programming.

 

Assignment operators in Python are here to make our lives easier. These operators help us assign values to variables in a clean and efficient way and make our code efficient and compact.

 

We’ll explore how these operators work and how we can use them to streamline our code.

Basic Assignment Operator

Let’s start with the basics.

 

The equal sign (=) is the simple assignment operator in Python. It assigns the value on its right to the variable on its left.

 

Example:

a = 10 b = 5 c = a + b print(c)  # Output: 15

In this example:

 

  • We assign the values 10 to a and 5 to b.
  • We add a and b and assign the result to c.
  • We print the value of c, which is 15.

Augmented Assignment Operators in Python

Now, let’s move on to augmented assignment operators.

 

These operators combine an operation with an assignment in one step. They make our code more concise and easier to read.

Addition Assignment Operator (+=)

How It Works: This operator would thus add to the right operand and assign the result to the left operand.

 

Example:

a = 10 a += 5 print(a)  # Output: 15

Here, a is initially 10.

The ‘+=’ operator adds 5 to a and assigns the result back to a. So, a becomes 15.

Subtraction Assignment Operator (-=)

How It Works: It subtracts the right operand from the left operand and assigns the result to the left operand.

 

Example:

a = 10 a -= 5 print(a)  # Output: 5

Initially, a is 10.

The ‘-=’ operator subtracts 5 from a and assigns the result back to a. Thus, a becomes 5.

Multiplication Assignment Operator (*=)

How It Works: This is the operator for multiplication of the left operand by the right operand, with the result being assigned to the left operand.

 

Example:

a = 10 a *= 5 print(a)  # Output: 50

Initially, a is 10.

The ‘*=’ operator multiplies a by 5 and assigns the result back to a. Hence, a becomes 50.

Division Assignment Operator (/=)

How It Works: It divides the left operand by the right and assigns the outcome to the left operand.

 

Example:

a = 10 a /= 5 print(a)  # Output: 2.0

Initially, a is 10.

The ‘/=’ operator divides a by 5 and assigns the result back to a. Thus, a becomes 2.0.

Modulus Assignment Operator (%=)

How It Works: This operator divides the left operand by the right operand and assigns the remainder to the left operand.

 

Example:

a = 10 a %= 3 print(a)  # Output: 1

Initially, a is 10.

The ‘%=’ operator divides a by 3 and assigns the remainder back to a. Therefore, a becomes 1.

Floor Division Assignment Operator (//=)

How It Works: It performs floor division of the left operand by the right operand and, therefore, modifies the value of the left operand.

 

Example:

a = 10 a //= 3 print(a)  # Output: 3

Initially, a is 10.

The ‘//=’ operator divides a by 3 and assigns the floor value back to a. So, a becomes 3.

Exponentiation Assignment Operator (**=)

How It Works: The operator raises the left operand to the power of the right one and puts the result back into the left operand.

 

Example:

a = 2 a **= 3 print(a)  # Output: 8

Initially, a is 2.

The ‘**=’ operator raises a to the power of 3 and assigns the result back to a. Therefore, a becomes 8.

Bitwise AND Assignment Operator (&=)

How It Works: It performs a bitwise AND operation on the operands and assigns the result to the left operand.

 

Example:

a = 5  # 0101 in binary a &= 3  # 0011 in binary print(a)  # Output: 1 (0001 in binary)

Initially, a is 5 (0101 in binary).

The ‘&=’ operator performs a bitwise AND with 3 (0011 in binary) and assigns the result back to a. Thus, a becomes 1 (0001 in binary).

Bitwise OR Assignment Operator (|=)

How It Works: This operator performs a bitwise OR operation on the operands and assigns the result to the left operand.

 

Example:

a = 5  # 0101 in binary a |= 3  # 0011 in binary print(a)  # Output: 7 (0111 in binary)

Initially, a is 5 (0101 in binary).

The ‘|=’ operator performs a bitwise OR with 3 (0011 in binary) and assigns the result back to a. So, a becomes 7 (0111 in binary).

Bitwise XOR Assignment Operator (^=)

How It Works: It performs a bitwise XOR operation on the operands and assigns the result to the left operand.

 

Example:

a = 5  # 0101 in binary a ^= 3  # 0011 in binary print(a)  # Output: 6 (0110 in binary)

Initially, a is 5 (0101 in binary).

The ‘^=’ operator performs a bitwise XOR with 3 (0011 in binary) and assigns the result back to a. Thus, a becomes 6 (0110 in binary).

Bitwise Right Shift Assignment Operator (>>=)

How It Works: This operator performs a bitwise right shift on the left operand and assigns the result to the left operand.

 

Example:

a = 8  # 1000 in binary a >>= 2 print(a)  # Output: 2 (0010 in binary)

Initially, a is 8 (1000 in binary).

The ‘>>=’ operator right shifts a by 2 and assigns the result back to a. So, a becomes 2 (0010 in binary).

Bitwise Left Shift Assignment Operator (<<=)

How It Works: It performs a bitwise left shift on the left operand and assigns the result to the left operand.

 

Example:

a = 3  # 0011 in binary a <<= 2 print(a)  # Output: 12 (1100 in binary)

Initially, a is 3 (0011 in binary).

The ‘<<=’ operator left shifts a by 2 and assigns the result back to a. Therefore, a becomes 12 (1100 in binary).

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Introducing the Walrus Operator (:=)

Ever wondered if there’s a way to simplify assignments within expressions?

Meet the Walrus Operator.

The Walrus Operator (:=) allows us to assign values to variables as part of an expression. It makes our code more concise and readable.

 

Imagine you’re iterating over a list and want to process elements until the list becomes short. The Walrus Operator lets us do this efficiently.

 

Example:

a = [1, 2, 3, 4, 5] while (n := len(a)) > 2: print(n) a.pop()

Output:

1

  • n is assigned the length of a within the while loop condition.
  • The loop runs until a has two or fewer elements.
  • We reduce our code’s length without sacrificing clarity.

Practical Examples of Assignment Operators

Let’s dive into more practical examples of assignment operators in Python.

 

These examples will help us see how assignment operators make our code cleaner and more efficient.

Addition Assignment Operator (+=):

total = 0 for i in range(5): total += i print(total)

Output:

2

  • We use the += operator to accumulate the sum of numbers from 0 to 4.

Subtraction Assignment Operator (-=):

balance = 100 while balance > 0: withdrawal = int(input("Enter amount to withdraw: ")) balance -= withdrawal print(f"Remaining balance: {balance}")

Output:

3

  • We use the -= operator to update the balance after each withdrawal.

Multiplication Assignment Operator (*=):

factorial = 1 n = int(input("Enter a number: ")) for i in range(1, n + 1): factorial *= i print(f"The factorial of {n} is {factorial}")

Output:

4

Division Assignment Operator (/=):

amount = 1000 years = int(input("Enter the number of years: ")) while years > 0: amount /= 2 years -= 1 print(f"Amount after halving each year: {amount}")

Output:

5

Modulus Assignment Operator (%=):

number = int(input("Enter a number: ")) divisor = int(input("Enter the divisor: ")) number %= divisor print(f"Remainder: {number}")

Output:

6

Floor Division Assignment Operator (//=):

amount = 1000 years = int(input("Enter the number of years: ")) while years > 0: amount //= 2 years -= 1 print(f"Amount after floor division each year: {amount}")

Output:

7

Exponentiation Assignment Operator (**=):

base = int(input("Enter the base: ")) exponent = int(input("Enter the exponent: ")) base **= exponent print(f"Result: {base}")

Output:

8

Bitwise AND Assignment Operator (&=):

a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) a &= b print(f"Result of bitwise AND: {a}")

Output:

9

Bitwise OR Assignment Operator (|=):

a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) a |= b print(f"Result of bitwise OR: {a}")

Output:

10

Bitwise XOR Assignment Operator (^=):

a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) a ^= b print(f"Result of bitwise XOR: {a}")

Output:

11

Bitwise Right Shift Assignment Operator (>>=):

a = int(input("Enter a number: ")) shift = int(input("Enter the number of positions to shift: ")) a >>= shift print(f"Result after right shift: {a}")

Output:

12

Bitwise Left Shift Assignment Operator (<<=):

a = int(input("Enter a number: ")) shift = int(input("Enter the number of positions to shift: ")) a <<= shift print(f"Result after left shift: {a}")

Output:

13

Conclusion

Mastering assignment operators in Python can significantly improve our coding skills. These operators help us write cleaner, more efficient code. In this comprehensive guide, we explored assignment operators in Python, from the basic operator to the more advanced augmented operators and the Walrus Operator.

 

Whether we’re using simple assignments or the Walrus Operator, understanding these tools is essential. As we practice and apply these operators, our Python programming becomes more intuitive and effective.

FAQs
No, the Walrus Operator (:=) was introduced in Python 3.8 and is not available in earlier versions.
  • = operator is used for value assignment.
  • == does a comparison to check if the two values are equal.
Python will implicitly type cast if needed. For instance, if a float is added to an integer using ‘+=’, it will become a float.
  • += operator adds the right operand to the left operand and assigns the result to the left operand.
  • + simply adds the operands without assignment.
The Walrus Operator allows assignment within expressions, which can make code more concise and readable, especially within loops and comprehensions.
brochureimg

The DevOps Playbook

Simplify deployment with Docker containers.

Streamline development with modern practices.

Enhance efficiency with automated workflows.

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved