Compound Assignment Python Found

Augmented assignment (or compound assignment) is the name given to certain assignmentoperators in certain programming languages (especially those derived from C). An augmented assignment is generally used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable. A simple example is which is expanded to . Similar constructions are often available for various binary operators.

In general, in languages offering this feature, most operators that can take a variable as one of their arguments and return a result of the same type have an augmented assignment equivalent that assigns the result back to the variable in place, including arithmetic operators, bitshift operators, and bitwise operators.

Discussion[edit]

For example, the following statement or some variation of it can be found in many programs:

x = x + 1

This means "find the number stored in the variable x, add 1 to it, and store the result of the addition in the variable x." As simple as this seems, it may have an inefficiency, in that the location of variable x has to be looked up twice if the compiler does not recognize that two parts of the expression are identical: x might be a reference to some array element or other complexity. In comparison, here is the augmented assignment version:

x += 1

With this version, there is no excuse for a compiler failing to generate code that looks up the location of variable x just once, and modifies it in place, if of course the machine code supports such a sequence. For instance, if x is a simple variable, the machine code sequence might be something like

Load x Add 1 Store x

and the same code would be generated for both forms. But if there is a special op code, it might be

MDM x,1

meaning "Modify Memory" by adding 1 to x, and a decent compiler would generate the same code for both forms. Some machine codes offer INC and DEC operations (to add or subtract one), others might allow constants other than one.

More generally, the form is

x ?= expression

where the ? stands for some operator (not always +), and there may be no special op codes to help. There is still the possibility that if x is a complicated entity the compiler will be encouraged to avoid duplication in accessing x, and of course, if x is a lengthy name, there will be less typing required. This last was the basis of the similar feature in the ALGOL compilers offered via the Burroughs B6700 systems, using the tilde symbol to stand for the variable being assigned to, so that

LongName:=x + sqrt(LongName)*7;

would become

LongName:=x + sqrt(~)*7;

and so forth. This is more general than just x:=~ + 1; Producing optimum code would remain the province of the compiler.

Semantics[edit]

In expression-oriented programming languages such as C, assignment and augmented assignment are expressions, which have a value. This allows their use in complex expressions. However, this can produce sequences of symbols that are difficult to read or understand, and worse, a mistype can easily produce a different sequence of gibberish that although accepted by the compiler does not produce desired results. In other languages, such as Python, assignment and augmented assignment are statements, not expressions, and thus cannot be used in complex expressions. For example, the following is valid C, but not valid Python:

As with assignment, in these languages augmented assignment is a form of right-associative assignment.

By language[edit]

C descendants[edit]

In C, C++, and C#, the assignment operator is =, which is augmented as follows:

OperatorDescription
Addition
Subtraction
Multiplication
Division
Modulus
Left bit shift
Right bit shift
Bitwise AND
Bitwise exclusive OR
Bitwise inclusive OR

Each of these is called a compound assignment operator in said languages.[1][2][3]

Supporting languages[edit]

The following list, though not complete or all-inclusive, lists some of the major programming languages that support augmented assignment operators.

See also[edit]

References[edit]

Introduction

Numbers are extremely common in programming. They are used to represent things like screen size dimensions, geographic locations, money and points, the amount of time that passes in a video, positions of game avatars, and colors through assigning numeric codes.

Being able to effectively perform mathematical operations in programming is an important skill to develop because of how frequently you’ll be working with numbers. Though a high-level understanding of mathematics can certainly help you become a better programmer, it is not a prerequisite. If you don’t have a background in mathematics, try to think of math as a tool to accomplish what you would like to achieve, and as a way to improve your logical thinking.

We'll be working with two of Python's most used numeric data types, integers and floats:

  • Integers are whole numbers that can be positive, negative, or 0 (…, , , , …).
  • Floats are real numbers, they contain a decimal point (as in or ).

This tutorial will go over operators that can be used with number data types in Python.

Operators

An operator is a symbol or function that indicates an operation. For example, in math the plus sign or + is the operator that indicates addition.

In Python, we will see some familiar operators that are brought over from math, but other operators we will use are specific to computer programming.

Here is a quick reference table of math-related operators in Python. We’ll be covering all of the following operations in this tutorial.

OperationWhat it returns
x + ySum of and
x - yDifference of and
-xChanged sign of
+xIdentity of
x * yProduct of and
x / yQuotient of x and y
x // yQuotient from floor division of and
x % yRemainder of
x ** y to the power

We’ll also be covering compound assignment operators, including and , that combine an arithmetic operator with the operator.

Addition and Subtraction

In Python, addition and subtraction operators perform just as they do in mathematics. In fact, you can use the Python programming language as a calculator.

Let’s look at some examples, starting with integers:

Instead of passing integers directly into the statement, we can initialize variables to stand for integer values:

Because integers can be both positive and negative numbers (and 0 too), we can add a negative number with a positive number:

