Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python assignment operators.

Assignment operators are used to assign values to variables:

Related Pages

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Getting Started
  • Keywords and Identifier
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python I/O and Import

Python Operators

  • Python Namespace

Python Flow Control

  • Python if...else
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python Pass

Python Functions

  • Python Function
  • Function Argument
  • Python Recursion
  • Anonymous Function
  • Global, Local and Nonlocal
  • Python Global Keyword
  • Python Modules
  • Python Package

Python Datatypes

  • Python Numbers
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary

Python Files

  • Python File Operation
  • Python Directory
  • Python Exception
  • Exception Handling
  • User-defined Exception

Python Object & Class

  • Classes & Objects
  • Python Inheritance
  • Multiple Inheritance
  • Operator Overloading

Python Advanced Topics

  • Python Iterator
  • Python Generator
  • Python Closure
  • Python Decorators
  • Python Property
  • Python RegEx

Python Date and time

  • Python datetime Module
  • Python datetime.strftime()
  • Python datetime.strptime()
  • Current date & time
  • Get current time
  • Timestamp to datetime
  • Python time Module
  • Python time.sleep()

Python Tutorials

Precedence and Associativity of Operators in Python

Python Operator Overloading

Python if...else Statement

Python 3 Tutorial

  • Python Strings
  • Python any()

Operators are special symbols that perform operations on variables and values. For example,

Here, + is an operator that adds two numbers: 5 and 6 .

  • Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Special Operators

1. Python Arithmetic Operators

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

Here, - is an arithmetic operator that subtracts two values or variables.

Example 1: Arithmetic Operators in Python

In the above example, we have used multiple arithmetic operators,

  • + to add a and b
  • - to subtract b from a
  • * to multiply a and b
  • / to divide a by b
  • // to floor divide a by b
  • % to get the remainder
  • ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

Here, = is an assignment operator that assigns 5 to x .

Here's a list of different assignment operators available in Python.

Example 2: Assignment Operators

Here, we have used the += operator to assign the sum of a and b to a .

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False . For example,

Here, the > comparison operator is used to compare whether a is greater than b or not.

Example 3: Comparison Operators

Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,

Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .

Example 4: Logical Operators

Note : Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)

6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.

  • Identity operators

In Python, is and is not are used to check if two values are located at the same memory location.

It's important to note that having two variables with equal values doesn't necessarily mean they are identical.

Example 4: Identity operators in Python

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.

  • Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).

In a dictionary, we can only test for the presence of a key, not the value.

Example 5: Membership operators in Python

Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .

  • Precedence and Associativity of operators in Python

Table of Contents

  • Introduction
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python Bitwise operators
  • Python Special operators

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

Assignment Operators

Add and assign, subtract and assign, multiply and assign, divide and assign, floor divide and assign, exponent and assign, modulo and assign.

For demonstration purposes, let’s use a single variable, num . Initially, we set num to 6. We can apply all of these operators to num and update it accordingly.

Assigning the value of 6 to num results in num being 6.

Expression: num = 6

Adding 3 to num and assigning the result back to num would result in 9.

Expression: num += 3

Subtracting 3 from num and assigning the result back to num would result in 6.

Expression: num -= 3

Multiplying num by 3 and assigning the result back to num would result in 18.

Expression: num *= 3

Dividing num by 3 and assigning the result back to num would result in 6.0 (always a float).

Expression: num /= 3

Performing floor division on num by 3 and assigning the result back to num would result in 2.

Expression: num //= 3

Raising num to the power of 3 and assigning the result back to num would result in 216.

Expression: num **= 3

Calculating the remainder when num is divided by 3 and assigning the result back to num would result in 2.

Expression: num %= 3

We can effectively put this into Python code, and you can experiment with the code yourself! Click the “Run” button to see the output.

The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values.

Python Tutorial

  • Python Basics
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators

Python - Assignment Operators

  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python Control Statements
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Object & Classes
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Built-in Exceptions
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - GUIs
  • Python Questions and Answers
  • Python Useful Resources
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Assignment Operator

The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

Example of Assignment Operator in Python

Consider following Python statements −

At the first instance, at least for somebody new to programming but who knows maths, the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.

Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.

