Assignment Operators

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

to

to and assigns the result to

from and assigns the result to

by and assigns the result to

with and assigns the result to ; the result is always a float

with and assigns the result to ; the result will be dependent on the type of values used

to the power of and assigns the result to

is divided by and assigns the result to

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
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • 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 Advanced Concepts
  • Python - Abstract Base Classes
  • Python - Custom Exceptions
  • Python - Higher Order Functions
  • Python - Object Internals
  • Python - Memory Management
  • Python - Metaclasses
  • Python - Metaprogramming with Metaclasses
  • Python - Mocking and Stubbing
  • Python - Monkey Patching
  • Python - Signal Handling
  • Python - Type Hints
  • Python - Automation Tutorial
  • Python - Humanize Package
  • Python - Context Managers
  • Python - Coroutines
  • Python - Descriptors
  • Python - Diagnosing and Fixing Memory Leaks
  • Python - Immutable Data Structures
  • Python Useful Resources
  • Python - Questions & Answers
  • Python - Online Quiz
  • Python - Quick Guide
  • Python - Projects
  • Python - Useful Resources
  • Python - Discussion
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • 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.

theme logo

Logical Python

Effective Python Tutorials

Python Assignment Operators

Introduction to python assignment operators.

Assignment Operators are used for assigning values to the variables. We can also say that assignment operators are used to assign values to the left-hand side operand. For example, in the below table, we are assigning a value to variable ‘a’, which is the left-side operand.

OperatorDescriptionExampleEquivalent
= a = 2a = 2
+= a += 2a = a + 2
-= a -= 2a = a – 2
*= a *= 2a = a * 2
/= a /= 2a = a / 2
%= a %= 2a = a % 2
//= a //= 2a = a // 2
**= a **= 2a = a ** 2
&= a &= 2a = a & 2
|= a |= 2a = a | 2
^= a ^= 2a = a ^ 2
>>= a >>= 2a = a >> 2
<<= a <<= 3a = a << 2

Assignment Operators

Assignment operator.

Equal to sign ‘=’ is used as an assignment operator. It assigns values of the right-hand side expression to the variable or operand present on the left-hand side.

Assigns value 3 to variable ‘a’.

Addition and Assignment Operator

The addition and assignment operator adds left-side and right-side operands and then the sum is assigned to the left-hand side operand.

Below code is equivalent to:  a = a + 2.

Subtraction and Assignment Operator

The subtraction and assignment operator subtracts the right-side operand from the left-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a – 2.

Multiplication and Assignment Operator

The multiplication and assignment operator multiplies the right-side operand with the left-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a * 2.

Division and Assignment Operator

The division and assignment operator divides the left-side operand with the right-side operand, and then the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a / 2.

Modulus and Assignment Operator

The modulus and assignment operator divides the left-side operand with the right-side operand, and then the remainder is assigned to the left-hand side operand.

Below code is equivalent to:  a = a % 3.

Floor Division and Assignment Operator

The floor division and assignment operator divides the left side operand with the right side operand. The result is rounded down to the closest integer value(i.e. floor value) and is assigned to the left-hand side operand.

Below code is equivalent to:  a = a // 3.

Exponential and Assignment Operator

The exponential and assignment operator raises the left-side operand to the power of the right-side operand, and the result is assigned to the left-hand side operand.

Below code is equivalent to:  a = a ** 3.

Bitwise AND and Assignment Operator

Bitwise AND and assignment operator performs bitwise AND operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a & 3.

Illustration:

Numeric ValueBinary Value
2010
3011

Bitwise OR and Assignment Operator

Bitwise OR and assignment operator performs bitwise OR operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a | 3.

Bitwise XOR and Assignment Operator

Bitwise XOR and assignment operator performs bitwise XOR operation on both the operands and assign the result to the left-hand side operand.

Below code is equivalent to:  a = a ^ 3.

Bitwise Right Shift and Assignment Operator

Bitwise right shift and assignment operator right shifts the left operand by the right operand positions and assigns the result to the left-hand side operand.

Below code is equivalent to:  a = a >> 1.

Numeric InputBinary ValueRight shift by 1Numeric Output
2001000011
4010000102

Bitwise Left Shift and Assignment Operator

Bitwise left shift and assignment operator left shifts the left operand by the right operand positions and assigns the result to the left-hand side operand.

Below code is equivalent to:  a = a << 1.

Numeric InputBitwise ValueLeft shift by 1Numeric Output
2001001004
4010010008

References:

  • Different Assignment operators in Python
  • Assignment Operator in Python
  • Assignment Expressions

01 Career Opportunities

02 beginner, 03 intermediate, 04 training programs, assignment operators in python, what is an assignment operator in python.

.

Types of Assignment Operators in Python

1. simple python assignment operator (=), example of simple python assignment operator, 2. augmented assignment operators in python, 1. augmented arithmetic assignment operators in python.

+=Addition Assignment Operator
-=Subtraction Assignment Operator
*=Multiplication Assignment Operator
/=Division Assignment Operator
%=Modulus Assignment Operator
//=Floor Division Assignment Operator
**=Exponentiation Assignment Operator

2. Augmented Bitwise Assignment Operators in Python

&=Bitwise AND Assignment Operator
|=Bitwise OR Assignment Operator
^=Bitwise XOR Assignment Operator
>>=Bitwise Right Shift Assignment Operator
<<=Bitwise Left Shift Assignment Operator

Augmented Arithmetic Assignment Operators in Python

