Python Tutorial

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

Python - Assignment Operators

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

Python Assignment Operator

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

Example of Assignment Operator in Python

Consider following Python statements −

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

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

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

Augmented Assignment Operators in Python

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

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

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

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

The following are the augmented assignment operators in Python:

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

Augmented Addition Operator (+=)

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

It will produce the following output −

Augmented Subtraction Operator (-=)

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

Augmented Multiplication Operator (*=)

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

Augmented Division Operator (/=)

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

Augmented Modulus Operator (%=)

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

Augmented Exponent Operator (**=)

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

Augmented Floor division Operator (//=)

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

To Continue Learning Please Login

Assignment Operators

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

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

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

Expression: num = 6

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

Expression: num += 3

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

Expression: num -= 3

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

Expression: num *= 3

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

Expression: num /= 3

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

Expression: num //= 3

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

Expression: num **= 3

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

Expression: num %= 3

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

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

Python Assignment Operators: A Beginner’s Guide with Examples

Python offers a variety of tools to manipulate and manage data. Among these are assignment operators, which enable programmers to assign values to variables in a concise and efficient manner. Whether you’re a newcomer to programming or just getting started with Python, understanding assignment operators is a fundamental step toward becoming a proficient coder. In this article, we’ll explore the basics of Python assignment operators with clear examples to help beginners grasp their usage effectively.

Table of Contents

1. What are Assignment Operators?

  • Assignment operators are symbols in Python used to assign values to variables.
  • They provide a simple and convenient way to update the value of a variable with a new one.
  • Python offers a range of assignment operators, each designed to perform a specific task while assigning values.
  • Here are some common assignment operators:
  • = (Equal Sign) : The basic assignment operator is the equal sign (` = `). It assigns the value on the right side of the operator to the variable on the left side.
  • += (Add and Assign) : This operator adds the value on the right side to the current value of the variable on the left side and then assigns the result back to the variable on the left.
  • -= (Subtract and Assign) : Similar to the ` += ` operator, this subtracts the value on the right side from the variable on the left side and assigns the result back to the variable.
  • *= (Multiply and Assign) : This multiplies the value on the right side with the variable on the left side and assigns the result back to the variable.
  • /= (Divide and Assign) : Similarly, this divides the variable on the left side by the value on the right side and assigns the result back to the variable.
  • %= (Modulus and Assign) : The modulus operator returns the remainder when the variable on the left side is divided by the value on the right side. It then assigns this remainder back to the variable on the left side.
  • Now, let’s dive into examples to better understand the usage of these assignment operators.

2. Examples of Assignment Operators.

2.1 basic assignment (=)..

  • Example. def assign_operator(): x = 10 name = "Alice" print('x = ', x) print('name = ', name) if __name__ == "__main__": assign_operator()
  • In this example, the value ` 10 ` is assigned to the variable ` x `, and the string ` “Alice” ` is assigned to the variable ` name `.

2.2 Add and Assign (+=).

  • Example. def add_and_assign_operator(): count = 5 print('count = ', count) # Output 5. count += 3 # Equivalent to count = count + 3 print('count = ', count) # Output 8. if __name__ == "__main__": add_and_assign_operator()
  • After the above code, the variable ` count ` will have a value of ` 8 `.

2.3 Subtract and Assign (-=).

  • Example. def subtract_and_assign(): total = 100 discount = 20 total -= discount # Equivalent to total = total - discount print('total = ', total) # Output total = 80. if __name__ == "__main__": subtract_and_assign()
  • Following this code, the variable ` total ` will hold a value of ` 80 `.

2.4 Multiply and Assign (*=).

  • Example. def multiply_and_assign(): quantity = 3 price = 25 total_price = quantity * price # Regular multiplication total_price *= 2 # Equivalent to total_price = total_price * 2 print('total_price =', total_price) # Output total_price = 150 if __name__ == "__main__": multiply_and_assign()
  • After these lines, the variable ` total_price ` will be ` 150 `.

2.5 Divide and Assign (/=).

  • Example. def divide_and_assign(): budget = 500 expenses = 150 remaining_budget = budget - expenses remaining_budget /= 5 # Equivalent to remaining_budget = remaining_budget / 2 print('remaining_budget =', remaining_budget) # Output: remaining_budget = 70.0 if __name__ == "__main__": divide_and_assign()
  • Following this, the variable ` remaining_budget ` will be ` 70.0 `.

2.6 Modulus and Assign (%=).

  • Example. def modulus_and_assign(): minutes = 145 hours = minutes // 60 # Integer division to get hours remaining_minutes = minutes % 60 # Modulus to get remaining minutes print('minutes =', minutes) # Output: minutes = 145 print('hours =', hours) # Output: hours = 2 print('remaining_minutes =', remaining_minutes) # Output: remaining_minutes = 25 if __name__ == "__main__": modulus_and_assign()
  • In this case, the variable ` hours ` will have a value of ` 2 `, and the variable ` remaining_minutes ` will be ` 25 `.

3. Conclusion.

  • Understanding assignment operators is crucial for any aspiring Python programmer.
  • They provide a concise way to update variables based on arithmetic or other operations.
  • By mastering assignment operators, beginners can write cleaner, more efficient code.
  • In this article, we explored the basic assignment operator ` = `, along with compound assignment operators like ` += `, ` -= `, ` *= `, ` /= `, and ` %= `.
  • Through clear examples, we’ve demonstrated how each operator works in practice.
  • Armed with this knowledge, newcomers to Python can confidently tackle programming tasks and continue their journey to becoming proficient developers.

Leave a Comment Cancel Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed .

python assignment operator example

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

python assignment operator example

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.

logo

Python Assignment Operators

In Python, an assignment operator is used to assign a value to a variable. The assignment operator is a single equals sign (=). Here is an example of using the assignment operator to assign a value to a variable:

In this example, the variable x is assigned the value 5.

There are also several compound assignment operators in Python, which are used to perform an operation and assign the result to a variable in a single step. These operators include:

  • +=: adds the right operand to the left operand and assigns the result to the left operand
  • -=: subtracts the right operand from the left operand and assigns the result to the left operand
  • *=: multiplies the left operand by the right operand and assigns the result to the left operand
  • /=: divides the left operand by the right operand and assigns the result to the left operand
  • %=: calculates the remainder of the left operand divided by the right operand and assigns the result to the left operand
  • //=: divides the left operand by the right operand and assigns the result as an integer to the left operand
  • **=: raises the left operand to the power of the right operand and assigns the result to the left operand

Here are some examples of using compound assignment operators:

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, Type Conversion and Mathematics
  • Python List
  • Python Tuple
  • Python Sets
  • 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.

Example 1: Arithmetic Operators in Python

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

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

2. Python Assignment Operators

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

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

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

Example 2: Assignment Operators

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

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

3. Python Comparison Operators

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

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

Example 3: Comparison Operators

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

4. Python Logical Operators

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

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

Example 4: Logical Operators

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

5. Python Bitwise operators

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

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

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

6. Python Special operators

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

  • Identity operators

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

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

Example 4: Identity operators in Python

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

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

  • Membership operators

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

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

Example 5: Membership operators in Python

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

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

  • Precedence and Associativity of operators in Python

Table of Contents

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

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x , y # Use (loc := (x, y)) info = name , phone , * rest # Use (info := (name, phone, *rest)) # No equivalent px , py , pz = position name , phone , email , * other_info = contact
  • Inline type annotations are not supported: # Closest equivalent is "p: Optional[int]" as a separate declaration p : Optional [ int ] = None
  • Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

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:

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

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

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.

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

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 .

Bitwise operators perform operations on binary operands.

  • 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

python assignment operator example

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

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. It performs 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 0111, which is 7 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 bit 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 bit 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 right shift operation is performed on ‘a’, we get 00011110, 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 .

About the author

Rajat Gupta is an experienced financial analyst known for his deep insights into market trends and investment strategies. He excels in providing robust financial solutions that drive growth and stability.

Related Blogs

List of Lists in Python

Methods to check if a python string contains a substring

Ancil Eric D'Silva

Convert String to List in Python

How to represent an infinite number in Python?

How to square numbers in Python?

List Index Out of Range – Python Error [Solved]

Browse Flexiple's talent pool

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

  • Programmers
  • React Native
  • Ruby on Rails

Learn Python practically and Get Certified .

Popular Tutorials

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

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

Python Operators

  • Python Namespace

Python Flow Control

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

Python Functions

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

Python Datatypes

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

Python Files

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

Python Object & Class

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

Python Advanced Topics

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

Python Date and time

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

Python Tutorials

Python Operator Overloading

Precedence and Associativity of Operators in Python

Python any()

Python Strings

  • List of Keywords in Python
  • Python all()

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

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

Learn Python with Challenges

Solve challenges and become a Python expert.

  • Types of Python Operators

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

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

1. Python Arithmetic Operators

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

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

Example 1: Arithmetic Operators in Python

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

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

2. Python Assignment Operators

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

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

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

Example 2: Assignment Operators

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

Similarly, we can use any other assignment operators according to the need.

3. Python Comparison Operators

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

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

Example 3: Comparison Operators

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

4. Python Logical Operators

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

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

Example 4: Logical Operators

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

5. Python Bitwise operators

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

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

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

6. Python Special operators

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

  • Identity operators

In Python, is and is not are used to check if two values are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

Example 4: Identity operators in Python

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. 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 presence of key, not the value.

Example 5: Membership operators in Python

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

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

Table of Contents

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

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

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:

Python Assignment Operators

Assignment operators are used to assign values to variables:

Advertisement

Python Comparison Operators

Comparison operators are used to compare two values:

Python Logical Operators

Logical operators are used to combine conditional statements:

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:

Python Membership Operators

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

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

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:

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:

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

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.

  • Python - Home
  • Python - Introduction
  • Python - Syntax
  • Python - Comments
  • Python - Variables
  • Python - Data Types
  • Python - Numbers
  • Python - Type Casting
  • Python - Operators
  • Python - Booleans
  • Python - Strings
  • Python - Lists
  • Python - Tuples
  • Python - Sets
  • Python - Dictionary
  • Python - If Else
  • Python - While Loop
  • Python - For Loop
  • Python - Continue Statement
  • Python - Break Statement
  • Python - Functions
  • Python - Lambda Function
  • Python - Scope of Variables
  • Python - Modules
  • Python - Date & Time
  • Python - Iterators
  • Python - JSON
  • Python - File Handling
  • Python - Try Except
  • Python - Arrays
  • Python - Classes/Objects
  • Python - Inheritance
  • Python - Decorators
  • Python - RegEx
  • Python - Operator Overloading
  • Python - Built-in Functions
  • Python - Keywords
  • Python - String Methods
  • Python - File Handling Methods
  • Python - List Methods
  • Python - Tuple Methods
  • Python - Set Methods
  • Python - Dictionary Methods
  • Python - Math Module
  • Python - cMath Module
  • Python - Data Structures
  • Python - Examples
  • Python - Q&A
  • Python - Interview Questions
  • Python - NumPy
  • Python - Pandas
  • Python - Matplotlib
  • Python - SciPy
  • Python - Seaborn

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Python - assignment operators example

The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • **= Exponent AND assignment operator
  • %= Modulo AND assignment operator
  • //= Floor division AND assignment operator

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial
  • School Guide
  • Class 11 Syllabus
  • Class 11 Revision Notes
  • Maths Notes Class 11
  • Physics Notes Class 11
  • Chemistry Notes Class 11
  • Biology Notes Class 11
  • NCERT Solutions Class 11 Maths
  • RD Sharma Solutions Class 11
  • Math Formulas Class 11

Augmented Assignment Operators in Python

  • Assignment Operators in Python
  • Assignment Operators In C++
  • Assignment Operators in Programming
  • Python Arithmetic Operators
  • Chaining comparison operators in Python
  • Increment and Decrement Operators in Python
  • JavaScript Assignment Operators
  • Solidity - Assignment Operators
  • Difference between == and is operator in Python
  • C++ Assignment Operator Overloading
  • Python: Operations on Numpy Arrays
  • Operator Functions in Python | Set 2
  • Operator Functions in Python | Set 1
  • Python - Alternate Elements operation on Tuple
  • Python Bitwise Operators
  • Python NOT EQUAL operator
  • Assignment Operators in C
  • Java Assignment Operators with Examples
  • Compound assignment operators in Java

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

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Operators Explained in Detail with Examples

January 9, 2024

When diving into the world of Python programming, understanding Python operators is akin to learning the alphabets of a new language. These operators act as the building blocks for any Python script, playing a critical role in carrying out operations like arithmetic calculations, comparisons, and logical decisions. Not only do they facilitate code execution, but they also make your code more efficient and readable. In this comprehensive guide, we will explore various types of Python operators, how they function, and why they are essential for anyone aspiring to master Python programming.

Different Python Operators

Here are the list of Python Operators:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Augmented Operators
  • Bitwise Operators
  • Identity Operators
  • Membership Operators

We will cover these in detail in next chapters.

1. Arithmetic operators in Python

As the name suggests, these operators perform various arithmetic operations and calculations like addition, multiplications, division, etc. They can be used with numerical data types like integers and floats, and some can even be used with strings and lists for operations like concatenation and repetition.

Below is a table that provides a detailed explanation of arithmetic operators in Python.

In each example, the variable a is used to store the result of the operation, and then print(a) is used to display the output.

2. Comparison operators in Python

Comparison operators are also known as rational operators as well. They are used to compare different values.  They evaluate different types of expressions and manipulate the values of variables by performing different operations on them.

In each code example, the variable a is used to store the result of the comparison operation, and then print(a) is used to display the Boolean output ( True or False ).

3. Logical operators in Python

Python logical operators are used to evaluate the one or more than one condition between variables or operands by providing specific results. i.e True and False . Useful for making decisions in code (conditionals) and testing multiple conditions . It can be used with any data types that can be converted to Boolean values.

In each example, the variable a is used to store the result of the logical operation, and print(a) is used to display the resulting Boolean value ( True or False ).

4. Assignment Operators

Assignment operators are primarily used to assign values to variables. They perform a single function of assigning a value from the right-hand side to the variable on the left-hand side. It is useful for initializing variables and updating their values.

Below is a table that explains the assignment operators in Python, along with code examples using a small variable name ( a ) and the print() statement to display the result.

In each example, the variable a is initially assigned a value. Then, an assignment operator modifies this value, and print(a) displays the updated value.

5. Augmented Operators (Compound Assignment Operators)

Python has a set of operators known as "augmented assignment operators," also sometimes called "compound assignment operators." These operators provide a shorthand way to apply an operation and an assignment in a single step. They are similar to assignment operators but perform an additional operation before the assignment.

Unlike normal assignment operators, Augmented Assignment Operators are used to replace those statements where a binary operator takes two operands, variable1 and variable1 and then assigns a final result back to one of the operands.

Below is a table that outlines the augmented assignment operators in Python, complete with code examples using a small variable name ( a ) and the print() function to display the result.

In each example, the variable a is initially assigned a value. Then, an augmented assignment operator modifies this value, and print(a) displays the updated value.

6. Bitwise Operators

Bitwise operators in Python are used to operate at a binary level. This means they look directly at the binary digits or binary bits of an integer. Below is a table that explains each bitwise operator in Python, along with a code example that uses a small variable name ( a ) and the print() statement to display the result.

Below are some examples to help you understand how these operators work in Python:

Bitwise AND ( & ): This operator compares each binary digit of the first operand to the corresponding binary digit of the second operand. If both digits are 1 , the digit in the resulting binary representation is 1 , otherwise 0 .

Bitwise OR ( | ):  This operator also compares each binary digit of the first operand to the corresponding binary digit of the second operand. If either of the digits is 1 , the resulting binary digit is 1 .

Bitwise XOR ( ^ ):  The XOR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1 , the corresponding result bit is set to 1 .

Bitwise NOT ( ~ ):  This operator is a unary operator, meaning it works with a single operand. Bitwise NOT will invert the number's bit-wise representation. Note that because Python uses signed integers , the result will be the two's complement of the inverted bits.

Left Shift ( << ):  The left shift operator shifts the bits of a number to the left by a specified number of positions. Each left shift doubles the number, as it is equivalent to multiplication by 2 to the power of the number of shifted positions.

Right Shift ( >> ):  The right shift operator shifts the bits of a number to the right by a specified number of positions. Each right shift halves the number, rounding down.

7. Identity Operators

Identity operators in Python are used to compare the memory locations of two objects. They help to check if two variables refer to the same object in memory. Below is a table that describes the identity operators, accompanied by Python code examples using small variable names ( a and b ) and the print() function to display the result.

Description and Use-cases

is Operator : The is operator checks whether both the operands refer to the same object (i.e., point to the same memory location). It's often used to test if a variable is None , although it can also be used for other objects like lists or dictionaries to ensure that two variables point to the same data structure.

is not Operator : The is not operator is essentially the opposite of the is operator. It checks whether two variables refer to different objects in memory. This is useful for ensuring that two variables don't share the same underlying data.

Remember, is and is not operators should not be confused with == and != operators. The former compare the memory locations, whereas the latter compare the values.

8. Membership Operators

Membership operators are used to test whether a value is a member of a sequence such as a list, tuple, or string, or a collection like a dictionary . Below is a table explaining the membership operators in Python, with code examples using small variable names ( a and b ) and the print() statement to display the result.

in Operator : The in operator is used to check if a value exists in a sequence or a collection. It's a quick way to check for the presence of a specific item.

not in Operator : The not in operator is essentially the opposite of the in operator. It checks if a specified element is not present in a given sequence or collection.

Assignment Vs Augmented Assignment Operators

The fundamental difference between assignment operators and augmented assignment operators lies in their functionality and readability.

Assignment Operators:

Basic Function : Assignment operators are mainly used to assign values to variables.

Single Operation : Assignment operators perform just one function: they assign the value on the right-hand side to the variable on the left-hand side.

Multiple Steps for Operations : If you need to perform an operation (like addition, subtraction, etc.) and then assign the result to the variable, you have to do it in multiple steps or lines.

Augmented Assignment Operators:

Enhanced Function : Augmented assignment operators perform an operation in addition to assignment, effectively combining the two into a single action.

Conciseness : They allow for more concise code. Instead of writing a = a + 2 , you can simply write a += 2 .

Efficiency : Augmented assignment operators may be more efficient in some cases, as they can reduce the amount of typing and potentially perform the operation faster, although the speed difference is generally negligible for basic types.

Multiple Operations : They make it easier to perform complex calculations and reassignments in a single step.

Operators precedence order in Python

Operator precedence in Python determines the order in which operators are evaluated when multiple operators are present in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here is a list of operators in Python , sorted from highest precedence to lowest:

  • Parentheses () : Expressions inside parentheses are evaluated first.
  • Exponentiation ** : Right-to-left associativity.
  • Complement, Unary Plus and Minus ~ + - : Unary operators.
  • Multiply, Divide, Floor Divide, and Modulus * / // % : Left-to-right associativity.
  • Addition and Subtraction + - : Left-to-right associativity.
  • Bitwise Right Shift and Left Shift >> << : Left-to-right associativity.
  • Bitwise AND & : Left-to-right associativity.
  • Bitwise XOR ^ : Left-to-right associativity.
  • Bitwise OR | : Left-to-right associativity.
  • Comparison Operators == != < <= > >= : Left-to-right associativity.
  • Identity Operators is is not : Left-to-right associativity.
  • Membership Operators in not in : Left-to-right associativity.
  • Logical NOT not : Right-to-left associativity.
  • Logical AND and : Left-to-right associativity.
  • Logical OR or : Left-to-right associativity.
  • Conditional Expression if else : Right-to-left associativity.
  • Assignment = : Right-to-left associativity.
  • Augmented Assignment += -= *= /= //= %= **= &= ^= |= <<= >>= : Right-to-left associativity.

When multiple operators have the same precedence, Python usually evaluates them from left to right (left-to-right associativity). The exception to this rule is the exponentiation operator ( ** ), which has right-to-left associativity, meaning that operations are evaluated from right to left.

For example:

  • With the expression 3 + 4 * 2 , the multiplication ( * ) operator has higher precedence than addition ( + ), so 4 * 2 is evaluated first, resulting in 3 + 8 which is 11 .
  • In the expression 2 ** 3 ** 2 , the ** operator is right associative, so 3 ** 2 is evaluated first, resulting in 2 ** 9 which is 512

Special Cases and Syntax

Python allows some operators to be used in unconventional ways. For example, you can use the * operator to repeat strings and lists.

While using operators, you should follow certain syntax rules, like putting them between operands (in infix notation), or ensuring that they are applied to compatible data types.

Chaining : Python allows you to chain multiple comparisons to perform a more complex test.

Chained comparisons also benefit from short-circuit behavior. This means that if one comparison fails, the remaining ones are not executed, which can improve performance.

Mixing Operators in Expressions: Python allows for mixing certain types of operators, but it's important to use parentheses to make the expression clear.

When mixing operators with different data types, Python will usually automatically convert the types to make them compatible, if possible.

Common Mistakes and Best Practices

Importance of parentheses.

Clarifying Ambiguity : Parentheses help in making the expression unambiguous. This is especially crucial when dealing with operators of different precedences.

Parentheses can also make complex expressions more readable, even if they're not strictly necessary.

Floating-Point Arithmetic Caveats

Precision : Floating-point numbers do not always represent decimal numbers precisely, which can lead to errors in calculations.

Integer Division : When dividing integers, use // for integer division and / for floating-point division to avoid unexpected results.

Common Pitfalls with Assignment Operators

Immutable Reassignment : Be cautious when you are working with immutable types like tuples or strings. Reassignment will produce a new object instead of modifying the original one.

Augmented Assignment : Remember that augmented assignment ( += , *= etc.) can behave differently for mutable and immutable objects.

Chaining Assignments : While Python allows for chained assignments like a = b = 1 , be cautious when using this feature with mutable objects as it can lead to unexpected behavior.

Practical Examples

How to use Arithmetic Operators in Math Calculations

Arithmetic operators come in handy for a wide range of math calculations. Here we are calculating Area and Perimeter:

Using Comparison Operators in Conditional Statements

Comparison operators are frequently used in conditional statements like if , elif , and else . Here we are determining the Largest Number:

Using Logical Operators in Decision Making

Logical operators can be used for making complex decisions. Here we are checking the eligibility for a Loan:

Real-world Scenarios where Bitwise Operators are Useful

Bitwise operators are particularly useful in low-level programming and bit manipulation:

Setting Flags

Checking Flags

How Membership and Identity Operators Work in Data Structures like Lists, Sets, and Dictionaries

Membership and identity operators are quite useful when working with data structures:

Dictionaries

Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.  Moreover, we also covered the precedence of these operators over each other.

Further Reading

Python operators Augmented operators More about python operators

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

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

Notify me via e-mail if anyone answers my comment.

python assignment operator example

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Recent Comments

Popular posts, 7 tools to detect memory leaks with examples, 100+ linux commands cheat sheet & examples, tutorial: beginners guide on linux memory management, top 15 tools to monitor disk io performance with examples, overview on different disk types and disk interface types, 6 ssh authentication methods to secure connection (sshd_config), how to check security updates list & perform linux patch management rhel 6/7/8, 8 ways to prevent brute force ssh attacks in linux (centos/rhel 7).

Privacy Policy

HTML Sitemap

Python /= Operator: Performing Division and Assignment in Python

Python /= Operator

In Python, the “/=” operator is an example of an augmented assignment operator. We use Augmented assignment operators to combine an arithmetic or bitwise operator with the assignment operator to perform that operation and then assign that operation to the result in just one step. The “/=” operator is used to perform division and assign the result to the variable. In this article, we’ll explore how to use “/=” in Python and look at some examples of how it can simplify your code.

Using Python /= to Perform Division and Assignment

The “/=” operator in Python combines the division operator with the assignment operator to divide a variable by a value and assign the result back to the variable in one step. Here’s an example:

In this example, we first set the variable x equal to the integer value 10 . We then use the “/=” operator to divide x by 2 and assign the result ( 5.0 ) back to x . Finally, we use the print() function to display the updated value of x .

Note that the result of the division operation is automatically converted to a float, even if the operands are integers.

Using Python /= to Perform Division with Floating-Point Precision

The “/=” operator is particularly useful when working with floating-point numbers, where precision is important. Using the standard division operator ( / ) with floating-point numbers can result in loss of precision, but using the “/=” operator helps to preserve the precision of the result. Let us have a look at an example:

In this example, we first set the variables a , b , and c equal to the float values 1.0 , 3.0 , and 5.0 , respectively. We then use the “/=” operator twice to divide a by b and then by c , and assign the result to a , after all this, we use the print() function, which will show the updated value of a .

Note that the result of the division operation is a float, and the precision is preserved, resulting in a more accurate result.

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Using Python /= with Lists

The “/=” operator can also be used with lists in Python. When used with a list, the operator performs element-wise division and assigns the results back to the list. Here’s an example:

In this example, we first create a list called my_list containing five integer values. We then set the variable divisor equal to 2 . We use a for loop to iterate over the elements of my_list , and we use the “/=” operator to divide each element by divisor and assign the result back to the element. Finally, we use the print() function to display the updated value of my_list .

Note that the result of the division operation is automatically converted to a float, even if the elements of the list are integers.

Using “/=” in Combination with Other Operators

We can combine the “/=” operator with other arithmetic operators to perform more complex calculations in one step. Here are some examples:

In these examples, we first perform an arithmetic operation (addition, subtraction, or multiplication) using the corresponding augmented assignment operator ( += , -= , or *= ), and then we use the “/=” operator to divide the result by a value and assign the new result back to the variable.

Using “/=” to Update Values in a Dictionary

The “/=” operator can also be used with dictionaries in Python to update the values associated with a specific key. Here’s an example:

In this example, we have created a dictionary named as my_dict having three key-value pairs. We then use the “/=” operator to divide the value associated with the key 'b' by 2 and assign the new value back to the same key in the dictionary. After that, we can use the print() function to show the contents of the updated dictionary.

Note that the value associated with the key 'b' is automatically converted to a float, even if it was originally an integer.

If you use the /= operator with a divisor of zero, Python will raise a ZeroDivisionError .

The /= operator performs division with floating-point precision and returns a floating-point value, while the //= operator performs floor division and returns an integer value.

In this article, we’ve explored how to use the “/=” operator in Python to perform division and assignment in one step. We’ve looked at several examples of how to use the operator, including division with floating-point precision, element-wise division of lists, and updating values in dictionaries. The “/=” operator is a powerful tool that can simplify your code and make it more readable by combining arithmetic or bitwise operations with the assignment operator in one step.

Trending Python Articles

[Fixed] nameerror: name Unicode is not defined

  • Python »
  • 3.14.0a0 Documentation »
  • The Python Tutorial »
  • 3. An Informal Introduction to Python
  • Theme Auto Light Dark |

3. An Informal Introduction to Python ¶

In the following examples, input and output are distinguished by the presence or absence of prompts ( >>> and … ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, # , and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.

Some examples:

3.1. Using Python as a Calculator ¶

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>> . (It shouldn’t take long.)

3.1.1. Numbers ¶

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators + , - , * and / can be used to perform arithmetic; parentheses ( () ) can be used for grouping. For example:

The integer numbers (e.g. 2 , 4 , 20 ) have type int , the ones with a fractional part (e.g. 5.0 , 1.6 ) have type float . We will see more about numeric types later in the tutorial.

Division ( / ) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use % :

With Python, it is possible to use the ** operator to calculate powers [ 1 ] :

The equal sign ( = ) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

In interactive mode, the last printed expression is assigned to the variable _ . This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

In addition to int and float , Python supports other types of numbers, such as Decimal and Fraction . Python also has built-in support for complex numbers , and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j ).

3.1.2. Text ¶

Python can manipulate text (represented by type str , so-called “strings”) as well as numbers. This includes characters “ ! ”, words “ rabbit ”, names “ Paris ”, sentences “ Got your back. ”, etc. “ Yay! :) ”. They can be enclosed in single quotes ( '...' ) or double quotes ( "..." ) with the same result [ 2 ] .