In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as add and assign operator. In a single statement, it performs addition of two operands "a" and "b", and result is assigned to operand on left, i.e., "a".

Augmented Assignment Operators in Python

In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.

Python has the augmented assignment operators for all arithmetic and comparison operators.

Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.

The += operator is an augmented operator. It is also called cumulative addition operator, as it adds "b" in "a" and assigns the result back to a variable.

The following are the augmented assignment operators in Python:

  • Augmented Addition Operator
  • Augmented Subtraction Operator
  • Augmented Multiplication Operator
  • Augmented Division Operator
  • Augmented Modulus Operator
  • Augmented Exponent Operator
  • Augmented Floor division Operator

Augmented Addition Operator (+=)

Following examples will help in understanding how the "+=" operator works −

It will produce the following output −

Augmented Subtraction Operator (-=)

Use -= symbol to perform subtract and assign operations in a single statement. The "a-=b" statement performs "a=a-b" assignment. Operands may be of any number type. Python performs implicit type casting on the object which is narrower in size.

Augmented Multiplication Operator (*=)

The "*=" operator works on similar principle. "a*=b" performs multiply and assign operations, and is equivalent to "a=a*b". In case of augmented multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.

Augmented Division Operator (/=)

The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is equivalent to "a=a/b". The division operation of int or float operands is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.

Augmented Modulus Operator (%=)

To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not supported for complex number.

Augmented Exponent Operator (**=)

The "**=" operator results in computation of "a" raised to "b", and assigning the value back to "a". Given below are some examples −