1. augmented addition operator (+=), example of augmented addition operator in python, 2. augmented subtraction operator (-=), example of augmented subtraction operator in python, 3. augmented multiplication operator (*=), example of augmented multiplication operator in python, 4. augmented division operator (/=), example of augmented division operator in python, 5. augmented modulus operator (%=), example of augmented modulus operator in python, 6. augmented floor division operator (//=), example of augmented floor division operator in python, 7. augmented exponent operator (**=), example of augmented exponent operator in python, augmented bitwise assignment operators in python, 1. augmented bitwise and (&=), example of augmented bitwise and operator in python, 2. augmented bitwise or (|=), example of augmented bitwise or operator in python, 3. augmented bitwise xor (^=), example of augmented bitwise xor operator in python, 4. augmented bitwise right shift (>>=), example of augmented bitwise right shift operator in python, 5. augmented bitwise left shift (<<=), example of augmented bitwise left shift operator in python, walrus operator in python, syntax of an assignment expression, example of walrus operator in python.

Live Classes Schedule

Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast
Filling Fast

About Author

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 returns a sum of two operands as a result.

Python includes the operator module that includes underlying methods for each operator. For example, the + operator calls the operator.add(a,b) method.

Above, expression 5 + 6 is equivalent to the expression operator.add(5, 6) and operator.__add__(5, 6) . Many function names are those used for special methods, without the double underscores (dunder methods). For backward compatibility, many of these have functions with the double underscores kept.

Python includes the following categories of operators:

Arithmetic Operators

Assignment operators, comparison operators, logical operators, identity operators, membership test operators, bitwise operators.

Arithmetic operators perform the common mathematical operation on the numeric operands.

The arithmetic operators return the type of result depends on the type of operands, as below.

  • If either operand is a complex number, the result is converted to complex;
  • If either operand is a floating point number, the result is converted to floating point;
  • If both operands are integers, then the result is an integer and no conversion is needed.

The following table lists all the arithmetic operators in Python:

Operation Operator Function Example in Python Shell
Sum of two operands + operator.add(a,b)
Left operand minus right operand - operator.sub(a,b)
* operator.mul(a,b)
Left operand raised to the power of right ** operator.pow(a,b)
/ operator.truediv(a,b)
equivilant to // operator.floordiv(a,b)
Reminder of % operator.mod(a, b)

The assignment operators are used to assign values to variables. The following table lists all the arithmetic operators in Python:

Operator Function Example in Python Shell
=
+= operator.iadd(a,b)
-= operator.isub(a,b)
*= operator.imul(a,b)
/= operator.itruediv(a,b)
//= operator.ifloordiv(a,b)
%= operator.imod(a, b)
&= operator.iand(a, b)
|= operator.ior(a, b)
^= operator.ixor(a, b)
>>= operator.irshift(a, b)
<<= operator.ilshift(a, b)

The comparison operators compare two operands and return a boolean either True or False. The following table lists comparison operators in Python.

Operator Function Description Example in Python Shell
> operator.gt(a,b) True if the left operand is higher than the right one
< operator.lt(a,b) True if the left operand is lower than right one
== operator.eq(a,b) True if the operands are equal
!= operator.ne(a,b) True if the operands are not equal
>= operator.ge(a,b) True if the left operand is higher than or equal to the right one
<= operator.le(a,b) True if the left operand is lower than or equal to the right one

The logical operators are used to combine two boolean expressions. The logical operations are generally applicable to all objects, and support truth tests, identity tests, and boolean operations.

Operator Description Example
and True if both are true
or True if at least one is true
not Returns True if an expression evalutes to false and vice-versa

The identity operators check whether the two objects have the same id value e.i. both the objects point to the same memory location.

Operator Function Description Example in Python Shell
is operator.is_(a,b) True if both are true
is not operator.is_not(a,b) True if at least one is true

The membership test operators in and not in test whether the sequence has a given item or not. For the string and bytes types, x in y is True if and only if x is a substring of y .

Operator Function Description Example in Python Shell
in operator.contains(a,b) Returns True if the sequence contains the specified item else returns False.
not in not operator.contains(a,b) Returns True if the sequence does not contains the specified item, else returns False.

Bitwise operators perform operations on binary operands.

Operator Function Description Example in Python Shell
& operator.and_(a,b) Sets each bit to 1 if both bits are 1.
| operator.or_(a,b) Sets each bit to 1 if one of two bits is 1.
^ operator.xor(a,b) Sets each bit to 1 if only one of two bits is 1.
~ operator.invert(a) Inverts all the bits.
<< operator.lshift(a,b) Shift left by pushing zeros in from the right and let the leftmost bits fall off.
>> operator.rshift(a,b) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

assignment operators used in python

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles

Python Assignment Operators

Lesson Contents

Python assignment operators are one of the operator types and assign values to variables . We use arithmetic operators here in combination with a variable.

Let’s take a look at some examples.

Operator Assignment (=)

This is the most basic assignment operator and we used it before in the lessons about lists , tuples , and dictionaries .  For example, we can assign a value (integer) to a variable:

Operator Addition (+=)

We can add a number to our variable like this:

Using the above operator is the same as doing this:

The += operator is shorter to write but the end result is the same.

Operator Subtraction (-=)

We can also subtract a value. For example:

Using this operator is the same as doing this:

Operator Multiplication (*=)

We can also use multiplication. We’ll multiply our variable by 4:

Which is similar to:

Operator Division (/=)

Let’s try the divide operator:

This is the same as:

Operator Modulus (%=)

We can also calculate the modulus. How about this:

This is the same as doing it like this:

Operator Exponentiation (**=)

How about exponentiation? Let’s give it a try:

Which is the same as doing it like this:

Operator Floor Division (//=)

The last one, floor division:

You have now learned how to use the Python assignment operators to assign values to variables and how you can use them with arithmetic operators . I hope you enjoyed this lesson. If you have any questions, please leave a comment.

Ask a question or start a discussion by visiting our Community Forum

Operators and Expressions in Python

Operators and Expressions in Python

Table of Contents

Getting Started With Operators and Expressions

The assignment operator and statements, arithmetic operators and expressions in python, comparison of integer values, comparison of floating-point values, comparison of strings, comparison of lists and tuples, boolean expressions involving boolean operands, evaluation of regular objects in a boolean context, boolean expressions involving other types of operands, compound logical expressions and short-circuit evaluation, idioms that exploit short-circuit evaluation, compound vs chained expressions, conditional expressions or the ternary operator, identity operators and expressions in python, membership operators and expressions in python, concatenation and repetition operators and expressions, the walrus operator and assignment expressions, bitwise operators and expressions in python, operator precedence in python, augmented assignment operators and expressions.

In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation. So, operators are the building blocks of expressions, which you can use to manipulate your data. Therefore, understanding how operators work in Python is essential for you as a programmer.

In this tutorial, you’ll learn about the operators that Python currently supports. You’ll also learn the basics of how to use these operators to build expressions.

In this tutorial, you’ll:

  • Get to know Python’s arithmetic operators and use them to build arithmetic expressions
  • Explore Python’s comparison , Boolean , identity , and membership operators
  • Build expressions with comparison, Boolean, identity, and membership operators
  • Learn about Python’s bitwise operators and how to use them
  • Combine and repeat sequences using the concatenation and repetition operators
  • Understand the augmented assignment operators and how they work

To get the most out of this tutorial, you should have a basic understanding of Python programming concepts, such as variables , assignments , and built-in data types .

Free Bonus: Click here to download your comprehensive cheat sheet covering the various operators in Python.

Take the Quiz: Test your knowledge with our interactive “Python Operators and Expressions” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python operators and expressions.

In programming, an operator is usually a symbol or combination of symbols that allows you to perform a specific operation. This operation can act on one or more operands . If the operation involves a single operand, then the operator is unary . If the operator involves two operands, then the operator is binary .

For example, in Python, you can use the minus sign ( - ) as a unary operator to declare a negative number. You can also use it to subtract two numbers:

In this code snippet, the minus sign ( - ) in the first example is a unary operator, and the number 273.15 is the operand. In the second example, the same symbol is a binary operator, and the numbers 5 and 2 are its left and right operands.

Programming languages typically have operators built in as part of their syntax. In many languages, including Python, you can also create your own operator or modify the behavior of existing ones, which is a powerful and advanced feature to have.

In practice, operators provide a quick shortcut for you to manipulate data, perform mathematical calculations, compare values, run Boolean tests, assign values to variables, and more. In Python, an operator may be a symbol, a combination of symbols, or a keyword , depending on the type of operator that you’re dealing with.

For example, you’ve already seen the subtraction operator, which is represented with a single minus sign ( - ). The equality operator is a double equal sign ( == ). So, it’s a combination of symbols:

In this example, you use the Python equality operator ( == ) to compare two numbers. As a result, you get True , which is one of Python’s Boolean values.

Speaking of Boolean values, the Boolean or logical operators in Python are keywords rather than signs, as you’ll learn in the section about Boolean operators and expressions . So, instead of the odd signs like || , && , and ! that many other programming languages use, Python uses or , and , and not .

Using keywords instead of odd signs is a really cool design decision that’s consistent with the fact that Python loves and encourages code’s readability .

You’ll find several categories or groups of operators in Python. Here’s a quick list of those categories:

  • Assignment operators
  • Arithmetic operators
  • Comparison operators
  • Boolean or logical operators
  • Identity operators
  • Membership operators
  • Concatenation and repetition operators
  • Bitwise operators

All these types of operators take care of specific types of computations and data-processing tasks. You’ll learn more about these categories throughout this tutorial. However, before jumping into more practical discussions, you need to know that the most elementary goal of an operator is to be part of an expression . Operators by themselves don’t do much:

As you can see in this code snippet, if you use an operator without the required operands, then you’ll get a syntax error . So, operators must be part of expressions, which you can build using Python objects as operands.

So, what is an expression anyway? Python has simple and compound statements. A simple statement is a construct that occupies a single logical line , like an assignment statement. A compound statement is a construct that occupies multiple logical lines, such as a for loop or a conditional statement. An expression is a simple statement that produces and returns a value.

You’ll find operators in many expressions. Here are a few examples:

In the first two examples, you use the addition and division operators to construct two arithmetic expressions whose operands are integer numbers. In the last example, you use the equality operator to create a comparison expression. In all cases, you get a specific value after executing the expression.

Note that not all expressions use operators. For example, a bare function call is an expression that doesn’t require any operator:

In the first example, you call the built-in abs() function to get the absolute value of -7 . Then, you compute 2 to the power of 8 using the built-in pow() function. These function calls occupy a single logical line and return a value. So, they’re expressions.

Finally, the call to the built-in print() function is another expression. This time, the function doesn’t return a fruitful value, but it still returns None , which is the Python null type . So, the call is technically an expression.

Note: All Python functions have a return value, either explicit or implicit. If you don’t provide an explicit return statement when defining a function, then Python will automatically make the function return None .

Even though all expressions are statements, not all statements are expressions. For example, pure assignment statements don’t return any value, as you’ll learn in a moment. Therefore, they’re not expressions. The assignment operator is a special operator that doesn’t create an expression but a statement.

Note: Since version 3.8, Python also has what it calls assignment expressions. These are special types of assignments that do return a value. You’ll learn more about this topic in the section The Walrus Operator and Assignment Expressions .

Okay! That was a quick introduction to operators and expressions in Python. Now it’s time to dive deeper into the topic. To kick things off, you’ll start with the assignment operator and statements.

The assignment operator is one of the most frequently used operators in Python. The operator consists of a single equal sign ( = ), and it operates on two operands. The left-hand operand is typically a variable , while the right-hand operand is an expression.

Note: As you already learned, the assignment operator doesn’t create an expression. Instead, it creates a statement that doesn’t return any value.

The assignment operator allows you to assign values to variables . Strictly speaking, in Python, this operator makes variables or names refer to specific objects in your computer’s memory. In other words, an assignment creates a reference to a concrete object and attaches that reference to the target variable.

Note: To dive deeper into using the assignment operator, check out Python’s Assignment Operator: Write Robust Assignments .

For example, all the statements below create new variables that hold references to specific objects:

In the first statement, you create the number variable, which holds a reference to the number 42 in your computer’s memory. You can also say that the name number points to 42 , which is a concrete object.

In the rest of the examples, you create other variables that point to other types of objects, such as a string , tuple , and list , respectively.

You’ll use the assignment operator in many of the examples that you’ll write throughout this tutorial. More importantly, you’ll use this operator many times in your own code. It’ll be your forever friend. Now you can dive into other Python operators!

Arithmetic operators are those operators that allow you to perform arithmetic operations on numeric values. Yes, they come from math, and in most cases, you’ll represent them with the usual math signs. The following table lists the arithmetic operators that Python currently supports:

Operator Type Operation Sample Expression Result
Unary Positive without any transformation since this is simply a complement to negation
Binary Addition The arithmetic sum of and
Unary Negation The value of but with the opposite sign
Binary Subtraction subtracted from
Binary Multiplication The product of and
Binary Division The quotient of divided by , expressed as a float
Binary Modulo The remainder of divided by
Binary Floor division or integer division The quotient of divided by , rounded to the next smallest whole number
Binary Exponentiation raised to the power of

Note that a and b in the Sample Expression column represent numeric values, such as integer , floating-point , complex , rational , and decimal numbers.

Here are some examples of these operators in use:

In this code snippet, you first create two new variables, a and b , holding 5 and 2 , respectively. Then you use these variables to create different arithmetic expressions using a specific operator in each expression.

Note: The Python REPL will display the return value of an expression as a way to provide immediate feedback to you. So, when you’re in an interactive session, you don’t need to use the print() function to check the result of an expression. You can just type in the expression and press Enter to get the result.

Again, the standard division operator ( / ) always returns a floating-point number, even if the dividend is evenly divisible by the divisor:

In the first example, 10 is evenly divisible by 5 . Therefore, this operation could return the integer 2 . However, it returns the floating-point number 2.0 . In the second example, 10.0 is a floating-point number, and 5 is an integer. In this case, Python internally promotes 5 to 5.0 and runs the division. The result is a floating-point number too.

Note: With complex numbers, the division operator doesn’t return a floating-point number but a complex one:

Here, you run a division between an integer and a complex number. In this case, the standard division operator returns a complex number.

Finally, consider the following examples of using the floor division ( // ) operator:

Floor division always rounds down . This means that the result is the greatest integer that’s smaller than or equal to the quotient. For positive numbers, it’s as though the fractional portion is truncated, leaving only the integer portion.

Comparison Operators and Expressions in Python

The Python comparison operators allow you to compare numerical values and any other objects that support them. The table below lists all the currently available comparison operators in Python:

Operator Operation Sample Expression Result
Equal to • if the value of is equal to the value of
• otherwise
Not equal to • if isn’t equal to
• otherwise
Less than • if is less than
• otherwise
Less than or equal to • if is less than or equal to
• otherwise
Greater than • if is greater than
• otherwise
Greater than or equal to • if is greater than or equal to
• otherwise

The comparison operators are all binary. This means that they require left and right operands. These operators always return a Boolean value ( True or False ) that depends on the truth value of the comparison at hand.

Note that comparisons between objects of different data types often don’t make sense and sometimes aren’t allowed in Python. For example, you can compare a number and a string for equality with the == operator. However, you’ll get False as a result:

The integer 2 isn’t equal to the string "2" . Therefore, you get False as a result. You can also use the != operator in the above expression, in which case you’ll get True as a result.

Non-equality comparisons between operands of different data types raise a TypeError exception:

In this example, Python raises a TypeError exception because a less than comparison ( < ) doesn’t make sense between an integer and a string. So, the operation isn’t allowed.

It’s important to note that in the context of comparisons, integer and floating-point values are compatible, and you can compare them.

You’ll typically use and find comparison operators in Boolean contexts like conditional statements and while loops . They allow you to make decisions and define a program’s control flow .

The comparison operators work on several types of operands, such as numbers, strings, tuples, and lists. In the following sections, you’ll explore the differences.

Probably, the more straightforward comparisons in Python and in math are those involving integer numbers. They allow you to count real objects, which is a familiar day-to-day task. In fact, the non-negative integers are also called natural numbers . So, comparing this type of number is probably pretty intuitive, and doing so in Python is no exception.

Consider the following examples that compare integer numbers:

In the first set of examples, you define two variables, a and b , to run a few comparisons between them. The value of a is less than the value of b . So, every comparison expression returns the expected Boolean value. The second set of examples uses two values that are equal, and again, you get the expected results.

Comparing floating-point numbers is a bit more complicated than comparing integers. The value stored in a float object may not be precisely what you’d think it would be. For that reason, it’s bad practice to compare floating-point values for exact equality using the == operator.

Consider the example below:

Yikes! The internal representation of this addition isn’t exactly equal to 3.3 , as you can see in the final example. So, comparing x to 3.3 with the equality operator returns False .

To compare floating-point numbers for equality, you need to use a different approach. The preferred way to determine whether two floating-point values are equal is to determine whether they’re close to one another, given some tolerance.

The math module from the standard library provides a function conveniently called isclose() that will help you with float comparison. The function takes two numbers and tests them for approximate equality:

In this example, you use the isclose() function to compare x and 3.3 for approximate equality. This time, you get True as a result because both numbers are close enough to be considered equal.

For further details on using isclose() , check out the Find the Closeness of Numbers With Python isclose() section in The Python math Module: Everything You Need to Know .

You can also use the comparison operators to compare Python strings in your code. In this context, you need to be aware of how Python internally compares string objects. In practice, Python compares strings character by character using each character’s Unicode code point . Unicode is Python’s default character set .

You can use the built-in ord() function to learn the Unicode code point of any character in Python. Consider the following examples:

The uppercase "A" has a lower Unicode point than the lowercase "a" . So, "A" is less than "a" . In the end, Python compares characters using integer numbers. So, the same rules that Python uses to compare integers apply to string comparison.

When it comes to strings with several characters, Python runs the comparison character by character in a loop.

The comparison uses lexicographical ordering , which means that Python compares the first item from each string. If their Unicode code points are different, this difference determines the comparison result. If the Unicode code points are equal, then Python compares the next two characters, and so on, until either string is exhausted:

In this example, Python compares both operands character by character. When it reaches the end of the string, it compares "o" and "O" . Because the lowercase letter has a greater Unicode code point, the first version of the string is greater than the second.

You can also compare strings of different lengths:

In this example, Python runs a character-by-character comparison as usual. If it runs out of characters, then the shorter string is less than the longer one. This also means that the empty string is the smallest possible string.

In your Python journey, you can also face the need to compare lists with other lists and tuples with other tuples. These data types also support the standard comparison operators. Like with strings, when you use a comparison operator to compare two lists or two tuples, Python runs an item-by-item comparison.

Note that Python applies specific rules depending on the type of the contained items. Here are some examples that compare lists and tuples of integer values:

In these examples, you compare lists and tuples of numbers using the standard comparison operators. When comparing these data types, Python runs an item-by-item comparison.

For example, in the first expression above, Python compares the 2 in the left operand and the 2 in the right operand. Because they’re equal, Python continues comparing 3 and 3 to conclude that both lists are equal. The same thing happens in the second example, where you compare tuples containing the same data.

It’s important to note that you can actually compare lists to tuples using the == and != operators. However, you can’t compare lists and tuples using the < , > , <= , and >= operators:

Python supports equality comparison between lists and tuples. However, it doesn’t support the rest of the comparison operators, as you can conclude from the final two examples. If you try to use them, then you get a TypeError telling you that the operation isn’t supported.

You can also compare lists and tuples of different lengths:

In the first two examples, you get True as a result because 5 is less than 8 . That fact is sufficient for Python to solve the comparison. In the second pair of examples, you get False . This result makes sense because the compared sequences don’t have the same length, so they can’t be equal.

In the final pair of examples, Python compares 5 with 5 . They’re equal, so the comparison continues. Because there are no more values to compare in the right-hand operands, Python concludes that the left-hand operands are greater.

As you can see, comparing lists and tuples can be tricky. It’s also an expensive operation that, in the worst case, requires traversing two entire sequences. Things get more complex and expensive when the contained items are also sequences. In those situations, Python will also have to compare items in a value-by-value manner, which adds cost to the operation.

Boolean Operators and Expressions in Python

Python has three Boolean or logical operators: and , or , and not . They define a set of operations denoted by the generic operators AND , OR , and NOT . With these operators, you can create compound conditions.

In the following sections, you’ll learn how the Python Boolean operators work. Especially, you’ll learn that some of them behave differently when you use them with Boolean values or with regular objects as operands.

You’ll find many objects and expressions that are of Boolean type or bool , as Python calls this type. In other words, many objects evaluate to True or False , which are the Python Boolean values.

For example, when you evaluate an expression using a comparison operator, the result of that expression is always of bool type:

In this example, the expression age > 18 returns a Boolean value, which you store in the is_adult variable. Now is_adult is of bool type, as you can see after calling the built-in type() function.

You can also find Python built-in and custom functions that return a Boolean value. This type of function is known as a predicate function. The built-in all() , any() , callable() , and isinstance() functions are all good examples of this practice.

Consider the following examples:

In this code snippet, you first define a variable called number using your old friend the assignment operator. Then you create another variable called validation_conditions . This variable holds a tuple of expressions. The first expression uses isinstance() to check whether number is an integer value.

The second is a compound expression that combines the modulo ( % ) and equality ( == ) operators to create a condition that checks whether the input value is an even number. In this condition, the modulo operator returns the remainder of dividing number by 2 , and the equality operator compares the result with 0 , returning True or False as the comparison’s result.

Then you use the all() function to determine if all the conditions are true. In this example, because number = 42 , the conditions are true, and all() returns True . You can play with the value of number if you’d like to experiment a bit.

In the final two examples, you use the callable() function. As its name suggests, this function allows you to determine whether an object is callable . Being callable means that you can call the object with a pair of parentheses and appropriate arguments, as you’d call any Python function.

The number variable isn’t callable, and the function returns False , accordingly. In contrast, the print() function is callable, so callable() returns True .

All the previous discussion is the basis for understanding how the Python logical operators work with Boolean operands.

Logical expressions involving and , or , and not are straightforward when the operands are Boolean. Here’s a summary. Note that x and y represent Boolean operands:

Operator Sample Expression Result
• if both and are
• otherwise
• if either or is
• otherwise
• if is
• if is

This table summarizes the truth value of expressions that you can create using the logical operators with Boolean operands. There’s something to note in this summary. Unlike and and or , which are binary operators, the not operator is unary, meaning that it operates on one operand. This operand must always be on the right side.

Now it’s time to take a look at how the operators work in practice. Here are a few examples of using the and operator with Boolean operands:

In the first example, both operands return True . Therefore, the and expression returns True as a result. In the second example, the left-hand operand is True , but the right-hand operand is False . Because of this, the and operator returns False .

In the third example, the left-hand operand is False . In this case, the and operator immediately returns False and never evaluates the 3 == 3 condition. This behavior is called short-circuit evaluation . You’ll learn more about it in a moment.

Note: Short-circuit evaluation is also called McCarthy evaluation in honor of computer scientist John McCarthy .

In the final example, both conditions return False . Again, and returns False as a result. However, because of the short-circuit evaluation, the right-hand expression isn’t evaluated.

What about the or operator? Here are a few examples that demonstrate how it works:

In the first three examples, at least one of the conditions returns True . In all cases, the or operator returns True . Note that if the left-hand operand is True , then or applies short-circuit evaluation and doesn’t evaluate the right-hand operand. This makes sense. If the left-hand operand is True , then or already knows the final result. Why would it need to continue the evaluation if the result won’t change?

In the final example, both operands are False , and this is the only situation where or returns False . It’s important to note that if the left-hand operand is False , then or has to evaluate the right-hand operand to arrive at a final conclusion.

Finally, you have the not operator, which negates the current truth value of an object or expression:

If you place not before an expression, then you get the inverse truth value. When the expression returns True , you get False . When the expression evaluates to False , you get True .

There is a fundamental behavior distinction between not and the other two Boolean operators. In a not expression, you always get a Boolean value as a result. That’s not always the rule that governs and and or expressions, as you’ll learn in the Boolean Expressions Involving Other Types of Operands section.

In practice, most Python objects and expressions aren’t Boolean. In other words, most objects and expressions don’t have a True or False value but a different type of value. However, you can use any Python object in a Boolean context, such as a conditional statement or a while loop.

In Python, all objects have a specific truth value. So, you can use the logical operators with all types of operands.

Python has well-established rules to determine the truth value of an object when you use that object in a Boolean context or as an operand in an expression built with logical operators. Here’s what the documentation says about this topic:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false: constants defined to be false: None and False . zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1) empty sequences and collections: '' , () , [] , {} , set() , range(0) ( Source )

You can determine the truth value of an object by calling the built-in bool() function with that object as an argument. If bool() returns True , then the object is truthy . If bool() returns False , then it’s falsy .

For numeric values, you have that a zero value is falsy, while a non-zero value is truthy:

Python considers the zero value of all numeric types falsy. All the other values are truthy, regardless of how close to zero they are.

Note: Instead of a function, bool() is a class. However, because Python developers typically use this class as a function, you’ll find that most people refer to it as a function rather than as a class. Additionally, the documentation lists this class on the built-in functions page. This is one of those cases where practicality beats purity .

When it comes to evaluating strings, you have that an empty string is always falsy, while a non-empty string is truthy:

Note that strings containing white spaces are also truthy in Python’s eyes. So, don’t confuse empty strings with whitespace strings.

Finally, built-in container data types, such as lists, tuples, sets , and dictionaries , are falsy when they’re empty. Otherwise, Python considers them truthy objects:

To determine the truth value of container data types, Python relies on the .__len__() special method . This method provides support for the built-in len() function, which you can use to determine the number of items in a given container.

In general, if .__len__() returns 0 , then Python considers the container a falsy object, which is consistent with the general rules you’ve just learned before.

All the discussion about the truth value of Python objects in this section is key to understanding how the logical operators behave when they take arbitrary objects as operands.

You can also use any objects, such as numbers or strings, as operands to and , or , and not . You can even use combinations of a Boolean object and a regular one. In these situations, the result depends on the truth value of the operands.

Note: Boolean expressions that combine two Boolean operands are a special case of a more general rule that allows you to use the logical operators with all kinds of operands. In every case, you’ll get one of the operands as a result.

You’ve already learned how Python determines the truth value of objects. So, you’re ready to dive into creating expressions with logic operators and regular objects.

To start off, below is a table that summarizes what you get when you use two objects, x and y , in an and expression:

If is returns
Truthy
Falsy

It’s important to emphasize a subtle detail in the above table. When you use and in an expression, you don’t always get True or False as a result. Instead, you get one of the operands. You only get True or False if the returned operand has either of these values.

Here are some code examples that use integer values. Remember that in Python, the zero value of numeric types is falsy. The rest of the values are truthy:

In the first expression, the left-hand operand ( 3 ) is truthy. So, you get the right-hand operand ( 4 ) as a result.

In the second example, the left-hand operand ( 0 ) is falsy, and you get it as a result. In this case, Python applies the short-circuit evaluation technique. It already knows that the whole expression is false because 0 is falsy, so Python returns 0 immediately without evaluating the right-hand operand.

In the final expression, the left-hand operand ( 3 ) is truthy. Therefore Python needs to evaluate the right-hand operand to make a conclusion. As a result, you get the right-hand operand, no matter what its truth value is.

Note: To dive deeper into the and operator, check out Using the “and” Boolean Operator in Python .

When it comes to using the or operator, you also get one of the operands as a result. This is what happens for two arbitrary objects, x and y :

Again, the expression x or y doesn’t evaluate to either True or False . Instead, it returns one of its operands, x or y .

As you can conclude from the above table, if the left-hand operand is truthy, then you get it as a result. Otherwise, you get the second operand. Here are some examples that demonstrate this behavior:

In the first example, the left-hand operand is truthy, and or immediately returns it. In this case, Python doesn’t evaluate the second operand because it already knows the final result. In the second example, the left-hand operand is falsy, and Python has to evaluate the right-hand one to determine the result.

In the last example, the left-hand operand is truthy, and that fact defines the result of the expression. There’s no need to evaluate the right-hand operand.

An expression like x or y is truthy if either x or y is truthy, and falsy if both x and y are falsy. This type of expression returns the first truthy operand that it finds. If both operands are falsy, then the expression returns the right-hand operand. To see this latter behavior in action, consider the following example:

In this specific expression, both operands are falsy. So, the or operator returns the right-hand operand, and the whole expression is falsy as a result.

Note: To learn more about the or operator, check out Using the “or” Boolean Operator in Python .

Finally, you have the not operator. You can also use this one with any object as an operand. Here’s what happens:

The not operator has a uniform behavior. It always returns a Boolean value. This behavior differs from its sibling operators, and and or .

Here are some code examples:

In the first example, the operand, 3 , is truthy from Python’s point of view. So, the operator returns False . In the second example, the operand is falsy, and not returns True .

Note: To better understand the not operator, check out Using the “not” Boolean Operator in Python .

In summary, the Python not operator negates the truth value of an object and always returns a Boolean value. This latter behavior differs from the behavior of its sibling operators and and or , which return operands rather than Boolean values.

So far, you’ve seen expressions with only a single or or and operator and two operands. However, you can also create compound logical expressions with multiple logical operators and operands.

To illustrate how to create a compound expression using or , consider the following toy example:

This expression returns the first truthy value. If all the preceding x variables are falsy, then the expression returns the last value, xn .

Note: In an expression like the one above, Python uses short-circuit evaluation . The operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true. At that point, Python stops evaluating operands. The value of the entire expression is that of the x that terminates the evaluation.

To help demonstrate short-circuit evaluation, suppose that you have an identity function , f() , that behaves as follows:

  • Takes a single argument
  • Displays the function and its argument on the screen
  • Returns the argument as its return value

Here’s the code to define this function and also a few examples of how it works:

The f() function displays its argument, which visually confirms whether you called the function. It also returns the argument as you passed it in the call. Because of this behavior, you can make the expression f(arg) be truthy or falsy by specifying a value for arg that’s truthy or falsy, respectively.

Now, consider the following compound logical expression:

In this example, Python first evaluates f(0) , which returns 0 . This value is falsy. The expression isn’t true yet, so the evaluation continues from left to right. The next operand, f(False) , returns False . That value is also falsy, so the evaluation continues.

Next up is f(1) . That evaluates to 1 , which is truthy. At that point, Python stops the evaluation because it already knows that the entire expression is truthy. Consequently, Python returns 1 as the value of the expression and never evaluates the remaining operands, f(2) and f(3) . You can confirm from the output that the f(2) and f(3) calls don’t occur.

A similar behavior appears in an expression with multiple and operators like the following one:

This expression is truthy if all the operands are truthy. If at least one operand is falsy, then the expression is also falsy.

In this example, short-circuit evaluation dictates that Python stops evaluating as soon as an operand happens to be falsy. At that point, the entire expression is known to be false. Once that’s the case, Python stops evaluating operands and returns the falsy operand that terminated the evaluation.

Here are two examples that confirm the short-circuiting behavior:

In both examples, the evaluation stops at the first falsy term— f(False) in the first case, f(0.0) in the second case—and neither the f(2) nor the f(3) call occurs. In the end, the expressions return False and 0.0 , respectively.

If all the operands are truthy, then Python evaluates them all and returns the last (rightmost) one as the value of the expression:

In the first example, all the operands are truthy. The expression is also truthy and returns the last operand. In the second example, all the operands are truthy except for the last one. The expression is falsy and returns the last operand.

As you dig into Python, you’ll find that there are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression, performance, and safety. For example, you can take advantage of this type of evaluation for:

  • Avoiding an exception
  • Providing a default value
  • Skipping a costly operation

To illustrate the first point, suppose you have two variables, a and b , and you want to know whether the division of b by a results in a number greater than 0 . In this case, you can run the following expression or condition:

This code works. However, you need to account for the possibility that a might be 0 , in which case you’ll get an exception :

In this example, the divisor is 0 , which makes Python raise a ZeroDivisionError exception. This exception breaks your code. You can skip this error with an expression like the following:

When a is 0 , a != 0 is false. Python’s short-circuit evaluation ensures that the evaluation stops at that point, which means that (b / a) never runs, and the error never occurs.

Using this technique, you can implement a function to determine whether an integer is divisible by another integer:

In this function, if b is 0 , then a / b isn’t defined. So, the numbers aren’t divisible. If b is different from 0 , then the result will depend on the remainder of the division.

Selecting a default value when a specified value is falsy is another idiom that takes advantage of the short-circuit evaluation feature of Python’s logical operators.

For example, say that you have a variable that’s supposed to contain a country’s name. At some point, this variable can end up holding an empty string. If that’s the case, then you’d like the variable to hold a default county name. You can also do this with the or operator:

If country is non-empty, then it’s truthy. In this scenario, the expression will return the first truthy value, which is country in the first or expression. The evaluation stops, and you get "Canada" as a result.

On the other hand, if country is an empty string , then it’s falsy. The evaluation continues to the next operand, default_country , which is truthy. Finally, you get the default country as a result.

Another interesting use case for short-circuit evaluation is to avoid costly operations while creating compound logical expressions. For example, if you have a costly operation that should only run if a given condition is false, then you can use or like in the following snippet:

In this construct, your clean_data() function represents a costly operation. Because of short-circuit evaluation, this function will only run when data_is_clean is false, which means that your data isn’t clean.

Another variation of this technique is when you want to run a costly operation if a given condition is true. In this case, you can use the and operator:

In this example, the and operator evaluates data_is_updated . If this variable is true, then the evaluation continues, and the process_data() function runs. Otherwise, the evaluation stops, and process_data() never runs.

Sometimes you have a compound expression that uses the and operator to join comparison expressions. For example, say that you want to determine if a number is in a given interval. You can solve this problem with a compound expression like the following:

In this example, you use the and operator to join two comparison expressions that allow you to find out if number is in the interval from 0 to 10 , both included.

In Python, you can make this compound expression more concise by chaining the comparison operators together. For example, the following chained expression is equivalent to the previous compound one:

This expression is more concise and readable than the original expression. You can quickly realize that this code is checking if the number is between 0 and 10 . Note that in most programming languages, this chained expression doesn’t make sense. In Python, it works like a charm.

In other programming languages, this expression would probably start by evaluating 0 <= number , which is true. This true value would then be compared with 10 , which doesn’t make much sense, so the expression fails.

Python internally processes this type of expression as an equivalent and expression, such as 0 <= number and number <= 10 . That’s why you get the correct result in the example above.

Python has what it calls conditional expressions . These kinds of expressions are inspired by the ternary operator that looks like a ? b : c and is used in other programming languages. This construct evaluates to b if the value of a is true, and otherwise evaluates to c . Because of this, sometimes the equivalent Python syntax is also known as the ternary operator.

However, in Python, the expression looks more readable:

This expression returns expression_1 if the condition is true and expression_2 otherwise. Note that this expression is equivalent to a regular conditional like the following:

So, why does Python need this syntax? PEP 308 introduced conditional expressions as an effort to avoid the prevalence of error-prone attempts to achieve the same effect of a traditional ternary operator using the and and or operators in an expression like the following:

However, this expression doesn’t work as expected, returning expression_2 when expression_1 is falsy.

Some Python developers would avoid the syntax of conditional expressions in favor of a regular conditional statement. In any case, this syntax can be handy in some situations because it provides a concise tool for writing two-way conditionals.

Here’s an example of how to use the conditional expression syntax in your code:

When day is equal to "Sunday" , the condition is true and you get the first expression, "11AM" , as a result. If the condition is false, then you get the second expression, "9AM" . Note that similarly to the and and or operators, the conditional expression returns the value of one of its expressions rather than a Boolean value.

Python provides two operators, is and is not , that allow you to determine whether two operands have the same identity . In other words, they let you check if the operands refer to the same object. Note that identity isn’t the same thing as equality. The latter aims to check whether two operands contain the same data.

Note: To learn more about the difference between identity and equality, check out Python ‘!=’ Is Not ‘is not’: Comparing Objects in Python .

Here’s a summary of Python’s identity operators. Note that x and y are variables that point to objects:

Operator Sample Expression Result
• if and hold a reference to the same in-memory object
• otherwise
• if points to an object different from the object that points to
• otherwise

These two Python operators are keywords instead of odd symbols. This is part of Python’s goal of favoring readability in its syntax.

Here’s an example of two variables, x and y , that refer to objects that are equal but not identical:

In this example, x and y refer to objects whose value is 1001 . So, they’re equal. However, they don’t reference the same object. That’s why the is operator returns False . You can check an object’s identity using the built-in id() function:

As you can conclude from the id() output, x and y don’t have the same identity. So, they’re different objects, and because of that, the expression x is y returns False . In other words, you get False because you have two different instances of 1001 stored in your computer’s memory.

When you make an assignment like y = x , Python creates a second reference to the same object. Again, you can confirm that with the id() function or the is operator:

In this example, a and b hold references to the same object, the string "Hello, Pythonista!" . Therefore, the id() function returns the same identity when you call it with a and b . Similarly, the is operator returns True .

Note: You should note that, on your computer, you’ll get a different identity number when you call id() in the example above. The key detail is that the identity number will be the same for a and b .

Finally, the is not operator is the opposite of is . So, you can use is not to determine if two names don’t refer to the same object:

In the first example, because x and y point to different objects in your computer’s memory, the is not operator returns True . In the second example, because a and b are references to the same object, the is not operator returns False .

Note: The syntax not x is y also works the same as x is not y . However, the former syntax looks odd and is difficult to read. That’s why Python recognizes is not as an operator and encourages its use for readability.

Again, the is not operator highlights Python’s readability goals. In general, both identity operators allow you to write checks that read as plain English.

Sometimes you need to determine whether a value is present in a container data type, such as a list, tuple, or set. In other words, you may need to check if a given value is or is not a member of a collection of values. Python calls this kind of check a membership test .

Note: For a deep dive into how Python’s membership tests work, check out Python’s “in” and “not in” Operators: Check for Membership .

Membership tests are quite common and useful in programming. As with many other common operations, Python has dedicated operators for membership tests. The table below lists the membership operators in Python:

Operator Sample Expression Result
• if present in
• otherwise
• if present in of values
• otherwise

As usual, Python favors readability by using English words as operators instead of potentially confusing symbols or combinations of symbols.

Note: The syntax not value in collection also works in Python. However, this syntax looks odd and is difficult to read. So, to keep your code clean and readable, you should use value not in collection , which almost reads as plain English.

The Python in and not in operators are binary. This means that you can create membership expressions by connecting two operands with either operator. However, the operands in a membership expression have particular characteristics:

  • Left operand : The value that you want to look for in a collection of values
  • Right operand : The collection of values where the target value may be found

To better understand the in operator, below you have two demonstrative examples consisting of determining whether a value is in a list:

The first expression returns True because 5 is in the list of numbers. The second expression returns False because 8 isn’t in the list.

The not in membership operator runs the opposite test as the in operator. It allows you to check whether an integer value is not in a collection of values:

In the first example, you get False because 5 is in the target list. In the second example, you get True because 8 isn’t in the list of values. This may sound like a tongue twister because of the negative logic. To avoid confusion, remember that you’re trying to determine if the value is not part of a given collection of values.

There are two operators in Python that acquire a slightly different meaning when you use them with sequence data types, such as lists, tuples, and strings. With these types of operands, the + operator defines a concatenation operator , and the * operator represents the repetition operator :

Operator Operation Sample Expression Result
Concatenation A new sequence containing all the items from both operands
Repetition A new sequence containing the items of repeated times

Both operators are binary. The concatenation operator takes two sequences as operands and returns a new sequence of the same type. The repetition operator takes a sequence and an integer number as operands. Like in regular multiplication, the order of the operands doesn’t alter the repetition’s result.

Note: To learn more about concatenating string objects, check out Efficient String Concatenation in Python .

Here are some examples of how the concatenation operator works in practice:

In the first example, you use the concatenation operator ( + ) to join two strings together. The operator returns a completely new string object that combines the two original strings.

In the second example, you concatenate two tuples of letters together. Again, the operator returns a new tuple object containing all the items from the original operands. In the final example, you do something similar but this time with two lists.

Note: To learn more about concatenating lists, check out the Concatenating Lists section in the tutorial Python’s list Data Type: A Deep Dive With Examples .

When it comes to the repetition operator, the idea is to repeat the content of a given sequence a certain number of times. Here are a few examples:

In the first example, you use the repetition operator ( * ) to repeat the "Hello" string three times. In the second example, you change the order of the operands by placing the integer number on the left and the target string on the right. This example shows that the order of the operands doesn’t affect the result.

The next examples use the repetition operators with a tuple and a list, respectively. In both cases, you get a new object of the same type containing the items in the original sequence repeated three times.

Regular assignment statements with the = operator don’t have a return value, as you already learned. Instead, the assignment operator creates or updates variables. Because of this, the operator can’t be part of an expression.

Since Python 3.8 , you have access to a new operator that allows for a new type of assignment. This new assignment is called assignment expression or named expression . The new operator is called the walrus operator , and it’s the combination of a colon and an equal sign ( := ).

Note: The name walrus comes from the fact that this operator resembles the eyes and tusks of a walrus lying on its side. For a deep dive into how this operator works, check out The Walrus Operator: Python’s Assignment Expressions .

Unlike regular assignments, assignment expressions do have a return value, which is why they’re expressions . So, the operator accomplishes two tasks:

  • Returns the expression’s result
  • Assigns the result to a variable

The walrus operator is also a binary operator. Its left-hand operand must be a variable name, and its right-hand operand can be any Python expression. The operator will evaluate the expression, assign its value to the target variable, and return the value.

The general syntax of an assignment expression is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, in certain situations, you won’t need them. Either way, they won’t hurt you, so it’s safe to use them.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand. It’s particularly useful in the context of a conditional statement. To illustrate, the example below shows a toy function that checks the length of a string object:

In this example, you use a conditional statement to check whether the input string has fewer than 8 characters.

The assignment expression, (n := len(string)) , computes the string length and assigns it to n . Then it returns the value that results from calling len() , which finally gets compared with 8 . This way, you guarantee that you have a reference to the string length to use in further operations.

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. Currently, Python supports the following bitwise operators:

Operator Operation Sample Expression Result
Bitwise AND • Each bit position in the result is the logical AND of the bits in the corresponding position of the operands.
• if both bits are , otherwise .
Bitwise OR • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if either bit is , otherwise .
Bitwise NOT • Each bit position in the result is the logical negation of the bit in the corresponding position of the operand.
• if the bit is and if the bit is .
Bitwise XOR (exclusive OR) • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if the bits in the operands are different, if they’re equal.
Bitwise right shift Each bit is shifted right places.
Bitwise left shift Each bit is shifted left places.

As you can see in this table, most bitwise operators are binary, which means that they expect two operands. The bitwise NOT operator ( ~ ) is the only unary operator because it expects a single operand, which should always appear at the right side of the expression.

You can use Python’s bitwise operators to manipulate your data at its most granular level, the bits. These operators are commonly useful when you want to write low-level algorithms, such as compression, encryption, and others.

Note: For a deep dive into the bitwise operators, check out Bitwise Operators in Python . You can also check out Build a Maze Solver in Python Using Graphs for an example of using bitwise operators to construct a binary file format.

Here are some examples that illustrate how some of the bitwise operators work in practice:

In the first example, you use the bitwise AND operator. The commented lines begin with # and provide a visual representation of what happens at the bit level. Note how each bit in the result is the logical AND of the bits in the corresponding position of the operands.

The second example shows how the bitwise OR operator works. In this case, the resulting bits are the logical OR test of the corresponding bits in the operands.

In all the examples, you’ve used the built-in bin() function to display the result as a binary object. If you don’t wrap the expression in a call to bin() , then you’ll get the integer representation of the output.

Up to this point, you’ve coded sample expressions that mostly use one or two different types of operators. However, what if you need to create compound expressions that use several different types of operators, such as comparison, arithmetic, Boolean, and others? How does Python decide which operation runs first?

Consider the following math expression:

There might be ambiguity in this expression. Should Python perform the addition 20 + 4 first and then multiply the result by 10 ? Should Python run the multiplication 4 * 10 first, and the addition second?

Because the result is 60 , you can conclude that Python has chosen the latter approach. If it had chosen the former, then the result would be 240 . This follows a standard algebraic rule that you’ll find in virtually all programming languages.

All operators that Python supports have a precedence compared to other operators. This precedence defines the order in which Python runs the operators in a compound expression.

In an expression, Python runs the operators of highest precedence first. After obtaining those results, Python runs the operators of the next highest precedence. This process continues until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order.

Here’s the order of precedence of the Python operators that you’ve seen so far, from highest to lowest:

Operators Description
Exponentiation
, , Unary positive, unary negation, bitwise negation
, , , Multiplication, division, floor division,
, Addition, subtraction
, Bitwise shifts
Bitwise AND
Bitwise XOR
Bitwise OR
, , , , , , , , , Comparisons, identity, and membership
Boolean NOT
Boolean AND
Boolean OR
Walrus

Operators at the top of the table have the highest precedence, and those at the bottom of the table have the lowest precedence. Any operators in the same row of the table have equal precedence.

Getting back to your initial example, Python runs the multiplication because the multiplication operator has a higher precedence than the addition one.

Here’s another illustrative example:

In the example above, Python first raises 3 to the power of 4 , which equals 81 . Then, it carries out the multiplications in order from left to right: 2 * 81 = 162 and 162 * 5 = 810 .

You can override the default operator precedence using parentheses to group terms as you do in math. The subexpressions in parentheses will run before expressions that aren’t in parentheses.

Here are some examples that show how a pair of parentheses can affect the result of an expression:

In the first example, Python computes the expression 20 + 4 first because it’s wrapped in parentheses. Then Python multiplies the result by 10 , and the expression returns 240 . This result is completely different from what you got at the beginning of this section.

In the second example, Python evaluates 4 * 5 first. Then it raises 3 to the power of the resulting value. Finally, Python multiplies the result by 2 , returning 6973568802 .

There’s nothing wrong with making liberal use of parentheses, even when they aren’t necessary to change the order of evaluation. Sometimes it’s a good practice to use parentheses because they can improve your code’s readability and relieve the reader from having to recall operator precedence from memory.

Consider the following example:

Here the parentheses are unnecessary, as the comparison operators have higher precedence than and . However, some might find the parenthesized version clearer than the version without parentheses:

On the other hand, some developers might prefer this latter version of the expression. It’s a matter of personal preference. The point is that you can always use parentheses if you feel that they make your code more readable, even if they aren’t necessary to change the order of evaluation.

So far, you’ve learned that a single equal sign ( = ) represents the assignment operator and allows you to assign a value to a variable. Having a right-hand operand that contains other variables is perfectly valid, as you’ve also learned. In particular, the expression to the right of the assignment operator can include the same variable that’s on the left of the operand.

That last sentence may sound confusing, so here’s an example that clarifies the point:

In this example, total is an accumulator variable that you use to accumulate successive values. You should read this example as total is equal to the current value of total plus 5 . This expression effectively increases the value of total , which is now 15 .

Note that this type of assignment only makes sense if the variable in question already has a value. If you try the assignment with an undefined variable, then you get an error:

In this example, the count variable isn’t defined before the assignment, so it doesn’t have a current value. In consequence, Python raises a NameError exception to let you know about the issue.

This type of assignment helps you create accumulators and counter variables, for example. Therefore, it’s quite a common task in programming. As in many similar cases, Python offers a more convenient solution. It supports a shorthand syntax called augmented assignment :

In the highlighted line, you use the augmented addition operator ( += ). With this operator, you create an assignment that’s fully equivalent to total = total + 5 .

Python supports many augmented assignment operators. In general, the syntax for this type of assignment looks something like this:

Note that the dollar sign ( $ ) isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. The above statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the assignment operator ( = ), using the current value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

The table below shows a summary of the augmented operators for arithmetic operations:

Operator Description Sample Expression Equivalent Expression
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

As you can conclude from this table, all the arithmetic operators have an augmented version in Python. You can use these augmented operators as a shortcut when creating accumulators, counters, and similar objects.

Did the augmented arithmetic operators look neat and useful to you? The good news is that there are more. You also have augmented bitwise operators in Python:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

Finally, the concatenation and repetition operators have augmented variations too. These variations behave differently with mutable and immutable data types:

Operator Description Example
• Runs an augmented concatenation operation on the target sequence.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.
• Adds to itself times.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator works on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Now you know what operators Python supports and how to use them. Operators are symbols, combinations of symbols, or keywords that you can use along with Python objects to build different types of expressions and perform computations in your code.

In this tutorial, you’ve learned:

  • What Python’s arithmetic operators are and how to use them in arithmetic expressions
  • What Python’s comparison , Boolean , identity , membership operators are
  • How to write expressions using comparison, Boolean, identity, and membership operators
  • Which bitwise operators Python supports and how to use them
  • How to combine and repeat sequences using the concatenation and repetition operators
  • What the augmented assignment operators are and how they work

In other words, you’ve covered an awful lot of ground! If you’d like a handy cheat sheet that can jog your memory on all that you’ve learned, then click the link below:

With all this knowledge about operators, you’re better prepared as a Python developer. You’ll be able to write better and more robust expressions in your code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Dan Bader

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Operators and Expressions in Python (Cheat Sheet)

🔒 No spam. We take your privacy seriously.

assignment operators used in python

Currently Reading :

Currently reading:

Simple assignment operator in Python

Different assignment operators in python.

Rajat Gupta

Software Developer

Published on  Thu Jun 30 2022

Assignment operators in Python are in-fix which are used to perform operations on variables or operands and assign values to the operand on the left side of the operator. They perform arithmetic, logical, and bitwise computations.

Assignment Operators in Python

Add and equal operator, subtract and equal operator, multiply and equal operator, divide and equal operator, modulus and equal operator, double divide and equal operator, exponent assign operator.

  • Bitwise and operator

Bitwise OR operator

  • Bitwise XOR Assignment operator

Bitwise right shift assignment operator

Bitwise left shift assignment operator.

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.

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.

This operator subtracts the value on the right side from the value on the left side and stores the result in the operand on the left side.

The Multiply and equal operator multiplies the right operand with the left operand and then stores the result in the left operand.

It divides the left operand with the right operand and then stores the quotient in the left operand.

The modulus and equal operator finds the modulus from the left and right operand and stores the final result in the left operand.

The double divide and equal or the divide floor and equal operator divides the left operand with the right operand and stores the floor result in the left operand.

It performs exponential or power calculation and assigns value to the left operand.

Bitwise And operator

Performs Bitwise And operation on both variables and stores the result in the left operand. The Bitwise And operation compares the corresponding bits of the left operand to the bits of the right operand and if both bits are 1, the corresponding result is also 1 otherwise 0.

The binary value of 3 is 0011 and the binary value of 5 is 0101, so when the Bitwise And operation is performed on both the values, we get 0001, which is 1 in decimal.

Performs Bitwise OR operator on both variables and stores the result in the left operand. The Bitwise OR operation compares the corresponding bits of the left operand to the bits of the right operand and if any one of the bits is 1, the corresponding result is also 1 otherwise 0.

The binary value of 5 is 0101 and the binary value of 10 is 1010, so when the Bitwise OR operation is performed on both the values, we get 1111, which is 15 in decimal .

Bitwise XOR operator

Performs Bitwise XOR operator on both variables and stores the result in the left operand. The Bitwise XOR operation compares the corresponding bits of the left operand to the bits of the right operand and if only one of the bits is 1, the corresponding result is also 1 otherwise 0.

The binary value of 5 is 0101 and the binary value of 9 is 1001, so when the Bitwise XOR operation is performed on both the values, we get 1100, which is 12 in decimal.

This operator performs a Bitwise right shift on the operands and stores the result in the left operand.

The binary value of 15 is 1111, so when the Bitwise right shift operation is performed on ‘a’, we get 0011, which is 3 in decimal.

This operator performs a Bitwise left shift on the operands and stores the result in the left operand.

The binary value of 15 is 1111, so when the Bitwise left shift operation is performed on ‘a’, we get 11110, which is 30 in decimal.

Closing Thoughts

In this tutorial, we read about different types of assignment operators in Python which are special symbols used to perform arithmetic, logical, and bitwise operations on the operands and store the result in the left side operand. One can read about other Python concepts here .

Related Blogs

4 Ways to implement Python Switch Case Statement

Sanchitee Ladole

Converting String to Float in Python

Ancil Eric D'Silva

Memoization Using Decorators In Python

Harsh Pandey

Harsh Pandey

Python Increment - Everything you need to know

Theano Python Beginner Guide for Getting Started

Taygun Dogan

Taygun Dogan

17 min read

Python Classes And Objects

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.

  • Programmers
  • React Native
  • Ruby on Rails

assignment operators used in python

Assignment Operators in Python

Assignment Operators in Python

Table of Contents

Assignment Operators will work on values and variables. They are the special symbols that hold arithmetic, logical, and bitwise computations. The value which the operator operates is referred to as the Operand.

Read this article about Assignment Operators in Python

What are Assignment Operators?

The assignment operator will function to provide value to variables. The table below is about the different types of Assignment operator

+= will add right side operand with left side operand, assign to left operand a+=b
= It will assign the value of the right side of the expression to the left side operandx=y+z
-= can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala -= b  
*= can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala *= b     
/= will divide the left operand with right operand and then assign to the left operanda /= b
%= will divide the left operand with the right operand and then assign to the left operanda %= b  
<<=
It functions bitwise left on operands and will assign value to the left operand a <<= b 
>>=
This operator will perform right shift on operands and can assign value to the left operanda >>= b     

^=
This will function the bitwise xOR operands and can assign value to the left operand a ^= b    

|=
This will function Bitwise OR operands and will provide value to the left operand.a |= b    

&=
This operator will perform Bitwise AND on operand and can provide value to the left operanda&=b
**=
operator will evaluate the exponent value with the help of operands an assign value to the left operanda**=b

Here we have listed each of the Assignment operators

1. What is Assign Operator?

This assign operator will provide the value of the right side of the expression to the left operand.

2. What is Add and Assign

This Add and Assign operator will function to add the right side operand with the left side operator, and provide the result to the left operand.

3. What is Subtract and assign ?

This subtract and assign operator works to subtract the right operand from the left operand and give the result to the left operand.

4. What is Multiply and assign ?

This Multiply and assign will function to multiply the right operand with the left operand and will provide the result in the left operand.

5. What is Divide and assign Operator?

This functions to divide the left operand and provides results at the left operand.

6. What is Modulus and Assign Operator?

This operator functions using the modulus with the left and the right operand and provides results at the left operand.

7. What is Divide ( floor)and Assign Operator?

This operator will divide the left operand with the right operand, and provide the result at the left operand.

8. What is Exponent and Assign Operator?

This operator will function to evaluate the exponent and value with the operands and, provide output in the left operand.

9.What is Bitwise and Assign Operator?

This operator will function Bitwise AND on both the operand and provide the result on the left operand.

10. What is Bitwise OR and Assign Operator?

This operand will function Bitwise OR on the operand, and can provide result at the left operand.

11. What is Bitwise XOR and Assign Operator?

This operator will function for Bitwise XOR on the operands, and provide result at the left operand.

12. What is Bitwise Right Shift and Assign Operator?

This operator will function by providing the Bitwise shift on the operands and giving the result at the left operand.

13. What is Bitwise Left shift and Assign Operator?

This operator will function Bitwise left shift by providing the Bitwise left shift on the operands and giving the result on the left operand.

To conclude, different types of assignment operators are discussed in this. Beginners can improve their knowledge and understand how to apply the assignment operators through reading this.

Assignment Operators in Python- FAQs

Q1. what is an assignment statement in python.

Ans. It will calculate the expression list and can provide a single resulting object to each target list from left to right

Q2. What is the compound operator in Python?

Ans. The compound operator will do the operation of a binary operator and will save the result of the operation at the left operand.

Q3. What are the two types of assignment statements

Ans. Simple Assignment Statements and Reference Assignment Statements are the two types of assignment statements.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Python Logical Operators

Python Bitwise Operator

Leave a Comment Cancel reply

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

Reach Out to Us for Any Query

SkillVertex is an edtech organization that aims to provide upskilling and training to students as well as working professionals by delivering a diverse range of programs in accordance with their needs and future aspirations.

© 2024 Skill Vertex

  • Read Tutorial
  • Watch Guide Video

If that is about as clear as mud don't worry we're going to walk through a number of examples. And one very nice thing about the syntax for assignment operators is that it is nearly identical to a standard type of operator. So if you memorize the list of all the python operators then you're going to be able to use each one of these assignment operators quite easily.

The very first thing I'm going to do is let's first make sure that we can print out the total. So right here we have a total and it's an integer that equals 100. Now if we wanted to add say 10 to 100 how would we go about doing that? We could reassign the value total and we could say total and then just add 10. So let's see if this works right here. I'm going to run it and you can see we have a hundred and ten. So that works.

large

However, whenever you find yourself performing this type of calculation what you can do is use an assignment operator. And so the syntax for that is going to get rid of everything here in the middle and say plus equals and then whatever value. In this case I want to add onto it.

So you can see we have our operator and then right afterward you have an equal sign. And this is going to do is exactly like what we had before. So if I run this again you can see total is a hundred and ten

large

I'm going to just so you have a reference in the show notes I'm going to say that total equals total plus 10. This is exactly the same as what we're doing right here we're simply using assignment in order to do it.

I'm going to quickly go through each one of the other elements that you can use assignment for. And if you go back and you reference the show notes or your own notes for whenever you kept track of all of the different operators you're going to notice a trend. And that is because they're all exactly the same. So here if I want to subtract 10 from the total I can simply use the subtraction operator here run it again. And now you can see we have 90. Now don't be confused because we only temporarily change the value to 1 10. So when I commented this out and I ran it from scratch it took the total and it subtracted 10 from that total and that's what got printed out.

large

I'm going to copy this and the next one down the line is going to be multiplication. So in this case I'm going to say multiply with the asterisk the total and I'm just going to say times two just so we can see exactly what the value is going to be. And now we can see that's 200 which makes sense.

large

So we've taken total we have multiplied it by two and we have piped the entire thing into the total variable. So far so good. As you may have guessed next when we're going to do is division. So now I'm going to say total and then we're going to perform this division assignment and we're going to say divide this by 10 run it and you can see it gives us the value and it converts it to a float of ten point zero.

large

Now if this is starting to get a little bit much. Let's take a quick pause and see exactly what this is doing. Remember that all we're doing here is it's a shortcut. You could still perform it the same way we have in number 3 I could say total is equal to the total divided by 10. And if I run this you'll see we get ten point zero. And let's see what this warning is it says redefinition of total type from int to float. So we don't have to worry about this and this for if you're building Python programs you're very rarely ever going to see the syntax and it's because we have this assignment operator right here. So that is for division. And we also have the ability to use floor division as well. So if I run this you're going to see it's 10. But one thing you may notice is it's 10 it's not ten point zero. So remember that our floor division returns an integer it doesn't return a floating-point number. So if that is what you want then you can perform that task just like we did there.

Next one on the list is our exponents. I'm going to say the total and we're going to say we're going to assign that to the total squared. So going to run this and we get ten thousand. Just like you'd expect. And we have one more which is the modulus operator. So here remember it is the percent equals 2. And this is going to return zero because 100 is even if we changed 100 to be 101. This is going to return one because remember the typical purpose of the modulus operator is to let you know if you're working with an event or an odd value.

large

Now with all this being said, I wanted to show you every different option that you could use the assignment operator on. But I want to say that the most common way that you're going to use this or the most common one is going to be this one right here where we're adding or subtracting. So those are going to be the two most common. And what usually you're going to use that for is when you're incrementing or decrementing values so a very common way to do this would actually be like we have our total right here. So we have a total of 100 and you could imagine it being a shopping cart and it's 100 dollars and you could say product 2 and set this equal to 120. And then if I say product 3 and set this equal to 10. And so what I could do here is I could say total plus equals product to and then we could take the value and say product 3 and now if I run this you can see the value is 230.

large

So that's a very common way whenever you want to generate a sum you can use this type of syntax which is much faster and it's also going to be a more pythonic way it's going to be the way you're going to see in standard Python programs whenever you're wanting to generate a sum and then reset and reassign the value.

So in review, that is how you can use assignment operators in Python.

devCamp does not support ancient browsers. Install a modern version for best experience.

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 operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example Try it
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3
print(x)

Advertisement

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example Try it
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example Try it
and  Returns True if both statements are true x < 5 and  x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Operator Description Example Try it
is  Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example Try it
in  Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example Try it
AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2

Operator Precedence

Operator precedence describes the order in which operations are performed.

Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated first:

Multiplication * has higher precedence than addition + , and therefor multiplications are evaluated before additions:

The precedence order is described in the table below, starting with the highest precedence at the top:

Operator Description Try it
Parentheses
Exponentiation
    Unary plus, unary minus, and bitwise NOT
      Multiplication, division, floor division, and modulus
  Addition and subtraction
  Bitwise left and right shifts
Bitwise AND
Bitwise XOR
Bitwise OR
                    Comparisons, identity, and membership operators
Logical NOT
AND
OR

If two operators have the same precedence, the expression is evaluated from left to right.

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression from left to right:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

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 operators used in python

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.

Table of Contents

Assignment operator, addition assignment operator, subtraction assignment operator, multiplication assignment operator, division assignment operator, modulus assignment operator, floor division assignment operator, exponentiation assignment operator, bitwise and assignment operator, bitwise or assignment operator, bitwise xor assignment operator , bitwise right shift assignment operator, bitwise left shift assignment operator, walrus operator, conclusion , python assignment operator: tips and tricks to learn.

Assignment Operators in Python

Assignment operators are vital in computer programming because they assign values to variables. Python stores and manipulates data with assignment operators like many other programming languages . First, let's review the fundamentals of Python assignment operators so you can understand the concept.

In Python, the following operators are often used for assignments:

Sign Type of Python Operators = Assignment Operator += Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment //= Floor division assignment **= Exponentiation assignment &= Bitwise AND assignment |= Bitwise OR assignment ^= Bitwise XOR assignment >>= Bitwise right shift assignment <<= Bitwise left shift assignment := Walrus Operator

Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations.

Python assignment operator provides a way to define assignment statements. This statement allows you to create, initialize, and update variables throughout your code, just like a software engineer . Variables are crucial in any code; assignment statements provide complete control over creating and modifying variables.

Understanding the Python assignment operator and how it is used in assignment statements can equip you with valuable tools to enhance the quality and reliability of your Python code.

In Python, the equals sign (=) is the primary assignment operator. It assigns the variable's value on the left side to the value on the right side of the operator.

Here's a sample to think about:

In this code snippet, the variable 'x' is given the value of 6. The assignment operator doesn't check for equality but assigns the value.

Become a Online Certifications Professional

  • 13 % CAGR Estimated Growth By 2026
  • 30 % Increase In Job Demand

Python Training

  • 24x7 learner assistance and support

Automation Testing Masters Program

  • Comprehensive blended learning program
  • 200 hours of Applied Learning

Here's what learners are saying regarding our programs:

Charlotte Martinez

Charlotte Martinez

This is a good course for beginners as well as experts with all the basic concepts explained clearly. It's a good starter to move to python programming for programmers as well as non- programmers

Daniel Altufaili

Daniel Altufaili

It infrastructure oprations , johnson electric.

Upon finishing the QA automation course, I received fresh assignments at my job owing to my heightened proficiency in IT, IoT, and ML. In addition to this, I earned a promotion and 20% salary increase. This course significantly expanded my expertise and motivated me to continuously enhance my skills through ongoing upskilling efforts.

The addition assignment operator (+=) adds the right-hand value to the left-hand variable.

The addition assignment operator syntax is variable += value.

The addition assignment operator increments a by 5. The console displays 14 as the result.

Also Read: Top Practical Applications of Python

The subtraction assignment operator subtracts a value from a variable and stores it in the same variable.

The subtraction assignment operator syntax is variable-=-value.

Using the multiplication assignment operator (=), multiply the value on the right by the variable's existing value on the left.

The assignment operator for multiplication has the following syntax: variable *= value

In this situation, the multiplication assignment operator multiplies the value of a by 2. The output, 10, is shown on the console.

Related Read: 16 Most Important Python Features and How to Use them

Using the division assignment operator (/=), divide the value of the left-hand variable by the value of the right-hand variable.

The assignment operator for division has the following syntax: variable /= value

Using the division assignment operator, divide a value by 3. The console displays 5.0.

Recommended Read: Why Choose Python? Discover Its Core Advantages!

The modulus assignment operator (% =) divides the left and right variable values by the modulus. The variable receives the remainder.

The modulus assignment operator syntax is variable %= value.

The modulus assignment operator divides a by 2. The console displays the following: 1.

Use "//" to divide and assign floors in one phrase. What "a//=b" means is "a=a//b". This operator cannot handle complicated numbers.

The floor division assignment operator syntax is variable == value.

The floor division assignment operator divides a by 2. The console displays 5.

The exponentiation assignment operator (=) elevates the left variable value to the right value's power.

Operator syntax for exponentiation assignment:

variable**=value

The exponentiation assignment operator raises a to 2. The console shows 9.

The bitwise AND assignment operator (&=) combines the left and right variable values using a bitwise AND operation. Results are assigned to variables.

The bitwise AND assignment operator syntax is variable &= value.

The bitwise AND assignment operator ANDes a with 2. The console displays 2 as the outcome.

The bitwise OR assignment operator (|=) bitwise ORs the left and right variable values.

The bitwise OR assignment operator syntax is variable == value.

A is ORed with 4 using the bitwise OR assignment operator. The console displays 6.

Use the bitwise XOR assignment operator (^=) to XOR the left and right values of a variable. Results are assigned to variables.

For bitwise XOR assignment, use the syntax: variable ^= value.

The bitwise XOR assignment operator XORs a with 4. The console displays 2 as the outcome.

The right shift assignment operator (>>=) shifts the variable's left value right by the number of places specified on the right.

The assignment operator for the bitwise right shift has the following syntax:

variable >>= value

The bitwise right shift assignment operator shifts 2 places to the right. The result is 1.

The variable value on the left moves left by the specified number of places on the right using the left shift assignment operator (<<=).

The bitwise left shift assignment operator syntax is variable <<= value.

When we execute a Bitwise right shift on 'a', we get 00011110, which is 30 in decimal.

Python gets new features with each update. Emily Morehouse added the walrus operator to Python 3.8's initial alpha. The most significant change in Python 3.8 is assignment expressions. The ":=" operator allows mid-expression variable assignment. This operator is called the walrus operator.

variable := expression

It was named for the operator symbol (:=), which resembled a sideways walrus' eyes and tusks.

Walrus operators simplify code authoring, which is its main benefit. Each user input was stored in a variable before being passed to the for loop to check its value or apply a condition. It is important to note that the walrus operator cannot be used alone.

With the walrus operator, you can simultaneously define a variable and return a value.

Above, we created two variables, myVar and value, with the phrase myVar = (value = 2346). The expression (value = 2346) defines the variable value using the walrus operator. It returns the value outside the parenthesis as if value = 2346 were a function. 

The variable myVar is initialized using the return value from the expression (value = 2346). 

The output shows that both variables have the same value.

Learn more about other Python operators by reading our detailed guide here .

Discover how Python assignment operators simplify and optimize programs. Python assignment operators are explained in length in this guide, along with examples, to help you understand them. Start this intriguing journey to improve your Python knowledge and programming skills with Simplilearn's Python training course .

1. What is the ":=" operator in Python?

Python's walrus operator ":" evaluates, assigns, and returns a value from a single sentence. Python 3.8 introduces it with this syntax (variable:=expression).

2. What does = mean in Python?

The most significant change in Python 3.8 is assignment expressions. The walrus operator allows mid-expression variable assignment.

3. What is def (:) Python?

The function definition in Python is (:). Functions are defined with def. A parameter or parameter(s) follows the function name. The function body begins with an indentation after the colon (:). The function body's return statement determines the value.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees

Cohort Starts:

4 Months€ 2,499

Cohort Starts:

7 months€ 1,500

Cohort Starts:

6 Months€ 1,500

Cohort Starts:

8 months€ 1,099

Recommended Reads

Python Interview Guide

Filter in Python

Understanding Python If-Else Statement

Top Job Roles in the Field of Data Science

Yield in Python: An Ultimate Tutorial on Yield Keyword in Python

The Best Tips for Learning Python

Get Affiliated Certifications with Live Class programs

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Augmented Assignment Operators in Python

An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write “ a = 5 “ to assign value 5 to variable ‘a’. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “ a = a + 7 “, we can use the augmented assignment operator and write the expression as “ a += 7 “. Here += has combined the functionality of arithmetic addition and assignment.

So, augmented assignment operators provide a short way to perform a binary operation and assigning results back to one of the operands. The way to write an augmented operator is just to write that binary operator and assignment operator together. In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes:

1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,

 a = a + b can be written as a += b

2. Subtraction and Assignment (-=): This operator combines the impact of subtraction and assignment.  

a = a – b can be written as a -= b

Example:  

3. Multiplication and Assignment (*=): This operator combines the functionality of multiplication and assignment.  

a = a * b can be written as a *= b

4. Division and Assignment (/=): This operator has the combined functionality of division and assignment.  

a = a / b can be written as a /= b

5. Floor Division and Assignment (//=): It performs the functioning of floor division and assignment.  

a = a // b can be written as a //= b

6. Modulo and Assignment (%=): This operator combines the impact of the modulo operator and assignment.  

a = a % b can be written as a %= b

7. Power and Assignment (**=): This operator is equivalent to the power and assignment operator together.  

a = a**b can be written as a **= b

8. Bitwise AND & Assignment (&=): This operator combines the impact of the bitwise AND operator and assignment operator. 

a = a & b can be written as a &= b

9. Bitwise OR and Assignment (|=): This operator combines the impact of Bitwise OR and assignment operator.  

a = a | b can be written as a |= b

10. Bitwise XOR and Assignment (^=): This augmented assignment operator combines the functionality of the bitwise XOR operator and assignment operator. 

a = a ^ b can be written as a ^= b

11. Bitwise Left Shift and Assignment (<<=): It puts together the functioning of the bitwise left shift operator and assignment operator.  

a = a << b can be written as a <<= b

12. Bitwise Right Shift and Assignment (>>=): It puts together the functioning of the bitwise right shift operator and assignment operator.  

a = a >> b can be written as a >>= b

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • 10 Best Free VPN Services in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn Python practically and Get Certified .

Popular Tutorials

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

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output

Python Operators

Python flow control.

Python if...else Statement

  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python

Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

Precedence and Associativity of Operators in Python

  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

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.

Operator Operation Example
Addition
Subtraction
Multiplication
Division
Floor Division
Modulo
Power

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.

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponent Assignment

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.

Operator Meaning Example
Is Equal To gives us
Not Equal To gives us
Greater Than gives us
Less Than gives us
Greater Than or Equal To give us
Less Than or Equal To gives us

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 .

Operator Example Meaning
a b :
only if both the operands are
a b :
if at least one of the operands is
a :
if the operand is and vice-versa.

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)

Operator Meaning Example
Bitwise AND x & y = 0 ( )
Bitwise OR x | y = 14 ( )
Bitwise NOT ~x = -11 ( )
Bitwise XOR x ^ y = 14 ( )
Bitwise right shift x >> 2 = 2 ( )
Bitwise left shift x 0010 1000)

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.

Operator Meaning Example
if the operands are identical (refer to the same object)
if the operands are not identical (do not refer to the same object)

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.

Operator Meaning Example
if value/variable is in the sequence
if value/variable is in the sequence

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

Before we wrap up, let’s put your knowledge of Python operators to the test! Can you solve the following challenge?

Write a function to split the restaurant bill among friends.

  • Take the subtotal of the bill and the number of friends as inputs.
  • Calculate the total bill by adding 20% tax to the subtotal and then divide it by the number of friends.
  • Return the amount each friend has to pay, rounded off to two decimal places.

Video: Operators in Python

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Tutorial

Guru Software

Python Operators Complete Tutorial – Logical, Arithmetic, Comparison and More

  • riazul-islam
  • September 4, 2024

Table of Contents

Python provides a rich set of operators to manipulate variables and values in your code. Mastering these operators is key to writing efficient Python scripts.

In this complete tutorial, we will cover the most important Python operators:

  • Logical operators
  • Arithmetic operators
  • Comparison operators
  • Assignment operators
  • Identity operators
  • Membership operators
  • Bitwise operators
  • Operator precedence

We will look at examples of using these operators, explain what each operator does, and discuss some common use cases. By the end, you‘ll have a solid grasp of Python operators to apply in your own code.

Logical Operators

Logical operators in Python allow you to combine conditional statements and evaluate logic in your code. The three logical operators are:

These operators evaluate to True or False based on the truthiness or falsiness of the operands.

Here‘s an example with and :

The and operator evaluates to True only if both operands are true.

Similarly, the or operator evaluates to True if either operand is true:

Finally, the not operator flips the truthiness of the operand:

With these three operators, you can build complex logical expressions and conditionals in Python.

Arithmetic Operators

Python supports common arithmetic operators for mathematical calculations:

  • + – Addition
  • - – Subtraction
  • * – Multiplication
  • / – Division
  • % – Modulus
  • ** – Exponent
  • // – Floor division

Here are some examples of using these operators:

You can perform all basic math operations using these arithmetic operators.

Comparison Operators

Comparison operators allow you to compare two values and evaluate conditions:

  • == – Equal to
  • != – Not equal to
  • > – Greater than
  • < – Less than
  • >= – Greater than or equal to
  • <= – Less than or equal to

For example:

Comparison operators output a boolean True or False depending on the comparison between the variables.

Assignment Operators

Assignment operators are used to assign values to variables in Python:

The standard assignment operator = simply assigns the value on the right to the variable on the left.

Compound assignment operators like += and -= apply the operation before assigning the result to the variable.

Some other compound assignment operators are:

  • *= – Multiplication assignment
  • /= – Division assignment
  • %= – Modulus assignment

These operators provide convenient shortcuts for assigning values in Python.

Identity Operators

Identity operators compare two objects to see if they are located in the same part of memory. The two identity operators are:

In Python, immutable objects like strings and integers with the same value share the same part of memory.

However, mutable objects like lists create a copy when setting to a new variable name.

So you need to use identity operators carefully depending on the object type.

Membership Operators

Membership operators test whether a value is present in a sequence or collection. The two membership operators are:

You can use membership operators to check if a variable matches elements of a list, tuple, string, dictionary or other collection type.

Bitwise Operators

Bitwise operators act on variables at the bit level to perform operations. In Python these are used less often than arithmetic and logical operators, but can be useful for some data science and analysis applications.

Some key bitwise operators in Python include:

  • & – Bitwise AND
  • | – Bitwise OR
  • ^ – Bitwise XOR
  • << – Bitwise left shift
  • >> – Bitwise right shift

Here is an example of using bitwise AND:

The & operator compares bits in each position, outputting a 1 only if both input bits are 1.

While bitwise operators are more niche, they enable manipulating values at the binary level which can be important for particular use cases.

Operator Precedence

Operator precedence determines the order in which Python evaluates operators when multiple operators are present in an expression.

Certain operators like exponentiation have higher precedence than addition/subtraction, which influences evaluation order.

We can override operator precedence by adding parentheses, which forces operations inside parentheses to be evaluated first.

Here is an example:

Understanding precedence can help properly structure complex expressions and ensure calculations occur as expected. The full operator precedence hierarchy in Python is:

  • Parentheses ()
  • Exponentiation **
  • Multiplication, Division, Floor division, Modulus * / // %
  • Addition, Subtraction + -
  • Comparison operators > < == !=
  • Assignment = += -=
  • Identity is is not
  • Membership in not in
  • Logical operators and or not

Operators lower in the hierarchy are evaluated first before operators higher in the hierarchy. Use parentheses whenever unsure of evaluation order or to explicitly force precedence.

We covered the main types of operators used in Python programming:

  • Logical operators combine boolean logic
  • Arithmetic operators perform mathematical calculations
  • Comparison operators enable variable comparison and evaluations
  • Assignment operators set variable values
  • Identity operators check if objects are the same
  • Membership operators evaluate collection membership
  • Bitwise operators manipulate bits and binary representations
  • Operator precedence governs the order expressions are evaluated

Mastering these operators allows writing concise and effective Python code. Pay special attention to precedence rules and when to use parentheses.

With all the major Python operators covered, you now have key knowledge to continue building your Python skills. Reference this tutorial anytime you need a quick refresher on operator usage and functions.

Read More Topics

Zookeeper architecture in-depth, getting the most from zephyr for jira: a test management guide, 8 best free zendesk alternatives for small teams in 2023, how to bypass youtube tv vpn proxy detected in 2023, introduction to youtube to wav converters, software reviews.

  • Alternative to Calendly
  • Mojoauth Review
  • Tinyemail Review
  • Radaar.io Review
  • Clickreach Review
  • Digital Ocean @$200 Credit
  • NordVPN @69%OFF
  • Bright Data @Free 7 Days
  • SOAX Proxy @$1.99 Trial
  • ScraperAPI @Get Data for AI
  • Expert Beacon
  • Security Software
  • Marketing Guides
  • Cherry Picks
  • History Tools

Lifetime Deals are a Great Way to Save money. Read Lifetime Deals Reviews, thoughts, Pros and Cons, and many more. Read Reviews of Lifetime Deals, Software, Hosting, and Tech products.

Contact:hello@ gurusoftware.com

Affiliate Disclosure:   Some of the links to products on Getorskip.com are affiliate links. It simply means that at no additional cost, we’ll earn a commission if you buy any product through our link.

© 2020 – 2024 Guru Software

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

assign operator to variable in python?

Usual method of applying mathematics to variables is

Is it able to calculate and manipulate two operands like this?

Then how do i connect op and two variables a and b ? I know I can compare op to + , - , % , $ and then assign and compute....

But can i do something like a op b , how to tell compiler that op is an operator?

  • compiler-construction

Remi Guan's user avatar

6 Answers 6

You can use the operator module and a dictionary:

bourgeoisiefrog's user avatar

  • 6 For python 3.x the operator.truediv or operator.floordiv should be used instead docs.python.org/3/library/operator.html –  joni jones Commented Feb 14, 2017 at 21:20
  • additionally, using op_func in this way doesn't work. As the edit queue on this answer is full I've fixed these errors in an answer below (assuming this answer remains ACCEPTED w/ 76 upvotes...) –  Robert Houghton Commented Dec 31, 2021 at 17:12
  • @RobertHoughton: what do you claim "doesn't work" with this answer? (I don't know what you mean by "the edit queue" either, but that's maybe just something I don't see.) –  rici Commented Dec 31, 2021 at 20:06

The operator module http://docs.python.org/library/operator.html exposes functions corresponding to practically all Python operators. You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b).

Luciano Ramalho's user avatar

I know this is a really old thread, but I believe at the time people didn't know about the eval function (Maybe it came with Python 3). So here's an updated answer to the question

If the input is not expected to be valid all the time ast.literal_eval can be used instead. It raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not. Eg. if a , b and op are respectively 5, 10, + then result is 15

Eeshaan's user avatar

  • 2 It should be expression = a + c + b . btw, using eval for user input is a bad idea. ast.literal_eval is better. –  SilentGuy Commented Oct 23, 2020 at 22:20
  • @SilentGuy you're very much right! I've updated my answer –  Eeshaan Commented Oct 24, 2020 at 3:41
  • 5 eval wasn't new to Python 3. The reason people aren't suggesting it is because it is not safe to use on user input. It can execute any Python expression (with any side effects) that someone types in. Also, literal_eval only evaluates literals. It cannot evaluate an arithmetic expression like '5+10' . –  khelwood Commented May 16, 2021 at 13:03
  • ast.literal_eval cannot do arithmetic in general, or deal with other operators. It can only handle + and - because of a quirk in the Python grammar . –  Karl Knechtel Commented May 29, 2022 at 23:57

You can use the operator module to create a dictionary. From the Python 3 documentation of that module:

"The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y."

Robert Houghton's user avatar

You'll need to compare the user's inputted string to your list of operands by hand. There is no analogue of int() here, since operators are keywords in the language and not values.

Once you've compared that input string to your list of operands and determined the operator that it corresponds to, you can use the Python standard library's operator module to calculate the result of applying the operator to your two operands.

Jordan Lewis's user avatar

  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center . –  Community Bot Commented Aug 24 at 15:10

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python compiler-construction operators or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • 70s-90s Anime Mecha Movie/Series
  • What is the first work of fiction to feature a vampire-human hybrid or dhampir vampire hunter as a protagonist?
  • Why isn't a confidence level of anything >50% "good enough"?
  • What would be a good weapon to use with size changing spell
  • Can reinforcement learning rewards be a combination of current and new state?
  • Why a minus sign is often put into the law of induction for an inductor
  • Could a lawyer agree not to take any further cases against a company?
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • What's the purpose of scanning the area before opening the portal?
  • How to go from Asia to America by ferry
  • What is the relationship between language and thought?
  • Topos notions coming from topology and uniqueness of generalizations
  • tcolorbox: title and subtitle without linebreak (detach title)
  • How to clean a female disconnect connector
  • Can the planet Neptune be seen from Earth with binoculars?
  • Generate all the free polyominoes who's width and height is no larger than 8
  • Which volcano is more hazardous? Mount Rainier or Mount Hood?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • How can I play MechWarrior 2?
  • When has the SR-71 been used for civilian purposes?
  • What is the translation of this quote by Plato?
  • Websites assume the wrong country after using a VPN
  • Circut that turns two LEDs off/on depending on switch
  • Is my magic enough to keep a person without skin alive for a month?

assignment operators used in python

IMAGES

  1. 7 Types of Python Operators that will ease your programming

    assignment operators used in python

  2. Assignment Operators In python

    assignment operators used in python

  3. PPT

    assignment operators used in python

  4. Python Operators (Arithmetic, Logical, Relational, Assignment & Bitwise)

    assignment operators used in python

  5. 7 Types of Python Operators that will ease your programming

    assignment operators used in python

  6. 7 Types of Python Operators that will ease your programming

    assignment operators used in python

VIDEO

  1. Lec 14: Assignment Operators In Python

  2. Day 10: Assignment and Compound Operators in Python Programming

  3. L-5.4 Assignment Operators

  4. Operators in Python

  5. Python Bitwise Operators බිටු අනුසාරිත මෙහෙයුම් සහ පැවරුම් කාරක Assignment Operators

  6. Become a Python Expert: Secrets and Guide of Assignment Operator

COMMENTS

  1. Assignment Operators in Python

    Assignment Operators in Python

  2. Python's Assignment Operator: Write Robust Assignments

    Python's Assignment Operator: Write Robust Assignments

  3. Python Assignment Operators

    Python Assignment Operators

  4. Python Assignment Operators

    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. Assignment. Assigning the value of 6 to num results in num being 6. Expression: num = 6. Add and assign. Adding 3 to num and assigning the result back to num would result in 9 ...

  5. The Walrus Operator: Python's Assignment Expressions

    The Walrus Operator: Python 3.8 Assignment Expressions

  6. Python

    Python - Assignment Operators

  7. Python Assignment Operators

    Introduction to Python Assignment Operators. Assignment Operators are used for assigning values to the variables. We can also say that assignment operators are used to assign values to the left-hand side operand. For example, in the below table, we are assigning a value to variable 'a', which is the left-side operand.

  8. Assignment Operators in Python

    Assignment Operators in Python are used to assign values to the variables. "=" is the fundamental Python assignment operator. They require two operands to operate upon. The left side operand is called a variable, and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=".

  9. 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 ...

  10. Python Assignment Operators

    Operator Addition (+=) Operator Subtraction (-=) Operator Multiplication (*=) Operator Division (/=) Operator Modulus (%=) Operator Exponentiation (**=) Conclusion. Python assignment operators are one of the operator types and assign values to variables. We use arithmetic operators here in combination with a variable.

  11. Operators and Expressions in Python

    Operators and Expressions in Python

  12. Different Assignment operators in Python

    Assignment operators in Python are in-fix which are used to perform operations on variables or operands and assign values to the operand on the left side of the operator. They perform arithmetic, logical, and bitwise computations. Assignment Operators in Python. Simple assignment operator in Python; Add and equal operator; Subtract and equal ...

  13. Assignment Operators in Python

    a /= b. %=. Divide AND will divide the left operand with the right operand and then assign to the left operand. a %= b. <<=. It functions bitwise left on operands and will assign value to the left operand. a <<= b. >>=. This operator will perform right shift on operands and can assign value to the left operand.

  14. How to Use Assignment Operators in Python

    So if you memorize the list of all the python operators then you're going to be able to use each one of these assignment operators quite easily. The very first thing I'm going to do is let's first make sure that we can print out the total. So right here we have a total and it's an integer that equals 100. Now if we wanted to add say 10 to 100 ...

  15. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  16. Python Operators

    Python Operators

  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. Python Assignment Operator: A Comprehensive Guide 2024!

    Python uses in-fix assignment operators to perform operations on variables or operands and assign values to the operand on the left side of the operator. It carries out calculations involving arithmetic, logical, and bitwise operations. Python assignment operator provides a way to define assignment statements.

  19. Augmented Assignment Operators in Python

    The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Operators Sign Description SyntaxAssignment Operator = Assi

  20. Python Operators (With Examples)

    Python Operators (With Examples)

  21. python

    Since Python 3.8, code can use the so-called "walrus" operator (:=), documented in PEP 572, for assignment expressions.This seems like a really substantial new feature, since it allows this form of assignment within comprehensions and lambdas.. What exactly are the syntax, semantics, and grammar specifications of assignment expressions?

  22. Python Operators Complete Tutorial

    Assignment Operators. Assignment operators are used to assign values to variables in Python: x = 5 # Basic assignment x += 3 # x = x + 3 print(x) # 8 x -= 2 # x = x - 2 print(x) # 6. The standard assignment operator = simply assigns the value on the right to the variable on the left.

  23. Conditional/ternary operator for assignments in Python?

    Conditional/ternary operator for assignments in Python?

  24. assign operator to variable in python?

    There is no analogue of int() here, since operators are keywords in the language and not values. Once you've compared that input string to your list of operands and determined the operator that it corresponds to, you can use the Python standard library's operator module to calculate the result of applying the operator to your two operands.