To quote a quote, we need to “escape” it, by preceding it with \ . Alternatively, we can use the other type of quotation marks:

In the Python shell, the string definition and output string can look different. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

There is one subtle aspect to raw strings: a raw string may not end in an odd number of \ characters; see the FAQ entry for more information and workarounds.

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...''' . End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

produces the following output (note that the initial newline is not included):

Strings can be concatenated (glued together) with the + operator, and repeated with * :

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

This feature is particularly useful when you want to break long strings:

This only works with two literals though, not with variables or expressions:

If you want to concatenate variables or a variable and a literal, use + :

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:

Indices may also be negative numbers, to start counting from the right:

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s :

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n , for example:

The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j , respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error:

However, out of range slice indexes are handled gracefully when used for slicing:

Python strings cannot be changed — they are immutable . Therefore, assigning to an indexed position in the string results in an error:

If you need a different string, you should create a new one:

The built-in function len() returns the length of a string:

Strings are examples of sequence types , and support the common operations supported by such types.

Strings support a large number of methods for basic transformations and searching.

String literals that have embedded expressions.

Information about string formatting with str.format() .

The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.

3.1.3. Lists ¶

Python knows a number of compound data types, used to group together other values. The most versatile is the list , which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

Like strings (and all other built-in sequence types), lists can be indexed and sliced:

Lists also support operations like concatenation:

Unlike strings, which are immutable , lists are a mutable type, i.e. it is possible to change their content:

You can also add new items at the end of the list, by using the list.append() method (we will see more about methods later):

Simple assignment in Python never copies data. When you assign a list to a variable, the variable refers to the existing list . Any changes you make to the list through one variable will be seen through all other variables that refer to it.:

All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

The built-in function len() also applies to lists:

It is possible to nest lists (create lists containing other lists), for example:

3.2. First Steps Towards Programming ¶

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

This example introduces several new features.

The first line contains a multiple assignment : the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

The while loop executes as long as the condition (here: a < 10 ) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

The body of the loop is indented : indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

Table of Contents

  • 3.1.1. Numbers
  • 3.1.2. Text
  • 3.1.3. Lists
  • 3.2. First Steps Towards Programming

Previous topic

2. Using the Python Interpreter

4. More Control Flow Tools

  • Report a Bug
  • Show Source

IMAGES

  1. Python Operators

    python assignment operator example

  2. Python Operator

    python assignment operator example

  3. Assignment operators in python

    python assignment operator example

  4. Python Operators and Expressions

    python assignment operator example

  5. PPT

    python assignment operator example

  6. Python Operators

    python assignment operator example

VIDEO

  1. Assignment

  2. Assignment Operators in python #python #operator

  3. Belajar Python with Visual Studio

  4. Python Assignment Operator #coding #assignmentoperators #phython

  5. THIS IS MY FAVOURITE OPERATOR IN PYTHON #coding #python #codingtips #programminglanguage

  6. python assignment operator

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

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

  2. Assignment Operators in Python

    The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression. Syntax: a := expression. Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop.

  3. Python Assignment Operators

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

  4. Python

    Python - Assignment Operators - The = (equal to) symbol is defined as assignment operator in Python. ... Example. 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:

  5. Python Assignment Operators

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

  6. Python Assignment Operators: A Beginner's Guide with Examples

    Python offers a variety of tools to manipulate and manage data. Among these are assignment operators, which enable programmers to assign values to variables in a concise and efficient manner. Whether you're a newcomer to programming or just getting started with Python, understanding assignment operators is a fundamental step toward becoming a proficient coder. In […]

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

  8. Python Assignment Operators

    Here is an example of using the assignment operator to assign a value to a variable: x = 5 In this example, the variable x is assigned the value 5. There are also several compound assignment operators in Python, which are used to perform an operation and assign the result to a variable in a single step. These operators include: +=: adds the ...

  9. Python Operators (With Examples)

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

  10. Python Assignment Operators

    The Python Assignment Operators are handy for assigning the values to the declared variables. Equals (=) is the most commonly used assignment operator in Python. For example: i = 10. The list of available assignment operators in Python language. Python Assignment Operators. Example. Explanation. =.

  11. PEP 572

    This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : ... Examples Examples from the Python standard library site.py. env_base is only used on these lines, putting its assignment on the if moves it as the "header" of the block.

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

  13. Python Operators

    In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. ... we have assigned the string literal 'Jessa' to a variable name. Also, there are shorthand assignment operators in Python. For example, a+=2 which is equivalent to a = a+2. Operator Meaning Equivalent = (Assign) a=5Assign ...

  14. Different Assignment operators in Python

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

  15. Python Operators (With Examples)

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

  16. Python Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator Example Same As Try it = x = 5: x = 5: ... Operator Description Example Try it; in : Returns True if a sequence with the specified value is present in the object: x in y:

  17. Assignment Operators in Python

    Now that we have this rule clear let us look at the assignment operators in Python. The assignment operators allow us to create, initialise and update the variables. The simple assignment operator "=" It is the primary assignment operator. Let's look at some examples to understand the uses of the simple assignment operator:

  18. Python assignment operators example

    The example below shows the usage of assignment and compound assignment operators: = Assignment operator. += Addition AND assignment operator. -= Subtraction AND assignment operator. *= Multiply AND assignment operator. /= Division AND assignment operator. **= Exponent AND assignment operator. %= Modulo AND assignment operator.

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

  20. Python Operators Explained in Detail with Examples

    Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.

  21. Python /= Operator: Performing Division and Assignment in Python

    The "/=" operator in Python combines the division operator with the assignment operator to divide a variable by a value and assign the result back to the variable in one step. Here's an example: 1. 2. 3. x = 10. x /= 2. print(x) # Output: 5.0. In this example, we first set the variable x equal to the integer value 10.

  22. 3. An Informal Introduction to Python

    The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to). The body of the loop is indented: indentation is Python's way of grouping statements. At the ...