Unlocking Efficiency

Augmented assignment statements in python

A.I HUB
18 min readOct 9, 2024
Image By Author

Augmented assignment statements in Python are like shortcuts with a purpose, they simplify code, making it more concise and efficient. Instead of writing long, repetitive expressions, you can combine operations and assignments in a single step, boosting both readability and performance. Whether you are adding, subtracting or manipulating variables, augmented assignments make your code not only smarter but also faster to write. It’s a subtle yet powerful feature that every Python developer should master to write cleaner, more elegant code.

Table of Content

  • Expressions
  • Order of operation
  • Type conversion
  • Statements
  • Printing output
  • Getting user input
  • Complete programs

Augmented Assignment Statements

It is common to perform some mathematical binary operation on a variable
and then assign the result back to the variable. Here, are some examples.

count = count + 1
salary = salary - 1000
marks_in_maths = marks_in_maths + grace_marks
price_pencil = price_pencil // 2

In the first statement, 1 is added to the variable count and then the new
value is assigned back to the variable count. Similarly, in all the other
statements, we are performing some operations on the variable and assigning

the result back to the variable. Python supports augmented assignment
statements, which provide a shortcut for these types of expressions.

count += 1
salary -= 1000
marks_in_maths += grace_marks
price_pencil //= 2
Augmented assignment statements

Augmented assignment syntax is available for all binary arithmetic

operations.

Expressions

An expression is a combination of variables, literals, and operators, and it
always evaluates to a single value, which is again represented by an object.
Here, are some examples of expressions.

  • 45 + 6
  • 20.56 – 3 * 6
  • marks +
    50
  • 2 + 4 * 3

    (y+1) * (x-3)
  • a <= b
  • 35 marks

A single literal or a variable by itself is also considered an expression that
evaluates to itself for example, the integer literal 35 is an expression and
the variable marks is also an expression. Parentheses can be used in

expressions for enclosing some operations. We have already seen that if we
type an expression on the interactive prompt, the result of the expression is
displayed. In the program, simply writing the expression will not do
anything. We have to use the value of the expression in some way.

Evaluation of an expression generally results in the creation of a new object
so that it can be used on the right side of an assignment statement.

z = x + y * 3

Here, first, the expression x + y * 3 will be evaluated, and a new object
will be created for the result. This object will be assigned to the variable z.
So, if you want to preserve the value produced by an expression, you can
assign it to a variable. Otherwise, the value will just vanish.

Order of Operations — Operator

Precedence and Associativity

When there is only one operator in an expression, it is evaluated without any
ambiguity. For example, there is no confusion in evaluating the expression
45 + 6. However, when more than one operator appears in an expression,

then you need to determine which operator will be evaluated first. For
example, consider the expression 2 + 4 * 3. There are two ways in
which this expression can be evaluated. If an addition is done first, then the
value of this expression will be 6 * 3 which is 18, and if multiplication is
done first, then the value will be 2 + 12, which is 14. According to mathematics rules, multiplication would be done first, and 14 would be the
correct value.
In Python also, there are some rules that are followed while evaluating

expressions with multiple operators. Let us see those rules. The order of
evaluation depends on the precedence of an operator. The following table
shows the operator precedence for some common operators in Python, from
lowest to highest precedence.

Operator Precedence and Associativity

Operators in the same box have the same precedence. For example, the
operators *, /, //, % have the same precedence. To get the complete table
on your interactive prompt.

>>> help('PRECEDENCE')

Whenever an expression contains more than one operator, the operator with
a higher precedence is evaluated first. For example, in the expression 2 +
4 * 3, multiplication will be performed before addition because

multiplication has higher precedence than addition. In the expression x + y
< 10, firstly, the addition will be performed and then comparison because
the addition operator(+) has a precedence higher than that of the less than(<)
operator.

In the expression 36 / 2 * 3, division and multiplication are in the same
group, so they have the same precedence. If division is performed first, then
the value will be 54, and if multiplication is performed first, then the value

will be 6. In the expression 19 – 12 – 4 – 2, we have three subtraction

operators, which obviously have the same precedence. If we evaluate from
left to right, then the value is 19-12=7, 7-4=3, and then 3-2=1. If we
evaluate from right to left, we have 4-2=2, 12-2=10, and then 19-10=9. So, for expressions that have operators with the same precedence, the
evaluation order is still a problem. To solve these types of problems, an
associativity is assigned to each group. Associativity defines the order of

evaluation for operators that have the same precedence. In the precedence table, we can see that all the operators associate from left
to right except for the exponentiation operator, for which the precedence is
right to left. So, in the expression 36 / 2 * 3, the interpreter will first
perform division and then multiplication. The expression 19 – 12 – 4 –2 will also be evaluated from left to right, and the answer will be 1.

In the expression 2 ** 3 ** 2, we have the exponentiation operator,

which associates from right to left, therefore, firstly, 3 ** 2 will be

evaluated, which is 9 and then 2 ** 9, which is 512.
So, these were the precedence and associativity rules in Python. If you want
to override these rules and change the default evaluation order, you can use

parentheses. The operations that are enclosed within parentheses are
performed first. For example, in the expression 2 + 4 * 3, if you want to
perform addition first, you can enclose it inside parentheses. The value of the
expression (2 + 4) * 3 is 18 because addition is performed before
multiplication.

For evaluation of the expression inside parentheses, the same precedence
and associativity rules apply. For example, in the expression 39 / (5 +2 * 4), inside the parentheses, multiplication will be performed before
addition.
You can use nested parentheses in expressions, which means a pair of
parentheses can be enclosed within another pair of parentheses. In these
cases, expressions within the innermost parentheses are always evaluated

first, and then next to the innermost parentheses and so on, till the outermost
parentheses. After evaluating all expressions within parentheses, the remaining expression is evaluated as usual. For example, in the expression 5

* ((10 - 2) / 4), 10 – 2 is evaluated first, then 8 / 4 and
then 5 * 2.

PEP8 suggests adding whitespace around operators with the lowest priority.
In this expressions, the order of operations performed is clearer
due to spacing.

x + y**2 - a/b
a+b < c+d

This approach makes the code more readable. Anyone reading the code does
not need to refer to the precedence table to figure out which operation will
be performed first.

Type Conversion

You can combine different types of values in an expression. For example, 2 * 3.5 is a mixed-type expression. The two operands are of different types,
int and float. Similarly, 1.5 < x < 8 and 9 + '5' are also mixed
type expressions. Before the evaluation of such expressions, the operands

have to be converted to a common type. There can be other situations also
where you will want to convert from one type to another. For example, you
might have some numeric data in string form and you want to convert it to
int or float so that arithmetic calculations can be performed on that data.
The process of converting a value of one type to another type is called type
conversion. There are two kinds of type conversions in Python.

  • Implicit type conversion (Coercion)
  • Explicit type conversion (Casting)

Implicit type conversion is done automatically by the interpreter when
evaluating expressions of mixed types. For example, in the expression 2 *
3.5, the interpreter will convert integer 2 to the floating point equivalent
2.0 and then both float operands will be multiplied and the result will

be a float. The interpreter always promotes the smaller type to the larger
type to avoid any loss of data. It then performs the operation in larger type and returns the result in a larger type. The type int is considered "smaller"
than float and float is considered "smaller" than complex. The
implicit conversion is done only in related types, it is not performed between
unrelated types like, for example, int and str.

If we try to add a string and an int, for example, '2' + 5, Python will

not perform any conversion automatically. In this case, the programmer has
to request a conversion explicitly. Explicit type conversion is performed by

writing the required type name followed by the value to be converted inside
parentheses. For example, int(’2’) will convert the str value '2' to
int value 2 and float(28) will convert the int value 28 to float
value 28.0. Here, int()and float() are type conversion functions.
They will try to convert a value to their respective types. For example, the
int() function will take any value and try to convert it to an integer, if
possible.

>>> int(12.3)

Output

12
>>> int('100')

Output

100
>>> int(True)

Output

1
>>> int(False)

Output

0
>>> int('two')

Output

ValueError: invalid literal for int() with base 10:
'two'

When we convert a float to an int, the fractional part is truncated. When
Boolean values True and False are converted to int, we get 1 and 0
because True is equivalent to integer 1 and False is equivalent to integer
0. When we tried to convert the string value 'two' to an int, we got an
error because the int() function cannot convert a string to an integer if the

string does not represent a valid integer value.
The int() function can convert a string to an integer if the string
represents a number in hexadecimal or binary base. In this case, we have to inform the int() function about the base. In the following examples, we

are converting strings that contain hexadecimal and binary values to integer
values which are displayed in a decimal base.

>>> int('FF', 16)

Output

255
>>> int('1010', 2)

Output

10
We can use the str() function to convert a value to str type and
float() function to convert a value to float type.
>>> str(100)

Output

'100'
>>> str(3.6)

Output

'3.6'
>>> float('3.45')

Output

3.45
>>> float(3)

Output

3.0

If the string that you send to the float() function is something that cannot
be converted to a valid float, then Python will raise an error.
We know that the type of an object cannot be changed, so whenever there is
a type conversion, whether implicit or explicit, Python creates a new object
for the converted value.

Statements

A program is a sequence of statements and a statement is an instruction that
the Python interpreter can execute. Statements can be simple or compound.
Statements like a = 5, x *= 10, y = a + b are simple statements.
Compound statements (if, while, for) are a group of statements that are
treated as a single statement. They generally consist of a header line ending

in a colon and an indented block that contains other statements. We will
learn about compound statements in the coming sections.

Simple statements in Python generally end with a newline. Unlike other
languages like C++ or Java, there is no need to place a semicolon (;) to end a
statement. In Python, the end of the line means the end of the statement. So,
Python uses newline as the statement terminator. However, there are two
exceptions to this rule. If there is a backslash at the end of the line, then the

statement continues on the next line. For example, the following statement
continues on the next line because of the backslash character.

total_marks = marks_science + marks_maths \
+ marks_english + marks_socials \
+ grace_marks

So, if you have to write a statement that is too long to fit on a single line, you
can spread it on multiple lines by using backslash (\) as the continuation
character. This character at the end of the line indicates that the next line is a

continuation. This way, you can join multiple adjacent lines to construct a
single statement. This is called explicit line joining or explicit continuation.
Another situation when a statement does not end with a newline is when an

opening delimiter like parentheses, square brackets, or curly braces has not
been closed yet. In this case, Python automatically continues the statement
on the next adjacent line. This is called implicit line joining or implicit
continuation.

months = [ 
'January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November',
'December'
]
if (is_leap==TRUE and month=='MARCH'
and weekday=='SUNDAY'):
student = {
'name': 'John',
'gender': 'M',
'city': 'Paris',
'age': 21,}

Thus, any expression that is inside parentheses (), square brackets [], or curly
braces { } can be split over more than one line without using backslashes.
An exception to this is when there is an unterminated string literal enclosed
in single or double quotes.

print('Age should be less than 80 and greater than 18')

Here, the implicit line joining will not work.
You can take advantage of the implicit continuation to write more readable
code. Instead of inserting backslashes to continue the statement, it is

recommended to enclose your expression in parentheses to increase
readability.

total_marks = ( marks_science + marks_maths 
+ marks_english + marks_socials
+ grace_marks )

You can place multiple statements on a single line by separating the

statements with a semicolon. For example, the following line of code
consists of actually four statements.

a = 10; x = 5; y = a + x; z = a - y

However, this style is not recommended. Writing a single statement on each
line is preferred as it makes the code more readable and easier to understand.

Printing Output

Most computer programs interact with the user, they take some input from
the user at run time and display some sort of output on the screen. In Python,
we use the input function to get input from the console and print
function to display the output on the console. In this section, we will discuss

the print function and in the next section, we will discuss the input

function.

We have already seen how to display information on the screen by using the
print function. We have used it to print a literal, value of a variable or any
expression. Write the following statements in a .py file, execute it and
observe the output.

print('Let us start programming')
print(5 + 3*6)
name = 'Yashvaant'
age = 10
print(name)
print(age)

Output

Let us start programming
23
Yashvaant
10

The first statement prints a string literal, the second one prints the value of
an expression and the last two print the values of variables.

We can display multiple items in a single print call by separating the items
with commas. Here, are some examples.

name = 'Yashvaant'
age = 10
print(name, age)
print('Age =', age)
print('Five times six is', 5 * 6)
print('My name is', name, 'I will be an adult
after', 18 - age, 'years')

Output

Yashvaant 10
Age = 10
Five times six is 30
My name is Devank I will be an adult after 8 years

The first statement with the print function prints two variables, the second
one prints a string and a variable, the third one prints a string and an
expression and the fourth one prints a combination of strings, a variable and an expression, all separated by commas. Note that only string literals are
enclosed in quotes, while other items are written without quotes.
When we use the print function to display multiple items, all the items are
separated by a single space in the output. If we want to change this default

behavior and want the items to be separated by something else, then we can
specify a separator by adding a sep parameter at the end of the print call.
We will learn about the term parameter when we discuss functions. At this

point, you just need to know that you can write sep= followed by a string
literal that you want to be used as the separator.

day = 9
month = 11
year = 1977
print(day, month, year, sep='/')
print(day, month, year, sep='-')
print(day, month, year, sep='::')
print(day, month, year, sep='')

Output

9/11/1977
9-11-1977
9::11::1977
9111977

In the first print call, we have specified '/' for the sep parameter, so
each value in the output is separated by a '/’. Similarly, for the second
print call, each value in the output is separated by a dash, and in the third
print call, it is separated by two colons. If we do not want anything to be
printed between the values, we can specify an empty string for the sep

parameter, as we have done in the fourth print call. In this case, nothing is
printed between the values and so all the values are just joined together in
the output.

From the output of our programs, we can see that every print call ends
with a newline. This means that after printing everything, the cursor
automatically moves to the next line. Thus, the output of the next print
call starts with a fresh line. If we want the print call to end with something
else instead of a newline, we can specify the end parameter. For example,
end=’?' will end the line with a question mark.

print('Hello world', end='---')
print('Python is easy', end=' ')
print('Python is interesting!', end='')
print('Programming is fun')
print('Good Bye')

Output

Hello world---Python is easy Python is
interesting!Programming is fun
Good Bye

In the first print call, we have specified '---' for the end parameter,
so the output of this call ends with '---' instead of a newline. Similarly,
the output of the second print ends with a space because of the end
parameter. The third print has an empty string as the end parameter, so it
prints nothing at the end and the last two print calls end with the default

newline. If required, we can write both the sep and end parameters in a
single print call to specify our own custom separator and custom line ending.
This gives us more control over the format of our output.
You can write a print call with empty parentheses to insert an empty line
in the output. For example, when the following code is executed, two empty
lines will be printed between the two lines of text.

print('Let us start programming')
print()
print()
print('Python is interesting')

Output

Let us start programming
Python is interesting

There are other ways of formatting the output, which we will learn in the
next section.

Getting User Input

A program that does not take any input from the user will essentially
perform the same computations and will produce the same output every time
it is executed. Most of the time, we have to write programs that interact with
the user and behave differently depending on the user’s response. To write
such interactive programs, we should know how to get input from the user
and use it in our program.
The built-in function input() can be used to get keyboard input from the
user. When the input() function executes, the program is paused, and the
user is expected to enter some text on the screen.

print('Enter name of a city : ', end='')
city = input()
print('You entered', city)

When you execute this code, first, the message of the print call is

displayed on the screen. After this, the input function is called, this call
pauses the program and the interpreter waits for the user to enter some text.
The user types the input and ends the input by pressing the Enter key and

after this, the program execution continues. The input function returns the
entered text as a string, which means that a string object is created. To use
this string in our program, we have to assign it to a variable. In our program,
we have assigned the string to a variable named city. After this, we used

the variable city in a print function call. Here, are two sample runs of the
program.

# Sample run 1
Enter name of a city : Bangalore
You entered Bangalore
# Sample run 2
Enter name of a city : Bareilly
You entered Bareilly

The input() function captures the data entered by the user in a string and
that data can be used in the program by using the variable name.
Before asking the user to input something, we need to print a clear message
telling the user exactly what kind of data to enter. This message is called a
prompt. We have displayed this message by using the print function but

the input function is also capable of displaying the prompt. Writing a
separate print function for the prompt is not required, we can place the
prompt inside the parentheses of the input function.

city = input('Enter name of a city : ')
print('You entered', city)

This input function call first prints the prompt and then returns the text
entered by the user as a string. In our next example, we are going to enter
salary, display it and then increment by using the augmented assignment
syntax and then again display it.

salary = input('Enter salary : ')
print('Initial salary', salary)
salary += 200
print('Incremented salary', salary)
Enter salary : 1200
Initial salary 1200
Traceback (most recent call last):
File "C:\Users\test.py", line 3, in <module>
salary += 200

Output

TypeError: can only concatenate str (not "int") to str

We got a TypeError, because the input function always returns the user
input in the form of a string. We typed 1200 on the screen, and it was
returned as the string '1200’. You can check the type of variable salary by using the type function. It will show str. When we added 200 to
salary, the interpreter complained, saying that the two types are different
and it cannot perform implicit conversion. We want salary to be of
numeric type since we will have to do arithmetic calculations with it. The

type str does not support arithmetic operations, so we will perform an
explicit conversion here.

salary = int(input('Enter salary : '))
print('Initial salary', salary)
salary += 200
print('Incremented salary', salary)

We enclosed the call to the input function inside the int function, so now
the value returned by the input function is converted to int. Now, when
we run it, it gives the expected output.

Enter salary : 1200
Initial salary 1200
Incremented salary 1400

Now, if we check the type of salary, it will show int. The input function
always returns a string; it is your responsibility to convert the data returned
by input to the required type. So, when you expect a numeric input from the
user, make sure to convert the input to a numeric type using the correct

conversion function.

Complete Programs

Now we know enough basic concepts to start writing short and simple but
complete programs. We know how to get input from the user, perform some
basic calculations, and how to print and format output. So let us start writing
some programs.

  • Write a program that enters two numbers and displays their sum, product and difference.
n1 = int(input('Enter first number : '))
n2 = int(input('Enter second number : '))
print('Sum =', n1 + n2)
print('Difference =', n1 - n2)
print('Product =', n1 * n2)
  • Write a program that enters height in inches and displays it in feet and
    inches.
ht_inches = int(input('Enter the height in inches :'))
ft = ht_inches // 12
inches = ht_inches % 12
print(ft, 'feet', inches, 'inches')
  • Write a program that inputs the length and breadth of a rectangle and
    displays its area, perimeter and length of the diagonal.
length = float(input('Enter length of rectangle in cm : '))
breadth = float(input('Enter breadth of rectangle in cm : '))
area = length * breadth
perimeter = 2 * (length + breadth)
diagonal = (length*length + breadth*breadth) ** 0.5
print('Area of rectangle is ', area, 'sq cm')
print('Perimeter of rectangle is ', perimeter, 'cm')
print('Diagonal of rectangle is ', diagonal, 'cm')

Write a program that prompts the user to enter the values of principal,
interest rate and time and compute simple interest and compound interest.
Formulas for calculating simple interest and compound interest are
simple interest = (principal * rate * time) / 100
compound interest = amount – principal, where amount = principal (1 + rate
/ 100) time.

principal = float(input('Enter the principal : '))
time = int(input('Enter the time in years : '))
rate = float(input('Enter the interest rate : '))
simple_interest = (principal * time * rate) / 100
print('Simple interest is ', simple_interest)
compound_interest = principal * (1 + rate / 100) ** time - principal
print('Compound interest is ', compound_interest)
  • Write a program that prompts the user to enter a student name and marks
    in 3 subjects. Calculate the percentage marks and display the student’s name

    with the percentage.
name = input('Enter name : ')
marks_maths = int(input('Enter marks in maths : '))
marks_physics = int(input('Enter marks in physics : '))
marks_chemistry = int(input('Enter marks in chemistry : '))
total_marks = marks_maths + marks_physics + marks_chemistry
percentage = (total_marks/300) * 100
print(name, percentage)

We would suggest you type in the programs shown in the section, run them,
modify them and experiment with them in different ways. Initially, while
typing and coding, you will make mistakes that the interpreter will flag as

errors. Fixing these mistakes and getting your program to run is an integral
part of the learning process. It will help you become familiar with the syntax
and features of the language. Active engagement with code will also help
you to understand and retain the concepts and have a solid grasp of the topic.
This hands-on approach is the most effective way to learn programming.

Conclusion

Augmented assignment statements in Python provide a powerful and efficient way to simplify your code while improving readability. These operators, such as +=, -= and *=, allow you to perform operations and assignments in a single step, reducing redundancy and streamlining your logic. By using augmented assignments, you not only make your code more concise but also enhance its performance. Mastering these statements is essential for any Python developer looking to write clean, efficient and optimized programs. They might seem like small tools but their impact on your coding style can be profound.

--

--

A.I HUB

A.I HUB is a learning platform, where you can learn from all sorts of courses for free we help individuals and youngster by providing quality content.