Addition will behave similarly with floats:

Because we added two floats together, Python returned a float value with a decimal place.

The syntax for subtraction is the same as for addition, except you’ll change your operator from the plus sign () to the minus sign ():

Here, we subtracted an integer from a float. Python will return a float if at least one of the numbers involved in an equation is a float.

Unary Arithmetic Operations

A unary mathematical expression consists of only one component or element, and in Python the plus and minus signs can be used as a single element paired with a value to return the value’s identity (), or change the sign of the value ().

Though not commonly used, the plus sign indicates the identity of the value. We can use the plus sign with positive values:

When we use the plus sign with a negative value, it will also return the identity of that value, and in this case it would be a negative value:

With a negative value the plus sign returns the same negative value.

The minus sign, alternatively, changes the sign of a value. So, when we pass a positive value we’ll find that the minus sign before the value will return a negative value:

Alternatively, when we use the minus sign unary operator with a negative value, a positive value will be returned:

The unary arithmetic operations indicated by the plus sign and minus sign will return either the value’s identity in the case of , or the opposite sign of the value as in .

Multiplication and Division

Like addition and subtraction, multiplication and division will look very similar to how they do in mathematics. The sign we’ll use in Python for multiplication is and the sign we’ll use for division is .

Here’s an example of doing multiplication in Python with two float values:

When you divide in Python 3, your quotient will always be returned as a float, even if you use two integers:

This is one of the major changes between Python 2 and Python 3. Python 3’s approach provides a fractional answer so that when you use to divide by the quotient of will be returned. In Python 2 the quotient returned for the expression is .

Python 2’s operator performs floor division, where for the quotient the number returned is the largest integer less than or equal to . If you run the above example of with Python 2 instead of Python 3, you’ll receive as the output without the decimal place.

In Python 3, you can use to perform floor division. The expression will return the value of . Floor division is useful when you need a quotient to be in whole numbers.

Modulo

The operator is the modulo, which returns the remainder rather than the quotient after division. This is useful for finding numbers that are multiples of the same number, for example.

Let’s look at the modulo in action:

To break this down, 85 divided by 15 returns the quotient of 5 with a remainder of 10. The value is what is returned here because the modulo operator returns the remainder of a division expression.

If we use two floats with the modulo, a float value will be returned for the remainder:

In the case of 36.0 divided by 6.0, there is no remainder, so the value of is returned.

Power

The operator in Python is used to raise the number on the left to the power of the exponent of the right. That is, in the expression , 5 is being raised to the 3rd power. In mathematics, we often see this expression rendered as 5³, and what is really going on is 5 is being multiplied by itself 3 times. In Python, we would get the same result of by running either or .

Let’s look at an example with variables:

Raising the float to the power of through the operator results in a large float value returned.

Operator Precedence

In Python, as in mathematics, we need to keep in mind that operators will be evaluated in order of precedence, not from left to right or right to left.

If we look at the following expression:

We may read it left to right, but remember that multiplication will be done first, so if we call , we will receive the following value:

This is because evaluates to , and then we add to return as the final result.

If instead we would like to add the value to , then multiply that sum by , we can use parentheses just like we would in math:

One way to remember the order of operation is through the acronym PEMDAS:

OrderLetterStands for
1PParentheses
2EExponent
3MMultiplication
4DDivision
5AAddition
6SSubtraction

You may be familiar with another acronym for the order of operations, such as BEDMAS or BODMAS. Whatever acronym works best for you, try to keep it in mind when performing math operations in Python so that the results that you expect are returned.

Assignment Operators

The most common assignment operator is one you have already used: the equals sign . The assignment operator assigns the value on the right to a variable on the left. For example, assigns the value of the integer to the variable .

When programming, it is common to use compound assignment operators that perform an operation on a variable’s value and then assign the resulting new value to that variable. These compound operators combine an arithmetic operator with the operator, so for addition we’ll combine with to get the compound operator . Let’s see what that looks like:

First, we set the variable equal to the value of , then we used the compound assignment operator to add the right number to the value of the left variable and then assign the result to .

Compound assignment operators are used frequently in the case of for loops, which you’ll use when you want to repeat a process several times:

With the for loop, we were able to automate the process of the operator that multiplied the variable by the number and then assigned the result in the variable for the next iteration of the for loop.

Python has a compound assignment operator for each of the arithmetic operators discussed in this tutorial:

Compound assignment operators can be useful when things need to be incrementally increased or decreased, or when you need to automate certain processes in your program.

Conclusion

This tutorial covered many of the operators you’ll use with the integer and float numeric data types. If you would like to keep reading about numbers in Python, you can continue onto Built-in Python 3 Functions for Working with Numbers.

To learn more about other data types, take a look at Understanding Data Types in Python 3, and learn about how to convert data types by reading How To Convert Data Types in Python 3.

0 thoughts on “Compound Assignment Python Found

Leave a Reply

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