python-assignment-operators 

“`html

The Python Assignment operator is utilized to assign a value to a variable. Rather than placing the value directly in a memory location, the variable merely references the value stored in memory. Python offers augmented assignment operators, often referred to as compound operators, which enhance the efficiency of your code. The latest Python version introduced the concept of the walrus operator, enabling assignment of values to variables within an expression. In this article, you will explore all these concepts through practical examples.

Table of Contents:

What is an Assignment Statement in Python?

An assignment statement consists of a variable (the target), a value (the object), and the assignment operator (=), which connects the variable to the value. The assignment operator is one of the essential operators in Python.

The standard syntax for an assignment statement is

variable = expression

Examples:

  • name = “Alice”
  • age = 30
  • items = [10, 20, 30]
  • x = y = z = 0
  • total_cost = price * quantity + tax
  • def get_status():
    return “active”
    status = get_status()

Name Binding

In Python, variables do not represent actual containers that contain a value. Instead, they are just identifiers used to point to the container that holds the value. This implies that multiple variables can serve as references to a single value.

Example:

Python

Code Copied!

var isMobile = window.innerWidth “);

editor89774.setValue(decodedContent); // Set the default text editor89774.clearSelection();

editor89774.setOptions({ maxLines: Infinity });

function decodeHTML89774(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard89774() { const code = editor89774.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor89774 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor89774 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode89774() { var code = editor89774.getSession().getValue();

jQuery(“#runBtn89774 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “python”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output89774”).html(“

"+data+"");
            jQuery(".maineditor89774 .code-editor-output").show();
            jQuery("#runBtn89774 i.run-code").hide();
        }
    })
}

function closeoutput89774() {  
    var code = editor89774.getSession().getValue();
    jQuery(".maineditor89774 .code-editor-output").hide();
}

// Attach event listeners to the buttons
document.getElementById("copyBtn89774").addEventListener("click", copyCodeToClipboard89774);
document.getElementById("runBtn89774").addEventListener("click", runCode89774);
document.getElementById("closeoutputBtn89774").addEventListener("click", closeoutput89774);


Output:

``````html Name Binding

Clarification: In this instance, both x and y point to the identical integer object, 10.

Chained Assignment Operator in Python

Chaining an operator denotes that multiple operators can exist within the same expression. For the Assignment Operator, this allows you to designate the same value to several variables.

Instance:

Python
Code Copied!

"); jQuery(".maineditor16596 .code-editor-output").show(); jQuery("#runBtn16596 i.run-code").hide(); } }); }

function closeoutput16596() { var code = editor16596.getSession().getValue(); jQuery(".maineditor16596 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn16596").addEventListener("click", copyCodeToClipboard16596); document.getElementById("runBtn16596").addEventListener("click", runCode16596); document.getElementById("closeoutputBtn16596").addEventListener("click", closeoutput16596);

Result:

Chained Assignment Operator in Python

Clarification: Through the application of chained assignment, a, b, and c were assigned the identical value of 10.

Augmented Assignment Operators in Python

Augmented assignment operators, which are also referred to as compound operators, merge arithmetic and bitwise operators with the assignment operator. Utilizing an augmented operator permits you to evaluate the expression and simultaneously assign the result to the variable. This condenses two steps into one. It enhances code efficiency, especially with mutable objects, which are items that can be altered post-declaration.

Arithmetic Augmented Operators in Python

Python comprises seven arithmetic operators; consequently, there are seven augmented arithmetic operators. The assignment operator follows right-associativity, meaning that expressions are evaluated from right to left. Thus, calculations occur first, followed by the assignment of the result to the variable.

  • Consider x -= y as an illustration.
  • x -= y is tantamount to x = x – y.
  • Initially, x - y is computed.
  • Subsequently, the result is assigned to x.

Instance:

Python

Code Copied!

var isMobile = window.innerWidth ");

editor86083.setValue(decodedContent); // Initialize the default text editor86083.clearSelection();

editor86083.setOptions({ maxLines: Infinity });

function decodeHTML86083(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard86083() { const code = editor86083.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code successfully copied to clipboard!");

jQuery(".maineditor86083 .copymessage").show(); setTimeout(function() { jQuery(".maineditor86083 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error while copying code: ", err); }); }

function executeCode86083() {

var code = editor86083.getSession().getValue();

jQuery("#runBtn86083 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output86083").html("

"+data+"");
									jQuery(".maineditor86083 .code-editor-output").show();
									jQuery("#runBtn86083 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeOutput86083() {	
		var code = editor86083.getSession().getValue();
		jQuery(".maineditor86083 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn86083").addEventListener("click", copyCodeToClipboard86083);
    document.getElementById("runBtn86083").addEventListener("click", executeCode86083);
    document.getElementById("closeoutputBtn86083").addEventListener("click", closeOutput86083);
 
    



Output:

Arithmetic Augmented Operators in Python

Explanation: This script displays the value of x following each arithmetic augmented assignment operation. The same concept is applicable to all of them.

Below is a table featuring all the arithmetic augmented operators.

OperatorExampleEquivalentDescription
+=x += yx = x + yAdd and assign
-=x -= yx = x – ySubtract and assign
*=x *= yx = x * yMultiply and assign
/=x /= yx = x / yDivide and assign
//=x //= yx = x // yFloor Divide and assign
%=x %= yx = x % yEvaluate modulo and assign
**=x **= yx = x ** yCalculate the exponent and assign

Bitwise Augmented Operators in Python

The bitwise augmented operators function similarly to the arithmetic operators. They consider the binary values of the operands before performing calculations. It operates under the same principle and is assessed in the same way. Let’s examine an example.

Example:

Python
Code Copied!

Result:

Bitwise Augmented Operators in Python

Clarification: In this instance, the binary representations of 10, 3, and 2 are utilized to perform the operations.

OperatorSampleEquivalentDescription
&=x &= yx = x & yPerform a bitwise AND and then assign
^=x ^= yx = x ^ yExecute bitwise XOR and then assign
>>=x >>= yx = x >> yConduct Bitwise Right Shift and then assign
<<=x <<= yx = x << yExecute Bitwise Left Shift and assign

Functioning of Augmented Operators in Python

Augmented operators exhibit different behavior for mutable and immutable entities in Python. Let’s explore them individually with instances.

Assignment with Immutable Entities in Python

Immutable entities cannot be altered post-declaration. In Python, immutable types include int, bool, float, str, and tuple. If an attempt is made to modify a variable linked to an immutable entity, it will simply generate a new entity at another memory location, and the variable will now point to the new entity.

Let’s clarify the process step-by-step through an example.

Suppose we set x = 8 and then alter it to 5 via x = 5.

  • Initially, x points to the container holding the value 8.
  • When you execute x = 5, it generates a new integer value at a different memory location.
  • x then redirects itself to this new object, ‘5’, leaving the prior object, ‘8’.
  • Now, the ‘8’ entity lacks any reference. The ‘8’ entity will eventually be deleted by Python’s garbage collector.

Instance:

Python
Code Successfully Copied!

Result:

``````html Assignment with Immutable Objects in Python

Clarification: Although the action appears to alter x, it generates a new object, ‘6’, and assigns the variable x to it. The initial object ‘5’ stays intact and will eventually be removed by the garbage collector.

Assignment with Mutable Objects in Python

Mutable entities are those that can be altered post their declaration. In Python, mutable entities consist of lists, dictionaries, and sets. Augmented Operators can change the object directly. This allows it to modify the existing variable without generating a new one.

Illustration:

Python
Code Copied!

Outcome:

Assignment with Mutable Objects in Python

Clarification: As illustrated, the former object is altered without creating a new object in a different memory location.

Python Walrus Operator

This is a unique type of assignment operator introduced in Python 3.8. Walrus operators enable you to assess an expression or condition while simultaneously assigning the result using a single line of code.

The overall syntax of this operator is as below:

variable := expression

The yield of the expression is assessed and assigned to the variable. Following that, it is returned as the outcome of the entire expression.

Illustration:

Python

Code Copied!

// Code continuation... ``````html ");

editor56744.setValue(parsedContent); // Establish the default text editor56744.clearSelection();

editor56744.setOptions({ maxLines: Infinity });

function decodeHTML56744(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to replicate code to clipboard function copyCodeToClipboard56744() { const code = editor56744.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor56744 .copymessage").show(); setTimeout(function() { jQuery(".maineditor56744 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode56744() { var code = editor56744.getSession().getValue();

jQuery("#runBtn56744 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "python", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output56744").html("

"+data+"");
            jQuery(".maineditor56744 .code-editor-output").show();
            jQuery("#runBtn56744 i.run-code").hide();
        }
    });
}

function closeOutput56744() { var code = editor56744.getSession().getValue(); jQuery(".maineditor56744 .code-editor-output").hide(); }

// Attach event handlers to the buttons document.getElementById("copyBtn56744").addEventListener("click", copyCodeToClipboard56744); document.getElementById("runBtn56744").addEventListener("click", runCode56744); document.getElementById("closeoutputBtn56744").addEventListener("click", closeOutput56744);

Output:

Python Walrus Operator

Explanation:

  • In this scenario, the expression (square := n * n) computes the square of n and assigns it to the variable square. Subsequently, the condition square > 100 is evaluated on the same line, and if the condition holds true, the value of square is added to the list.
  • Without utilizing the walrus operator, the square is computed first. Then, it is compared to 100 and appended to the list if the condition is satisfied.
  • When using the walrus operator, both actions occur concurrently. The square is computed and assigned within the condition, and if it surpasses 100, it’s included in the ‘squares’ list.

Conclusion

Assignment operators serve as a core element of Python, playing an essential role in how values are stored, modified, and managed within your program. Python implements name binding rather than regarding variables as containers. Augmented assignment operators simplify operations by combining arithmetic or bitwise computations with assignment, reducing code length and often enhancing efficiency. Additionally, you were introduced to the walrus operator (:=), a sophisticated feature that facilitates assignments in expressions, eliminating redundancy and rendering conditions more expressive and compact.

To elevate your expertise, consider this Python training course to gain practical experience. Moreover, prepare for job interviews with Python interview questions curated by industry specialists.

Python Assignment Operators – FAQs

Q1. Can assignment operators be chained in Python?

Yes, you can chain assignment operators, for example, a = b = c = 5 assigns the value of 5 to all three variables.

Q2. What distinguishes = from == in Python?

The = operator is utilized to assign values to variables, while == is used to check equality between two values.

Q3. Can the += operator modify immutable types like strings?

No, += does not alter the original string but forms a new string since strings are immutable in Python.

Q4. What happens when an assignment operator is utilized on a list in Python?

When applied to a list, assignment operators like += or *= modify the list in place, as lists are mutable objects in Python.

Q5. Is it feasible to use multiple assignment operators in a single line in Python?

Yes, you can chain several assignment operators in one line (x = y = z = 10), assigning the same value to each variable.

The post Python Assignment Operators appeared first on Intellipaat Blog.

```


Leave a Reply

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

Share This