Augmented Floor division Operator (//=)

For performing floor division and assignment in a single statement, use the "//=" operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

DEV Community

DEV Community

Aswin Barath

Posted on Jan 6, 2021 • Updated on Aug 29, 2023

Assignment Operators in python

Assignment operators are used to assigning values to variables.

Alt Text

OK, now comes the real fun. Have ever been tired to use x = x + 5 , where we type the variable x twice? There's actually a shortcut for this called Augmented assignment operators .

Augmented assignment operators can be used as a replacement as follows:

Here's the Code and Output

Alt Text

Quick Note : The code snippets reuses the same variable to assign with different arithmetic operations / bitwise operations / shift operations .

So, while coding makes sure you practice to use print statements after each operation.

Best Resources

Python Blog Series : A Blog series where I will be learning and sharing my knowledge on each of the above topics.

Learn Python for Free, Get Hired, and (maybe) Change the World! : A detailed roadmap blog by Jayson Lennon (a Senior Software Engineer) with links to free resources.

Zero To Mastery Course - Complete Python Developer : A comprehensive course by Andrei Neagoie (a Senior Developer) that covers all of the above topics.

I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through  Blogging  during the busy time of my freelancing work life. Here’s the link to all of my socials categorized by platforms under one place:  https://linktr.ee/AswinBarath

Thank you  so much for reading my blog🙂.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

sharker3312 profile image

Manual Approval and Telegram Notifications in Jenkins

Lester Diaz Perez - Mar 11

m__mdy__m profile image

Polymorphism in Javascript

mahdi - Mar 23

kartikmehta8 profile image

Introduction to Version Control with Git

Kartik Mehta - Mar 11

anmolbaranwal profile image

All the tools I need to build a perfect AI app.

Anmol Baranwal - Mar 14

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

ADVERTISEMENT

Coding Essentials Guidebook for Developers

This book covers core coding concepts and tools. It contains chapters on computer architecture, the Internet, Command Line, HTML, CSS, JavaScript, Python, Java, SQL, Git, and more.

Learn more!

Image of the cover of the Coding Essentials Guidebook for Developers

Decoding Git Guidebook for Developers

This book dives into the initial commit of Git's C code in detail to help developers learn what makes Git tick. If you're curious how Git works under the hood, you'll enjoy this.

Image of the cover of the Decoding Git Guidebook for Developers

Decoding Bitcoin Guidebook for Developers

This book dives into the initial commit of Bitcoin's C++ code. The book strives to unearth and simplify the concepts that underpin the Bitcoin software system, so that beginner and intermediate developers can understand how it works.

Image of the cover of the Decoding Bitcoin Guidebook for Developers

Subscribe to be notified when we release new content and features!

Follow us on your favorite channels!

Assignment Operators in Python

Image of Assignment Operators in Python

Table of Contents

Introduction, what are the assignment operators and why would you use them in python, how do you use the assignment operators in python and what are the benefits of doing so, what are the benefits of using the assignment operators in python, what are the potential drawbacks of using the assignment operators in python, when is it best to use the assignment operators in python, when is it not recommended to use the assignments operators in python, is there ++ in python, why isn't there ++ and -- in python.

Whether you are an old hand or you are just learning to program , assignment operators are a useful tool to add to your programming arsenal. Assignment operators are often used when you want to make a variable change by a specific amount in shorthand.

In this blog post, we will discuss what the assignment operators are, how to use them in Python, and the benefits and drawbacks of doing so. We will also explore when it is best to use assignment operators in Python, and when it may not be the best option. Finally, we will answer the question of whether or not the incrementing operator ++ is available in Python.

An assignment operator is a symbol that you use in Python to indicate that you want to perform some action and then assign the value to a . You would use an addition or subtraction operator in Python when you want to calculate the result of adding or subtracting two numbers. There are two types of addition operators: the plus sign + and the asterisk * . There are also two types of subtraction operators: the minus sign - and the forward slash / .

The plus sign + is used to indicate that you want to add two numbers together. The asterisk * is used to indicate that you want to multiply two numbers together. The minus sign - is used to indicate that you want to subtract two numbers. The forward slash / is used to indicate that you want to divide two numbers.

Here are some examples of how to use the addition and subtraction operators in Python:

The += operator is used to add two numbers together. The result of the addition will be stored in the variable that is on the left side of the += symbol. In this example, the result of adding y (15) to x (25) is stored in the variable x .

The -= operator is used to subtract one number from another. The result of the subtraction will be stored in the variable that is on the left side of the -= symbol. In this example, the result of subtracting y (15) from x (25) is stored in the variable x.

These operators are convenient ways to add or subtract values from a variable without having to use an intermediate variable. For example, if you want to add two numbers together and store the result in a new variable, you would write:

first_number = first_number + second_number

However, if you want to use the += operator instead, you can simply write:

first_number += second_number

This will save you a few keystrokes and also make your code more readable.

The -= operator is similarly useful for subtracting values from a variable. For example:

first_number -= second_number

This will subtract the second_number from the variable first_number .

One potential drawback to using the += and -= assignment operators in Python is that they can be confusing for beginners.

Another potential drawback is that they can lead to code that is difficult to read and understand.

However, these drawbacks are outweighed by the benefits of using these operators, which include increased readability and brevity of code. For these reasons, I recommend using the += , -= , *= , and /= assignment operators in Python whenever possible.

The increment operator is best used when you want to increment or decrement a variable by a number and you want to eliminate some keystrokes or create some brevity in your code.

In addition, it can also be used with other operators, such as the multiplication operator * . The following example shows how to use the increment operator with the multiplication operator:

This will print out the value of x as "120".

You may consider not using the assignment operators when you are dealing with a team of new programmers who may find the syntax confusing.

There are ways to mitigate this though, with training, lunch and learns, and more you can bring up the developers to the place where using some of the intricacies of Python.

No, the ++ (and -- ) operators available in C and other languages were not brought over to Python.

If you attempt to use ++ and -- the way they are used in C you will not get the results you are expecting. Use the += and -= operators.

Python doesn't have a ++ operator because it can be easily replaced with the += operator. Having both was probably thought to create more confusion.

There's a certain amount of ambiguity in the operator to the language parser. It could interpret the ++ in Python as two unary operators (+ and +) or it could be one unary operator (++).

Lastly, it can cause confusing side effects and Python likes to eliminate edge cases when interpreting the code. Look up C precedence issues of pre and post incrementation if you want to know more. It's not fun.

The += and -= assignment operators in Python are convenient ways to add or subtract values from a variable without having to use an intermediate variable. They are also more readable than traditional methods of adding or subtracting values. For these reasons, I recommend using the += and -= assignment operators whenever possible. You can learn more in the Python documentation . Start using these powerful tools today!

If you're interested in learning more about the basics of coding, programming, and software development, check out our Coding Essentials Guidebook for Developers , where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to [email protected] .

Final Notes

Recommended product: Coding Essentials Guidebook for Developers

Related Articles

Python zfill method.

Image of the Git logo

Python Yield vs Return

Python zip two lists, using raw_input() in python 3, python list print, numpy around() in python, get the first 5 chapters of our coding essentials guidebook for developers free , the programming guide i wish i had when i started learning to code... 🚀👨‍💻📚.

Image of the cover of the Coding Essentials Guidebook for Developers

Check out our Coding Essentials Guidebook for Developers

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in python.

' src=

Last Updated on June 8, 2023 by Prepbytes

assignment operator in python program

To fully comprehend the assignment operators in Python, it is important to have a basic understanding of what operators are. Operators are utilized to carry out a variety of operations, including mathematical, bitwise, and logical operations, among others, by connecting operands. Operands are the values that are acted upon by operators. In Python, the assignment operator is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is the most commonly used operator in Python. In this article, we will explore the assignment operator in Python, how it works, and its different types.

What is an Assignment Operator in Python?

The assignment operator in Python is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is used to assign a value to a variable. When an assignment operator is used, the value on the right-hand side is assigned to the variable on the left-hand side. This is a fundamental operation in programming, as it allows developers to store data in variables that can be used throughout their code.

For example, consider the following line of code:

Explanation: In this case, the value 10 is assigned to the variable a using the assignment operator. The variable a now holds the value 10, and this value can be used in other parts of the code. This simple example illustrates the basic usage and importance of assignment operators in Python programming.

Types of Assignment Operator in Python

There are several types of assignment operator in Python that are used to perform different operations. Let’s explore each type of assignment operator in Python in detail with the help of some code examples.

1. Simple Assignment Operator (=)

The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is:

Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example

Explanation: In this case, the value 25 is assigned to the variable a using the simple assignment operator. The variable a now holds the value 25.

2. Addition Assignment Operator (+=)

The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is:

Here, the value on the right-hand side is added to the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is incremented by 5 using the addition assignment operator. The result, 15, is then printed to the console.

3. Subtraction Assignment Operator (-=)

The subtraction assignment operator is used to subtract a value from a variable and store the result in the same variable. The syntax for the subtraction assignment operator is

Here, the value on the right-hand side is subtracted from the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is decremented by 5 using the subtraction assignment operator. The result, 5, is then printed to the console.

4. Multiplication Assignment Operator (*=)

The multiplication assignment operator is used to multiply a variable by a value and store the result in the same variable. The syntax for the multiplication assignment operator is:

Here, the value on the right-hand side is multiplied by the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is multiplied by 5 using the multiplication assignment operator. The result, 50, is then printed to the console.

5. Division Assignment Operator (/=)

The division assignment operator is used to divide a variable by a value and store the result in the same variable. The syntax for the division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 5 using the division assignment operator. The result, 2.0, is then printed to the console.

6. Modulus Assignment Operator (%=)

The modulus assignment operator is used to find the remainder of the division of a variable by a value and store the result in the same variable. The syntax for the modulus assignment operator is

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the remainder is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the modulus assignment operator. The remainder, 1, is then printed to the console.

7. Floor Division Assignment Operator (//=)

The floor division assignment operator is used to divide a variable by a value and round the result down to the nearest integer, and store the result in the same variable. The syntax for the floor division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is rounded down to the nearest integer. The rounded result is then stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the floor division assignment operator. The result, 3, is then printed to the console.

8. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator is used to raise a variable to the power of a value and store the result in the same variable. The syntax for the exponentiation assignment operator is:

Here, the variable on the left-hand side is raised to the power of the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is raised to the power of 3 using the exponentiation assignment operator. The result, 8, is then printed to the console.

9. Bitwise AND Assignment Operator (&=)

The bitwise AND assignment operator is used to perform a bitwise AND operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise AND assignment operator is:

Here, the variable on the left-hand side is ANDed with the value on the right-hand side using the bitwise AND operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ANDed with 3 using the bitwise AND assignment operator. The result, 2, is then printed to the console.

10. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator is used to perform a bitwise OR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise OR assignment operator is:

Here, the variable on the left-hand side is ORed with the value on the right-hand side using the bitwise OR operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ORed with 3 using the bitwise OR assignment operator. The result, 7, is then printed to the console.

11. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator is used to perform a bitwise XOR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise XOR assignment operator is:

Here, the variable on the left-hand side is XORed with the value on the right-hand side using the bitwise XOR operator, and the result are stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is XORed with 3 using the bitwise XOR assignment operator. The result, 5, is then printed to the console.

12. Bitwise Right Shift Assignment Operator (>>=)

The bitwise right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and store the result in the same variable. The syntax for the bitwise right shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the right by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is shifted 2 positions to the right using the bitwise right shift assignment operator. The result, 2, is then printed to the console.

13. Bitwise Left Shift Assignment Operator (<<=)

The bitwise left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and store the result in the same variable. The syntax for the bitwise left shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the left by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Conclusion Assignment operator in Python is used to assign values to variables, and it comes in different types. The simple assignment operator (=) assigns a value to a variable. The augmented assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=) perform a specified operation and assign the result to the same variable in one step. The modulus assignment operator (%) calculates the remainder of a division operation and assigns the result to the same variable. The bitwise assignment operators (&=, |=, ^=, >>=, <<=) perform bitwise operations and assign the result to the same variable. The bitwise right shift assignment operator (>>=) shifts the bits of a variable to the right by a specified number of positions and stores the result in the same variable. The bitwise left shift assignment operator (<<=) shifts the bits of a variable to the left by a specified number of positions and stores the result in the same variable. These operators are useful in simplifying and shortening code that involves assigning and manipulating values in a single step.

Here are some Frequently Asked Questions on Assignment Operator in Python:

Q1 – Can I use the assignment operator to assign multiple values to multiple variables at once? Ans – Yes, you can use the assignment operator to assign multiple values to multiple variables at once, separated by commas. For example, "x, y, z = 1, 2, 3" would assign the value 1 to x, 2 to y, and 3 to z.

Q2 – Is it possible to chain assignment operators in Python? Ans – Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For example, "x = y = z = 1" would assign the value 1 to all three variables.

Q3 – How do I perform a conditional assignment in Python? Ans – To perform a conditional assignment in Python, you can use the ternary operator. For example, "x = a (if a > b) else b" would assign the value of a to x if a is greater than b, otherwise it would assign the value of b to x.

Q4 – What happens if I use an undefined variable in an assignment operation in Python? Ans – If you use an undefined variable in an assignment operation in Python, you will get a NameError. Make sure you have defined the variable before trying to assign a value to it.

Q5 – Can I use assignment operators with non-numeric data types in Python? Ans – Yes, you can use assignment operators with non-numeric data types in Python, such as strings or lists. For example, "my_list += [4, 5, 6]" would append the values 4, 5, and 6 to the end of the list named my_list.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Single Program Multiple Data (SPMD) Model
  • Hybrid Blockchain
  • SciPy - Cluster
  • How to Reduce Code Duplication in Scala?
  • Stacked Bar Chart With Selection Using Altair in Python
  • Git - Move Files
  • Git - LFS (Large File Storage)
  • Git - Hooks
  • 5 Best Email Marketing Software
  • Principal Components Analysis in Data Mining
  • How to Use FlycoSystemBar Library in Android App?
  • How to Handle Big Repositories with Git?
  • What are Bitcoin Mitigating Attacks?
  • How to Create a Waffle Chart in Excel
  • How to Add Trendline in Excel Chart
  • How To Create Dot Plots In Excel?
  • How To Create a Tornado Chart In Excel?
  • How to Fix “Failed to install the following Android SDK packages as some licenses have not been accepted” Error in Android Studio?

Increment and Decrement Operators in Programming

Increment and Decrement Operators are Unary Operators commonly used in programming to increase or decrease the value of a variable by one , respectively. They provide a shorthand way to perform these common operations.

Table of Content

  • Increment Operators
  • Increment Operators in C
  • Increment Operators in C++
  • Increment Operators in Java
  • Increment Operators in Python
  • Increment Operators in C#
  • Increment Operators in Javascript
  • Decrement Operators
  • Decrement Operators in C
  • Decrement Operators in C++
  • Decrement Operators in Java
  • Decrement Operators in Python
  • Decrement Operators in C#
  • Decrement Operators in Javascript
  • Difference between Increment and Decrement Operator

Increment Operators:

Increment operators are used in programming languages to increase the value of a variable by one. There are two types of increment operators: the prefix increment operator (++x) and the postfix increment operator (x++).

Prefix Increment Operator (++x):

  • The prefix increment operator increases the value of the variable by 1 before the value is used in the expression.
  • Syntax: ++x
  • Example: If x is initially 5, ++x will increment x to 6 and return the new value (6).

Postfix Increment Operator (x++):

  • The postfix increment operator increases the value of the variable by 1 after the value is used in the expression.
  • Syntax: x++
  • Example: If x is initially 5, x++ will return the current value of x (5) and then increment x to 6.

Increment Operators in C :

Below is the implementation of Increment Operator in C:

Increment Operators in C++ :

Below is the implementation of Increment Operator in C++:

Increment Operators in Java :

Below is the implementation of Increment Operator in Java:

Increment Operators in Python :

There are no increment(++) or decrement(–) operators in programming. If we need to increment or decrement the value of a variably by 1, then we can use the increment assignment(+=) or decrement assignment(-=) operators. Below is the implementation:

Increment Operators in C# :

Below is the implementation of Increment Operator in C#:

Increment Operators in Javascript :

Below is the implementation of Increment Operator in Javascript:

Decrement Operators:

Decrement operators are used in programming languages to decrease the value of a variable by one. Similar to increment operators, there are two types of decrement operators: the prefix decrement operator (–x) and the postfix decrement operator (x–).

Prefix Decrement Operator (–x):

  • The prefix decrement operator decreases the value of the variable by 1 before the value is used in the expression.
  • Syntax: --x
  • Example: If x is initially 5, --x will decrement x to 4 and return the new value (4).

Postfix Decrement Operator (x–):

  • The postfix decrement operator decreases the value of the variable by 1 after the value is used in the expression.
  • Syntax: x--
  • Example: If x is initially 5, x-- will return the current value of x (5) and then decrement x to 4.

Decrement Operators in C:

Below is the implementation of Decrement Operator in C:

Decrement Operators in C++:

Below is the implementation of Decrement Operator in C++:

Decrement Operators in Java:

Below is the implementation of Decrement Operator in Java:

Decrement Operators in Python:

Below is the implementation of Decrement Operator in Python:

Decrement Operators in C#:

Below is the implementation of Decrement Operator in C#:

Decrement Operators in Javascript:

Below is the implementation of Decrement Operator in Javascript:

Difference between Increment and Decrement Operator:

Please login to comment....

  • Programming
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Python Operators

    assignment operator in python program

  2. PPT

    assignment operator in python program

  3. Python Tutorials: Assignment Operators In python

    assignment operator in python program

  4. Lecture14 :- Special Operators || Assignment operators || Bitwise

    assignment operator in python program

  5. Assignment operators in python

    assignment operator in python program

  6. Python Operator

    assignment operator in python program

VIDEO

  1. Assignment Operator

  2. Assignment

  3. Python Assignment Operator #python #assignmentoperators #pythonoperators #operatorsinpython

  4. operator

  5. Python datatypes operator

  6. Assignment & Relational Operator

COMMENTS

  1. Assignment Operators in Python

    So, Assignment Operators are used to assigning values to variables. Now Let's see each Assignment Operator one by one. 1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand. Syntax: Example: Output: 2) Add and Assign: This operator is used to add the right side operand with the left ...

  2. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  3. Python Assignment Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.

  4. Python Operators (With Examples)

    Assignment operators are used to assign values to variables. For example, # assign 5 to x var x = 5. Here, = is an assignment operator that assigns 5 to x. Here's a list of different assignment operators available in Python.

  5. Python Assignment Operators

    The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values. num_one = 6. num_two = 3. print(num_one) num_one += num_two. print(num_one) num_one -= num_two. print(num_one)

  6. Python Assignment Operators: Explained With Examples

    This operator is symbolized by the equals sign (=), marking its significance as one of the most frequently used operators in Python programming. Python assignment operators facilitate the storage of a value in a variable by assigning the value on the right side of the operator to the variable on the left.

  7. Operators and Expressions in Python

    In programming, an operator is usually a symbol or combination of symbols that allows you to perform a specific operation. ... check out The Walrus Operator: Python 3.8 Assignment Expressions. Unlike regular assignments, assignment expressions do have a return value, which is why they're expressions. So, the operator accomplishes two tasks:

  8. The Walrus Operator: Python 3.8 Assignment Expressions

    Each new version of Python adds new features to the language. For Python 3.8, the biggest change is the addition of assignment expressions.Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.. This tutorial is an in-depth introduction to the walrus operator.

  9. Python

    Python Assignment Operator. The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions ...

  10. Assignment Operators in python

    Quick Note: The code snippets reuses the same variable to assign with different arithmetic operations / bitwise operations / shift operations.. So, while coding makes sure you practice to use print statements after each operation. Best Resources Python Blog Series: A Blog series where I will be learning and sharing my knowledge on each of the above topics.

  11. Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity

    Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise. Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and ...

  12. Assignment Operators in Python

    An assignment operator is a symbol that you use in Python to indicate that you want to perform some action and then assign the value to a . You would use an addition or subtraction operator in Python when you want to calculate the result of adding or subtracting two numbers. There are two types of addition operators: the plus sign + and the ...

  13. Different Assignment operators in Python

    The Simple assignment operator in Python is denoted by = and is used to assign values from the right side of the operator to the value on the left side. Input: a = b + c. Add and equal operator. This operator adds the value on the right side to the value on the left side and stores the result in the operand on the left side. Input: a = 5. a += 10.

  14. Python Operators

    The Python programming language provides arithmetic operators that perform addition, subtraction, multiplication, and division. It works the same as basic mathematics. ... In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. For example, ...

  15. Assignment Operators in Python

    The primary assignment operator is the simple assignment operator ("="). We then learned that Python supports more complex assignment operators that can be used to calculate values in place. The assignment operators can be used to calculate mathematical, logical, and bitwise operations.

  16. Assignment Expressions: The Walrus Operator

    In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.Assignment expression are written with a new notation (:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.. Assignment expressions allow you to assign and return a value in the same expression.

  17. Assignment Operator in Python

    The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is: variable = value. Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example.

  18. What does colon equal (:=) in Python mean?

    Pseudocode is an informal high-level description of the operating principle of a computer program or other algorithm.:= is actually the assignment operator. In Python this is simply =. To translate this pseudocode into Python you would need to know the data structures being referenced, and a bit more of the algorithm implementation.

  19. Python Operators from Scratch!!!

    Below is the simple python snippet that you can use as a reference: # Assigning values to variables. a = 10. b = 11 # Identity is operator. print('a is b is',a is b) # Identity is not operator. print('a is not b is',a is not b) When you run the above python script you will be prompted by the following output.

  20. Python Operators

    Understanding these comparison operators is crucial for controlling the flow of a Python program, as they are commonly used in conditional statements and loops to evaluate conditions and make decisions. ... Assignment Operator In Python. Assignment operators in Python are used to assign values to variables. These operators make the code more ...

  21. A Comprehensive Guide to Augmented Assignment Operators in Python

    The augmented assignment operator performs the operation on the current value of the variable and assigns the result back to the same variable in a compact syntax. For example: Here x += 3 is equivalent to x = x + 3. The += augmented assignment operator adds the right operand 3 to the current value of x, which is 2.

  22. Operators: What Role Do They Play in Programming?

    Unary operators work on one operand, binary operators work on two operands, and ternary operators utilise three operands to carry out the task. Java's operators include: Assignment: This binary operator uses the symbol = to assign the value of the operand on the right of an expression to the one on the left.

  23. Increment and Decrement Operators in Programming

    Increment Operators in Python: There are no increment(++) or decrement(-) operators in programming. If we need to increment or decrement the value of a variably by 1, then we can use the increment assignment(+=) or decrement assignment(-=) operators. Below is the implementation: