Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise

Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two operands as a result.

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

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

Python includes the following categories of operators:

Arithmetic Operators

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

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

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

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

The following table lists all the arithmetic operators in Python:

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

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

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

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

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

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

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

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

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

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

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

Bitwise operators perform operations on binary operands.

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

arithmetic assignment operators in python

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

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

01 Career Opportunities

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

.

Types of Assignment Operators in Python

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

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

2. Augmented Bitwise Assignment Operators in Python

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

Augmented Arithmetic Assignment Operators in Python

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

Live Classes Schedule

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

About Author

Arithmetic operators in Python (+, -, *, /, //, %, **)

This article explains the arithmetic operators in Python.

For numbers, such as integers ( int ) and floating point numbers ( float ), you can perform basic arithmetic operations like addition, subtraction, multiplication, division, and exponentiation. For lists or strings, you can perform operations such as concatenation and repetition.

Addition: the + operator

Subtraction: the - operator, multiplication: the * operator, division: the / operator, integer division: the // operator, division remainder (mod): the % operator, exponentiation: the ** operator, zerodivisionerror, compound assignment operators, operations involving int and float, operator precedence, concatenation: the + operator, repetition: the * operator.

The asterisks * and ** are also used when defining or calling a function to unpack arguments.

  • *args and **kwargs in Python (Variable-length arguments)
  • Unpack and pass list, tuple, dict to function arguments in Python

Arithmetic Operations

The + operator performs addition.

The - operator performs subtraction.

The * operator performs multiplication.

The / operator performs division.

In Python 2, division between integers returned an integer ( int ). Since Python 3, it has returned a floating point number ( float ).

The // operator performs integer division.

If floating point numbers ( float ) are included in the calculation, the result is returned as a float even if it represents an integer value.

The % operator calculates the remainder of division.

As in the above example, floating point numbers ( float ) may introduce numerical errors. See the following article for details.

  • Check if the floating point numbers are close in Python (math.isclose)

There is also the divmod() function that returns the quotient and remainder together.

  • Get quotient and remainder with divmod() in Python

The ** operator performs exponentiation.

You can also calculate the power of floating point numbers and negative values. 0 raised to the power of 0 is defined as 1 .

Division by 0 results in a ZeroDivisionError .

For exception handling, refer to the following article.

  • Try, except, else, finally in Python (Exception handling)

The operators, such as + and - , return a new object. Note that f-strings are used here to output the value of variables.

  • How to use f-strings in Python

Operators that are combined with = sign, like += , are called compound assignment operators. The result is assigned and updated to the object on the left side.

In addition to the += operator, there are the -= , *= , /= , %= , and **= operators.

If a floating point number ( float ) is included in a calculation with the + , - , or * operators, the result is returned as a float , even if it represents an integer value.

In Python 3, the / operator returns a float even if the calculation involves integers and the result is an integer value.

The ** operator returns an int if the calculation involves integers. However, if floating point numbers or negative values are involved, the result becomes a float , even if it represents an integer value.

In Python, the operator precedence follows the same rules as in standard arithmetic.

  • 6. Expressions - Operator precedence — Python 3.11.4 documentation

The following two expressions are equivalent.

If you enclose an expression in parentheses () , that part will be calculated first. This follows the same principle as in standard arithmetic.

Operations on lists, tuples, strings

Arithmetic operators perform specific operations on non-numeric objects.

The + operator performs concatenation on lists, tuples, strings, and other similar types.

Adding incompatible types results in a TypeError . For example, if you want to add a value to a list, you must concatenate it as a list with one element.

Note that a single element tuple requires a comma , at the end.

  • A tuple with one element requires a comma in Python

The compound assignment operator += can also be used.

There are other ways to concatenate lists, tuples, and strings other than the + operator. See the following articles for details.

  • Add an item to a list in Python (append, extend, insert)
  • Concatenate strings in Python (+ operator, join, etc.)

The * operator performs repetition on lists, tuples, strings, etc.

The * operator returns the same result whether an integer is used as the left operand (as in int * list ) or the right operand (as in list * int ).

For objects other than integers ( int ), a TypeError occurs. When using negative integers with the * operator, it returns an empty list, tuple, or string.

The compound assignment operator *= can also be used.

The * operator has a higher priority than the + operator, so the * operation is processed first. Of course, you can also control the processing order with parentheses () .

Related Categories

Related articles.

  • Get the fractional and integer parts with math.modf() in Python
  • pandas: Write DataFrame to CSV with to_csv()
  • pandas: Extract rows that contain specific strings from a DataFrame
  • Set operations on multiple dictionary keys in Python
  • Complex numbers in Python
  • Get the n-largest/smallest elements from a list in Python
  • Convert a list of strings and a list of numbers to each other in Python
  • Wrap and truncate a string with textwrap in Python
  • Transpose 2D list in Python (swap rows and columns)
  • Generate gradient image with Python, NumPy
  • NumPy: Compare two arrays element-wise
  • Set operations in Python (union, intersection, symmetric difference, etc.)
  • Count elements in a list with collections.Counter in Python
  • Get image size (width, height) with Python, OpenCV, Pillow (PIL)
  • Concatenate images with Python, Pillow

Assignment Operators

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

to

to and assigns the result to

from and assigns the result to

by and assigns the result to

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

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

to the power of and assigns the result to

is divided by and assigns the result to

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

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

Expression: num = 6

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

Expression: num += 3

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

Expression: num -= 3

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

Expression: num *= 3

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

Expression: num /= 3

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

Expression: num //= 3

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

Expression: num **= 3

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

Expression: num %= 3

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

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

Python Assignment Operators

Lesson Contents

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

Let’s take a look at some examples.

Operator Assignment (=)

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

Operator Addition (+=)

We can add a number to our variable like this:

Using the above operator is the same as doing this:

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

Operator Subtraction (-=)

We can also subtract a value. For example:

Using this operator is the same as doing this:

Operator Multiplication (*=)

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

Which is similar to:

Operator Division (/=)

Let’s try the divide operator:

This is the same as:

Operator Modulus (%=)

We can also calculate the modulus. How about this:

This is the same as doing it like this:

Operator Exponentiation (**=)

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

Which is the same as doing it like this:

Operator Floor Division (//=)

The last one, floor division:

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

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

theme logo

Logical Python

Effective Python Tutorials

Python Assignment Operators

Introduction to python assignment operators.

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

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

Assignment Operators

Assignment operator.

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

Assigns value 3 to variable ‘a’.

Addition and Assignment Operator

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

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

Subtraction and Assignment Operator

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

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

Multiplication and Assignment Operator

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

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

Division and Assignment Operator

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

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

Modulus and Assignment Operator

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

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

Floor Division and Assignment Operator

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

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

Exponential and Assignment Operator

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

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

Bitwise AND and Assignment Operator

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

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

Illustration:

Numeric ValueBinary Value
2010
3011

Bitwise OR and Assignment Operator

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

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

Bitwise XOR and Assignment Operator

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

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

Bitwise Right Shift and Assignment Operator

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

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

Numeric InputBinary ValueRight shift by 1Numeric Output
2001000011
4010000102

Bitwise Left Shift and Assignment Operator

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

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

Numeric InputBitwise ValueLeft shift by 1Numeric Output
2001001004
4010010008

References:

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

PyJourney

7. Basic Python Operators: Arithmetic, Comparison, and Assignment

Diving into Python, one of the most popular programming languages today, it’s crucial to grasp the basics. Operators in Python are the building blocks for performing calculations, making decisions, and storing values. I’ll walk you through the essentials of arithmetic, comparison, and assignment operators, which are foundational for anyone looking to code in Python.

Whether you’re a beginner just starting out or a seasoned coder brushing up on the basics, understanding these operators is key to writing efficient and effective code. From adding numbers to comparing values and assigning data, I’ve got you covered. Let’s unlock the power of Python operators together and make your coding journey a breeze.

Table of Contents

Arithmetic Operators

Python’s arithmetic operators are the backbone of numerical computations in this versatile language. I’ll break them down for you, so you have a clear understanding of how each operator works and where it’s applicable.

Addition and Subtraction

The Addition ( + ) and Subtraction ( - ) operators are straightforward. You’ll use them for adding or subtracting two numbers:

Subtraction

Multiplication and division.

For Multiplication ( * ) and Division ( / ), Python obeys the typical order of operations to ensure accurate results:

Multiplication

Remember, division always produces a float, even if you’re dividing two integers.

Modulus and Exponentiation

Moving on, the Modulus ( % ) operator finds the remainder after division of one number by another. It’s particularly useful in algorithms that require you to determine if a number is even or odd. Meanwhile, the Exponentiation ( ** ) operator raises one number, the base, to the power of another, the exponent:

Exponentiation

Floor division.

Lastly, Floor Division ( // ) divides and rounds down to the nearest whole number:

Mastering these operations is a must for any task that requires mathematical calculations. Whether you’re building financial models or creating games, arithmetic operators are your fundamental tools. Next, let’s move on to another set of operators that are as critical as arithmetic ones: comparison operators. This will help you make decisions in your code based on the data at hand.

When diving into Python, one of the fundamental tools in your programmer’s kit is the addition operator. Simple to use, it’s represented by the + sign and performs exactly what you’d expect—adds together two values. In practice, here’s how it plays out:

Adding integers

Adding floats.

This operator doesn’t just handle numerical data types like integers and floats, it can also concatenate strings and lists, making it extremely versatile:

Concatenating strings

Combining lists.

Furthermore, the addition operator can be used in an augmented assignment format to both add and assign a value to a variable in one expression:

Augmented assignment

It’s important to note that while addition in Python is fairly straightforward, it’s essential to consider the data type of the items you’re working with to avoid errors. For instance, trying to add together a string and an integer will result in a TypeError, as Python expects homogeneity in addition operations.

As you become more skilled with Python, you’ll find that the addition operator is not just about arithmetic. It’s a powerful tool that allows you to accumulate values, construct strings, merge data structures, and much more. Whether you’re calculating sums or constructing complex data payloads, the addition operator remains a reliable ally in your coding endeavors.

Just as the addition operator plays a crucial role in Python, the subtraction operator is equally fundamental for performing arithmetic calculations. Signified by a minus sign ( - ), subtraction in Python allows you to calculate the difference between numbers, and just like addition, can also be used with various data types.

When working with integers and floats , the subtraction operator operates as expected. If I write 10 - 5 , the output will naturally be 5 . However, subtracting a float from an integer, or vice versa, will result in a float: 7 - 2.0 yields 5.0 . It’s simple arithmetic but forms the basis for many complex operations in Python programming.

Interestingly, in the realm of strings and lists, Python does not directly support the subtraction operator. Trying to subtract one string from another, or one list from another, results in a TypeError . This is because the concept of subtraction doesn’t naturally extend to these data types in the same intuitive way as it does for numbers. However, developers often work around this limitation by using other methods to achieve similar outcomes, such as string methods or list comprehension.

Augmented assignment with subtraction is also available in Python. Using -= allows for a value to be subtracted from a variable and the result assigned back to that variable in a single, concise step. For example, I can write x -= 2 and whatever value x held would be decremented by 2 .

Remember, while Python’s subtraction operator might seem straightforward, its application is broad, acting as one of the pillars of mathematical operations in coding. From calculating simple differences to adjusting values on the fly, subtraction is vital for data manipulation and needs to be understood in depth by any aspiring Python programmer.

When it comes to programming in Python, the multiplication operator is as fundamental as it gets. Denoted by the asterisk (*), this operator allows for the product of two numbers, be they integers or floats. Here’s a quick example: if I write 3 * 4 , Python outputs 12 . This same principle applies to floats: 2.5 * 4.0 returns 10.0 .

But multiplication isn’t limited to numbers alone. Python’s flexibility shines when the multiplication operator is applied to strings. For instance, 'Python!' * 3 gives us 'Python!Python!Python!' , repeating the string thrice. It’s important to remember, this operation doesn’t combine separate strings — it repeats the same string multiple times.

Lists see similar benefits. Multiplying a list by an integer repeats the list’s contents. Therefore, [1, 2, 3] * 2 transforms into [1, 2, 3, 1, 2, 3] . This can be particularly useful when initializing a list with a fixed number of identical elements without manually typing them out.

I should point out that Python enforces type consistency when using the multiplication operator. Attempts to multiply incompatible types, like a string by a list, will result in a TypeError . This ensures that you’re aware of the data types you’re working with and helps maintain clean code.

Moreover, Python supports multiplications using external libraries like NumPy, which offer advanced features for array multiplications. In these scenarios, the multiplication operator can perform operations like matrix multiplications and dot products, taking Python’s capabilities well beyond basic arithmetic.

Using multiplication operator with caution is recommended, particularly when applying it to lists, since it could potentially lead to memory issues. Large list operations can consume significant amounts of memory and slow down performance, especially if you’re repeating a substantial list. Hence, always assess the impact on your code’s efficiency and memory usage before running such operations.

When we dive into the world of Python arithmetic, the division operator emerges as a crucial tool for numerical calculations. Python uses the forward slash (/) for division, providing a straightforward way to divide numbers. This operator can handle both integers and floats with ease. Here’s a quick example: if I write 10 / 5 , Python will give me 2.0 . Notice how the result is a float, not an integer. This is because Python automatically converts integer division results into float for more precision.

But what if you’re interested in integer division? That’s where the floor division operator (//) steps in. If I want to divide 10 by 3 and get an integer result without any decimal places, I’d use 10 // 3 , which yields 3 . It effectively rounds down the result to the nearest whole number. It’s paramount to mention that if there’s a negative number involved, floor division will round towards the negative of infinity. This behavior ensures consistency across different arithmetic operations.

Perhaps less commonly discussed but equally important is the modulus operator (%) , which gives us the remainder of a division operation. If I want to know what’s left over when 10 is divided by 3 , 10 % 3 would return 1 .

Knowing how to handle division in Python is particularly vital in data analysis and scientific computations, where precision and the type of division are key. It’s also important to highlight that Python will raise a ZeroDivisionError if you attempt to divide by zero. Hence, checks for zero are critical before performing division operations to prevent runtime errors.

One might also incorporate libraries like NumPy when dealing with arrays or matrices as these can offer more sophisticated functions and handle division in a way that’s optimized for large datasets. The flexibility of these libraries in handling various numerical operations complements the built-in Python division capabilities.

Remember, just like multiplication, division must be approached with an understanding of the data type involved to avoid type inconsistency errors. By keeping these intricacies in mind, you’ll be able to write more efficient and error-free code.

When I delve into Python’s arithmetic operations, the modulo operator often stands out. Represented by the % symbol, the modulo provides the remainder of a division operation rather than the quotient. It’s especially handy in various programming scenarios, such as determining odd or even numbers or iterating over a sequence with wrap-around.

Understanding the Modulo Operator

To use the modulo operator:

Where dividend is the number you’re dividing and divisor is the number by which you’re dividing. For example, 10 % 3 would return 1 because when dividing 10 by 3, the remainder is 1.

Key Uses of Modulo in Python

  • Looping Techniques : When you need to cycle through a list repeatedly, modulo helps to reset the index.
  • Even: if number % 2 == 0
  • Odd: if number % 2 != 0
  • Time Calculations : Modulo is perfect for converting seconds to minutes and hours, ensuring values stay within calendar bounds.

Unlike division operators, the modulo is less prone to runtime errors like ZeroDivisionError , but you still can’t use zero as a divisor. If attempted, Python will raise a ZeroDivisionError , similar to using the division operator.

Integrating modulo requires mindfulness about operand types — a common theme in Python arithmetic. The result of a modulo operation involving floats can be counterintuitive because we’re often taught to think of remainders in the context of integers.

In cases involving negative values:

The operation considers the sign of the divisor, resulting in 2 , because Python’s modulo returns the remainder closest to zero.

For advanced scenarios, external packages might offer specialized functions. NumPy, for instance, provides a variation of the modulo operator that behaves differently with negative values. Choosing the right tool for each job is critical in programming for efficiency and accuracy.

Whenever I’m faced with a problem requiring the determination of a quotient’s remainder, I make sure the modulo operator is top of mind. It’s a small but mighty tool in Python’s operator arsenal and can be the difference between a good and a great solution. With this knowledge, I can navigate numbers with precision and employ effective strategies for commonly faced challenges in programming.

When diving into Python’s arithmetic operators, we quickly come across the power operator , ** , which is used for exponentiation. This operator raises a number to the power of another, making it an invaluable tool when working with powers and roots in Python.

Let’s take a look at how it’s used:

Raising 2 to the power of 3

In this example, 2 is the base and 3 is the exponent. Python beautifully simplifies what could otherwise be a complex mathematical process into a single line of code.

Understanding the rules and behavior of exponentiation in Python is crucial, especially when dealing with large numbers or when performing precision computing. Here are some key points:

  • Positive exponents : The base is multiplied by itself as many times as the value of the exponent.
  • Negative exponents : Python will return the reciprocal of the base raised to the absolute value of the exponent.
  • Zero exponent : Any base raised to the power of zero will always be 1.

The ** operator isn’t just limited to integers. It can also be used with floats to handle scenarios requiring fractional exponents, which is common in scientific computations:

Square root of 9

Remember though, float operations might introduce rounding errors due to the nature of binary representation in computing. It’s always good practice to be aware of this when expecting precise results.

For more complex mathematical operations that go beyond what Python’s built-in functions offer, you might want to look into modules like math or numpy . These libraries have optimized functions for exponentiation and other intricate mathematical computations that ensure accuracy and efficiency.

As we continue to explore operators, it’s essential to practice using them in real-world problems that require exponentiation. There are countless applications, from calculating compound interest to transforming datasets in data science projects. Empowering yourself with the power operator opens up a universe of possibilities in Python programming.

When working with division in Python, you’ll inevitably come across the Floor Division operator, denoted by a double forward slash // . Unlike the standard division operator / that returns a floating-point result, floor division rounds down the result to the nearest whole number.

Let’s take a deeper dive into why floor division is crucial for certain calculations. One of the primary uses of floor division is to get an integer quotient from the division of two numbers. For instance, if you’re dividing 7 by 2 using the standard division operator, the result would be 3.5. However, with floor division, the result is simply 3 .

Here are a few scenarios where floor division is particularly handy:

  • Allocating resources evenly and determining leftovers
  • Working with time calculations , where decimal parts don’t make sense
  • Processing images or graphics by ensuring pixel counts remain whole numbers

Consider this code snippet for a better understanding:

It’s important to note that when dealing with negative numbers, floor division can have surprising results. For example:

Although -11 / 3 would typically yield approximately -3.6667, floor division will round this down to -4 . This behavior keeps the floor division consistent, always rounding towards minus infinity, which can be essential for maintaining predictable results in your code.

Using floor division in Python is an easy way to keep your calculations integer-based when needed. Integrating this operator into your toolbox can save time and additional steps, especially when working with loops or array indices where non-integer values could cause errors. Remember to test your code with a variety of inputs to understand how floor division operates across different scenarios.

Comparison Operators

When coding in Python, Comparison Operators are the bread and butter for making decisions. These operators allow me to compare two values and, based on the comparison, return a Boolean value of either True or False .

The Common Comparison Operators Are:

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

These operators are fundamental for control flow, enabling functions like if statements and while loops to make logical decisions. For example, I’ll compare user input to a set value to determine the next steps in a program.

Practical Uses of Comparison Operators

In real-world scenarios, I find comparison operators particularly useful when sorting items, validating user input , or implementing algorithms that require condition checking. They’re also crucial while filtering data , such as when I need to extract specific information from large datasets.

Avoiding Common Pitfalls

A common mistake I can make when using comparison operators is confusing the ‘equal to’ operator == with the assignment operator = . It’s vital to ensure that I’m using the correct operator to avoid unexpected behavior in my code. Another issue to watch out for is the mix-up between is and == . While is checks if two variables point to the same object, == evaluates if the values they hold are the same. This distinction is significant when working with mutable objects like lists.

Mastery Through Practice

The more I work with comparison operators, the more intuitive they become. I often incorporate various comparison operations in my practice exercises to get a solid grasp of each operator’s nuances. By combining comparison operators with logical ones like and , or , and not , I can craft complex conditions that can handle multifaceted scenarios in my programs.

Understanding the ‘equal to’ operator in Python is crucial for carrying out effective comparisons. The operator is denoted by two equal signs (==) and is used to determine whether two values are identical. When it comes to programming logic, this operator plays a pivotal role.

Consider a situation where I need to validate user input . I’d use the ‘equal to’ operator to compare the input with a predefined correct answer. If the user’s answer matches the correct answer, the operation evaluates to True .

Here’s a simple code snippet to illustrate its use:

In the code above, if the user_input matches secret_code , the message “Access Granted!” is displayed. Otherwise, the user sees “Access Denied!”

It’s also vital to remember that the ‘equal to’ operator checks for value equality, not identity. Object identity, or whether two variables point to the same object in memory, is checked using the is operator .

Here’s how you shouldn’t confuse ‘equal to’ with the assignment operator:

  • Assignment operator ( = ): Assigns a value to a variable.
  • Equal to operator ( == ): Compares two values for equality.

Moreover, when working with floating-point numbers, programmers need to be cautious of precision issues . Due to the way computers represent floating-point numbers, two values that seem identical may not be considered equal. Always validate such comparisons within a tolerance level or use the math.isclose() function for comparing floating-point numbers.

Using the ‘equal to’ operator effectively requires a firm grasp of the types of data being compared. Always ensure the operands are comparable and understand how Python treats different data types during comparison. For instance, comparing a string with an integer using ‘equal to’ will result in False because their data types are different.

In my next section, I’ll delve into another comparison operator that is often used side by side with ‘equal to’: the ‘not equal to’ operator.

Not Equal To

While the ‘equal to’ operator checks for similarity, the ‘not equal to’ operator serves the opposite function. Represented by an exclamation point followed by an equal sign (!=) , it determines if two values are different. I often use this operator when I need to execute a block of code only if a certain condition is not met. For instance, when dealing with user input, it’s crucial to ensure the input doesn’t match something specific, like a forbidden password or username.

Here’s a simple scenario:

In this example, the != operator saves the day by preventing users from choosing a restricted username. This safeguard is as vital as allowing correct inputs, especially when considering security implications.

Handling Data Types is another area where the ‘not equal to’ operator comes into play. Since Python is dynamically typed, you don’t always know what data types you’ll receive. So, checking for inequality also requires an understanding of how Python compares different data types. When Python compares an integer and a floating-point number, even if their mathematical values are the same, the != operator will consider the different types and may not behave as expected.

It’s especially important to Test Thoroughly when working with != . Situations involving collections like lists and dictionaries might not be straightforward, as the operator checks for inequality between all elements, potentially leading to confusion if not used correctly. Consider how Python treats different container types:

  • Lists: Element by element comparison
  • Dictionaries: Pair by pair (key and value) comparison

When you master the ‘not equal to’ operator, you enhance your error handling and control flow capabilities dramatically. This improvement leads to more robust and reliable code.

Greater Than

In the universe of Python’s comparison operators, the Greater than symbol > stands tall. It’s straightforward yet potent, enabling me to compare two values and determine if one is larger than the other. This operator is commonly used in control structures like if statements and loops, where decisions hinge on numerical comparisons.

When I apply the > operator, Python does what you’d expect – it checks to see if the value on the left is indeed greater than the value on the right. For instance, if I’ve got two variables, age1 set to 30 and age2 set to 25, writing age1 > age2 would yield True because 30 is, in fact, greater than 25. But the practical applications go far beyond just comparing simple integers.

Imagine working on a piece of code where I need to filter a list of items based on their prices. I’ll loop through each item and use the > operator to select only those whose price exceeds a certain threshold. This kind of operation is crucial in tasks like data analysis, where I’m often sieving through vast quantities of data to find significant figures.

  • Syntax: value1 > value2
  • Returns: True if value1 is greater than value2 , otherwise False

It’s also important to be aware of how Python handles comparisons between different data types. For example, comparing an integer to a float works seamlessly since Python knows how to interpret these kinds. However, using the > operator between incompatible types, such as an integer and a string, throws a TypeError. Intuitively, it’s comparing apples to oranges, which Python wisely refrains from.

In complex structures like dictionaries, I need to be more careful. Since dictionaries can hold various data types as values, ensuring I’m comparing items of the same type is imperative. Oftentimes, I’d have to iterate over the dictionary’s values and, based on context, apply the > operator to the elements that I can fairly compare.

Leveraging the > operator intelligently can propel condition-based logic to work precisely as I intend. It’s a cornerstone in building robust Python scripts that respond dynamically to varying data.

Just as crucial as the ‘greater than’ operator, the ‘less than’ operator in Python is denoted by the symbol < . This operator assesses whether the left-hand operand is smaller than the right-hand operand. It returns a boolean value – True if the assertion is correct and False otherwise.

Useful in various programming scenarios , the ‘less than’ operator is fundamental when sorting algorithms are in play or when we need to impose a threshold. Here are some common applications:

  • Imposing limits within loops
  • Conditional expressions in if statements
  • Filtering data during analysis

I use the ‘less than’ operator with numbers predominantly, but it’s versatile with other compatible types in Python, such as strings which are compared based on their alphabetical order.

When comparing strings with numbers , however, Python will raise a TypeError . It’s vital to ensure compatibility between the data types to prevent any unintended errors in the code. Keep in mind that specific comparisons involving complex data structures might require casting or additional checks for a smooth experience.

Up next, I’ll tackle the versatile yet simple assignment operators. Thriving in simplicity, these operators play a pivotal role in almost every aspect of a Python script. From variables initialization to the reassignment of values, assignment operators maintain state and control flow within a program, proving their indispensability in the realm of Python coding.

Greater Than or Equal To

When I’m programming in Python, the ‘greater than or equal to’ operator (>=) is equally essential as its counterpart. It’s used to compare two values, checking not only if one value is greater than the other but also if they’re equal. This operator is particularly useful when setting boundary conditions or ranges within my code.

Let’s explore its application with a real-world example . Imagine I’m writing a program that determines if a user is eligible for a senior discount. The eligibility age is 65 or older.

Here, I’m using the >= operator to check if the age entered is 65 or more. If the condition is true, the message ‘Eligible for discount’ is printed.

Moving beyond simple comparisons, the ‘greater than or equal to’ operator is vital in loop structures . For instance, consider processing a list of scores to determine how many are above a certain threshold:

print(f”Scores above threshold: {above_threshold}”)

In this snippet, each score is checked against the threshold, and the counter increases for each score that meets the condition.

Just as with the ‘less than’ operator, ensuring data type compatibility is crucial. Remember, comparing a string and an integer with >= could lead to errors. To maintain the integrity of my programs I ensure the variables in comparison are of the same or coercible types. This prevents unexpected behavior and promotes reliable code execution.

Like the threads of a tapestry, these operators interweave to form the logic of our Python script, making them indispensable tools in my arsenal for crafting efficient and effective code.

As I familiarize myself with these operators I find my scripts growing not only more sophisticated but also more robust. Stepping through each one, the journey through Python’s basic operators continues to unfold, revealing the simplicity and power of the language.

Less Than or Equal To

Just as important as the ‘greater than or equal to’ operator in Python is the ‘less than or equal to’ operator. This operator is denoted by <= and serves a critical role in programming—especially when you need to evaluate whether a value falls below or exactly at a certain threshold. For example, when managing inventory, confirming that stock levels are sufficient before processing a sale is essential. Here’s how it’s used:

In this snippet, Python checks if the order_quantity is less than or equal to stock . If the order quantity is 10 or less, the condition is true, and we proceed to process the order.

Understanding <= in Different Contexts

The <= operator isn’t limited to simple numerical comparisons—it’s also effective in other contexts:

  • String Comparison : Strings are compared lexicographically in Python, so you can check if one precedes another alphabetically.
  • Date Comparison : When working with date objects, <= ensures that an event occurs before or on a certain date.

Practical Applications of <=

I’ve observed that the use of <= spans a variety of applications:

  • Setting thresholds in game development to trigger an event
  • Validating user input to ensure it doesn’t exceed a limit
  • Analyzing datasets to filter entries based on a condition

It’s crucial to remember that the data types on either side of the <= must be compatible to avoid a TypeError .

Applying the ‘less than or equal to’ operator within loops and conditional statements allows for more complex decision-making processes:

This loop will only print numbers that are 5 or less, demonstrating how <= can control the flow of a program. As you can see, employing <= alongside other Python operators enhances the control and precision we have over our code. With this understanding, you’ll be able to craft more intricate and reliable Python programs that handle a multitude of scenarios effectively.

Assignment Operators

Assignment operators in Python are the foundation of variable management and data storage. These operators are used to assign values to variables . The most common assignment operator is the = sign, which might seem straightforward but is the workhorse of just about any Python program. For instance, when I create a variable to keep track of a score in a game, I use the = to set its initial value: score = 0 .

Beyond the basic assignment, Python also provides a suite of compound assignment operators that combine arithmetic operations with assignment. These are incredibly handy for modifying variable values efficiently. They not only make code cleaner and easier to read but often reduce the chance of typing errors in the process. Here are the main ones I frequently utilize:

  • += for adding and assignment: counter += 1 increments the counter by one.
  • -= for subtraction and assignment: health -= damage subtracts damage from health.
  • *= for multiplication and assignment: price *= discount applies a discount to the price.
  • /= for division and assignment: total /= num_items calculates the average price per item.

In Python, these operators do more than just reduce the amount of typing. For example, they can streamline loop operations or increment counters within a loop without having to write out the full assignment. This can make a significant difference in the readability and performance of the code. Let’s say I’m processing a list of numbers to get a total:

Here, the += operator is effortlessly increasing the total with each iteration. Additionally, in scenarios where I’m working with mutable data types like lists, these operators allow for the modification of data in place, which can lead to more memory-efficient code .

Moreover, Python’s assignment operators support chaining , which brings another layer of elegance to variable management. For example, I can initialize multiple variables at once: x = y = z = 0 . It’s also worth noting that Python 3.8 introduced the walrus operator := , which assigns values within an expression, further expanding the realms of assignment possibilities.

Simple Assignment

In mastering Python, Simple assignment is an essential tool in your programming arsenal. It’s the most straightforward form of assigning a value to a variable. You’ve already seen the = operator in action, which serves as the backbone for variable creation and manipulation in the language.

When I use simple assignment, I follow the basic syntax where the variable name comes first, followed by the = sign, and then the value I wish to assign. Here’s an easy-to-understand example:

In this case, my_variable now holds the value 10 . It’s a clear, concise method that underpins virtually every Python program I write. Additionally, Python allows for multiple assignments in a single line, further simplifying the code:

Here, x , y , and z are assigned to 1 , 2 , and 3 , respectively. It’s a handy shortcut that I often use to initialize several variables at once.

But simple assignment isn’t just about initializing; it’s also used for reassigning values . If I decide that my_variable needs a new value, a simple reassignment does the trick:

my_variable holds 30 instead of 10 . It’s crucial to remember that in Python, variables are just labels pointing to objects, and reassignment doesn’t affect the object originally referenced; it merely attaches the label to a new object.

Furthermore, Python uses dynamic typing , which means that I don’t need to declare the data type of a variable beforehand. This contrasts with statically-typed languages, in which variable types must be explicitly stated. Dynamic typing allows for more flexibility and quicker coding—Python figures out the data type on its own:

Initially, dynamic_var starts as an integer with any numerically assigned value but can just as quickly be reassigned to hold a string. This flexibility is one of Python’s strengths, making it an excellent choice for rapid development and iterative coding processes.

Addition Assignment

Shifting gears from simple assignment, let’s delve into addition assignment. In Python, the += operator does more than just add two numbers together; it’s used to add a value to a variable, updating the variable itself in the process. If I have a variable x and I want to increase its value by 10, I’d simply write x += 10 . This is equivalent to x = x + 10 but far more succinct.

What makes addition assignment invaluable is its ability to streamline code. Think about running totals or iterative updates in a loop – that’s where += shines. It’s not just beneficial for numbers; I’ve frequently used addition assignment with strings to concatenate additional text.

Here’s a quick glimpse:

This code snippet would output Hello, World! , demonstrating how += appends text to an existing string.

Common use cases for addition assignment in practical coding scenarios include:

  • Accumulating values in counters or sums
  • Updating the value of a variable in response to events
  • Concatenating strings or lists over multiple iterations

It’s important to note that addition assignment is part of a broader category of compound assignment operators . These operators include others like subtraction assignment ( -= ), multiplication assignment ( *= ), and division assignment ( /= ), each performing a similar update-in-place for their respective operations.

One aspect of addition assignment that’s often overlooked is its atomicity in single-threaded scenarios. When I use x += 1 , it’s a near-guarantee that x will be incremented by exactly one without the risk of interference from other operations, making it safer in certain applications over a separated statement like x = x + 1 .

Embracing addition assignment helps in writing more efficient and readable code . It’s a small piece of syntax that eloquently embodies Python’s philosophy of simplicity and elegance in programming.

Subtraction Assignment

Following the theme of compound assignment operators, let’s delve into subtraction assignment, another handy operator that Python programmers frequently use. Similar to addition assignment, subtraction assignment uses the -= operator to subtract a value from a variable and then update that same variable in one succinct step. Subtraction assignment is particularly useful when you need to decrease the value of a variable incrementally, such as when tracking decrements in a loop or managing a countdown.

Practical applications of subtraction assignment are easy to spot in day-to-day coding scenarios. For instance, imagine you’re developing a basic game where the player’s health decreases with each enemy encounter. Here’s how subtraction assignment simplifies the code:

player_health -= enemy_damage

By employing subtraction assignment, you avoid the more verbose and less intuitive player_health = player_health - enemy_damage , making the code cleaner and more maintainable.

More than just a convenient shortcut, subtraction assignment can knock out a few processor cycles, optimizing performance at a micro level. This might not stand out in smaller scripts, but when you’re dealing with large-scale applications, every bit of efficiency counts.

Subtraction assignment plays well within the bounds of atomicity in certain contexts, contributing to safer coding patterns. However, it’s important to note that like all operators, the atomicity of a -= operation isn’t guaranteed across all environments, especially in multi-threaded applications where race conditions might occur.

To master Python, practicing with these operators is essential. They’re not merely shorthand—they represent a deeper understanding of Python’s design philosophy that favors simplicity over complexity. Incorporating subtraction assignment where appropriate will ensure your code is not only functional but also adheres to Python’s ethos, making it both efficient and elegant.

Moving alongside subtraction assignment, multiplication and division assignment operators offer similar benefits with their unique twists…

Multiplication Assignment

Moving on to multiplication assignment in Python, we encounter the *= operator. This operator functions similarly to subtraction assignment but focuses on multiplying the current value of a variable by another and then updating the variable. Just like subtraction assignment, multiplication assignment streamlines code , making it more readable and efficient. Here’s how you can put it to use:

my_number is now 15

In the above example, my_number originally holds the value of 5. After applying my_number *= 3 , the value of my_number becomes 15. This tool is particularly useful when dealing with iterative multiplication within loops.

One must keep in mind that multiplication assignment can lead to unexpected results when used with mutable data types, such as lists. For instance, using *= on a list will repeat the elements in that list:

my_list is now [1, 2, 3, 1, 2, 3]

This convenience comes with the same caveats as subtraction assignment. Atomicity isn’t assured, especially in multi-threaded applications where race conditions might affect the value of the variable before the operation takes place.

Just as subtraction assignment simplified decrementing a value, multiplication assignment makes incrementing values exponentially a succinct operation. It ensures that code isn’t cluttered with long-winded expressions, adhering to Python’s philosophy that “Readability counts”. Practicing these operators allows programmers to harness their true potential, enabling one to write concise and clearly structured code.

While multiplication assignment is ideal for numerical calculations , it also plays a significant role in creating repeated sequences or extending lists within your programs. Implementing the *= operator pushes the envelope on what can be achieved with a single line of Python code, reminding us that sometimes, powerful solutions are just an operator away.

Division Assignment

In Python programming, Division assignment is another operation that streamlines the process of dividing a variable by a number and then updating that variable with the new value. Just like multiplication assignment, division assignment uses a compound operator, which is /= . This operator takes the variable on its left, divides it by the expression on its right, and then assigns the result back to the originally named variable.

Consider the scenario where I have a variable defining a quantity of items and I’d like to split these items evenly among a certain number of people. Instead of using two lines of code—one to divide and another to assign the result—I can simply employ the /= operator to perform both actions simultaneously. Here’s how it’s done:

After this operation, the items variable would contain the value 24, precisely what you’d expect after dividing 120 by 5. Easy and efficient, isn’t it?

It’s important to highlight that the division assignment operator in Python always performs floating-point division . This means that even when dividing two integers, the result will be a float . If an integer result is needed, you’d have to manually convert the outcome back to an integer using the int() function or use the floor division assignment operator //= .

However, when using division assignment, a key thing to be cautious about is ZeroDivisionError . This error occurs if the right-hand side of the assignment is zero. In real-world applications, it’s always smart to implement error handling to catch and address such potential issues:

While division assignment is extremely useful, it’s also vital to keep in mind that this operator modifies the variable in-place. If the variable is shared across different parts of a program or among multiple threads, one must consider the implications of altering its value through division assignment to avoid unexpected behaviors or conflicts.

Modulo Assignment

When working with Python, I often find the modulo assignment operator as a secret weapon for certain tasks. Modulo assignment `%=“ combines the modulo operation with assignment in one step. This operator takes the current value of a variable, performs a modulo operation with the specified value, and then updates the variable with the result. Here’s how it works in practice:

After executing, my_number becomes 1, because 10 modulo 3 leaves a remainder of 1.

This is particularly useful when I need to:

  • Ensure a Value Stays Within a Range : If I’m iterating over a list and want to wrap around when I reach the end, modulo assignment ensures that my index value never exceeds the list length.
  • Perform Frequent Remainder Operations : In situations like checking for even or odd numbers, calculating residues in math problems or creating checksums, using %= makes the code cleaner and more efficient.

It’s vital to consider the datatype of the variables involved, as modulo assignment with floating-point numbers can lead to unexpected results due to precision issues.

Common errors such as TypeError may occur if I try to use modulo assignment between incompatible data types like strings and integers. For example, my_string %='world' would raise a TypeError because a string cannot be the left operand for this operator.

The beauty of using modulo assignment lies in its ability to simplify code and reduce the chance of mistakes that might happen if I were to split the modulo operation and the assignment into two separate lines. However, like division assignment, I’m cautious to avoid ZeroDivisionError when the right-hand side is zero, which is crucial to keeping my code exception-proof.

Exponentiation Assignment

When I dive into the concept of Exponentiation assignment in Python, it’s evident that it serves a significant role in mathematical operations. This operator combines exponentiation with assignment, streamlining the process of raising a variable to the power of another number. Exponentiation assignment is represented by **= and is a shorthand way to write the operation x = x ** y , where x is the base variable and y is the exponent.

By using this operator, I can conveniently update the value of a variable without needing to type its name multiple times. This is incredibly efficient when dealing with complex calculations or iterating over large datasets . Here’s an example that illustrates its simplicity:

The result would be 125 , as 5 to the power of 3 is 125 . Using exponentiation assignment, the variable x is now updated to hold the value of 125 .

It’s important to remember that while this operator is powerful, it should be used with precision, particularly with floating-point numbers, where results might not be exact due to the nature of binary floating-point representation.

Moreover, just like with modulo assignment, there’s the need to be aware of and prevent any attempt to raise a number to the power of 0 . Not because it will cause an error, since any number to the power of 0 is 1 , but because it might result in unexpected behavior depending on the use case. Ensuring that the data types are correct before performing operations will help to avoid errors and ensure that the code runs as expected.

In practice, exponentiation assignment can be a very handy tool when coding functions that involve exponential growth , such as compound interest calculations or geometric progression. This operator also highlights Python’s design philosophy of readability, making code more concise and readable at a glance.

Floor Division Assignment

When delving into the realm of arithmetic operators in Python, we often encounter the floor division operator // , which divides two numbers and rounds down to the nearest whole number. Combining this with an assignment operator creates the Floor division assignment operator //= , which is both a time-saver and an enhancer of code legibility. This operator effectively changes the value of a variable to the result of the floor division of its current value by another number.

Imagine working with a dataset that requires the normalization of values by batches. Doing this efficiently requires updating each value without introducing a temporary variable. That’s where //= shines. For example, a //= b translates to a = a // b , hence reducing the lines of code and potential for error.

However, it’s crucial to remember that floor division behaves differently with positive and negative numbers. While 9 // 2 will give you 4 , -9 // 2 will result in -5 , since the result is always rounded down to the nearest whole number. This nuance must be kept in mind to avoid unexpected results, especially when working with datasets that may include negative numbers.

Floor division assignment also plays well with integer and floating-point numbers. Precision may vary with floating-point numbers, so confirming the accuracy of results is always good practice.

In scenarios involving repeated halving or distribution of elements into bins, //= remains a beneficial tool. Whether you’re rounding down timestamps to the nearest minute, or partitioning resources, it provides a straightforward, readable approach to in-place arithmetic operations.

Python’s emphasis on readability and simplicity is echoed throughout its operator suite – and the floor division assignment operator is a testament to that. It streamlines mathematical operations while maintaining clarity, an essential trait for writing clean and maintainable code .

I’ve taken you through the essentials of Python’s arithmetic, comparison, and assignment operators, highlighting the floor division assignment operator’s role in streamlining your code. Remember, while it’s a powerful tool for batch normalization, it’s crucial to be mindful of its behavior with different number types. With these operators in your toolkit, you’re now better equipped to write more concise and readable Python scripts. Embrace these fundamentals, and you’ll see your coding efficiency soar.

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python operators.

Operators are used to perform operations on variables and values.

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

Python divides the operators in the following groups:

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

Python Arithmetic Operators

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

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

Python Assignment Operators

Assignment operators are used to assign values to variables:

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

Advertisement

Python Comparison Operators

Comparison operators are used to compare two values:

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

Python Logical Operators

Logical operators are used to combine conditional statements:

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

Python Identity Operators

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

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

Python Membership Operators

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

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

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

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

Operator Precedence

Operator precedence describes the order in which operations are performed.

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

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

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

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

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

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

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

codingem.com

software development and tech.

Python Arithmetic Operators: A Complete Guide (50+ Examples)

In Python, there are 7 arithmetic operators you can use to perform basic mathematical operations.

Here is a table of all the arithmetic operators in Python with examples:

Operator Name Use
+ Addition x + y
Subtraction x – y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

This table is a quick cheat sheet.

However, there are so many things you can do with arithmetic operators in Python. In this guide, you are going to learn how to use arithmetic operators extensively.

Before we start, let’s quickly learn what arithmetic precedence and precedence groups mean:

Precedence Groups

When there are multiple arithmetic operations chained together, the Python compiler needs to know which ones to evaluate first.

This is where precedence is used.

The precedence group of the arithmetic operator specifies in which order expressions are evaluated.

Here is the precedence grouping of the arithmetic operators in Python. The upper the operator is on the table, the higher the precedence.

Operators Meaning
Parentheses
Exponent
, , , Multiplication, Division, Floor division, Modulus
, Addition, Subtraction

Now that you understand what is precedence, it is time to jump into the arithmetic operators in Python.

In Python, you can add two numeric values together using the addition operator (+).

For example:

The += Operator

When adding variables, you can combine the addition operator (+) with the assignment operator (=) to form the addition assignment operator (+=).

This is a shorthand for:

The addition operator (+) belongs to the lowest precedence group with subtraction.

This means any other arithmetic operations are carried out first.

Here 2 * 3 is calculated before adding it to 1.

In other words, the Python compiler sees the above expression as:

Where any expressions inside the parenthesis are calculated first.

Now you understand the basics of the addition operator in Python.

Next, let’s take a look at the more advanced use of addition.

The __add__() Method

In Python, you can add numeric types together to produce a new numeric value that represents the sum of the two.

This is made possible by the __add__() method that is implemented behind the scenes.

As a matter of fact, whenever you use the + operator, you are actually calling the __add__() method of the object.

You can verify that this is the case by running a simple experiment:

Understanding this is useful in a moment.

In Python, you can create a custom type by implementing a class that specifies the type.

For example, let’s create a Weight class:

Now, let’s see what happens when you try to add two Weight objects together:

This results in an error:

The error says you cannot use + on two Weight objects.

This is not a surprise.

How could the Python interpreter even know what it means to add two weights together?

But there is a way for you to make this work.

To support addition with custom types in Python, implement the __add__() method into the custom class.

For instance, let’s make it possible to add Weight objects together by summing the kilos of the objects:

The __add__() method takes two Weight objects:

  • self , the left-hand side of the operation.
  • otherWeight , the right-hand side of the operation.

It then sums up the kilos of the weights, creates a new Weight object, and returns it.

Now you can add two Weight objects together to create larger Weight objects, for example:

Pretty handy, isn’t it?

Now you understand how to add two custom objects together in Python using the __add__ method.

But what if the left-hand side and the right-hand side objects are not of the same type?

Adding Different Types

Let’s try to add a Weight object and an int :

This results in the following error:

This is because we have not specified what happens when adding a Weight to another object, such as to an int .

To support adding different types, you need to extend the implementation of the __add__() method:

  • If the right-hand side is an int , we can directly add it to the kilos of the Weight object.
  • If the right-hand side is not an int , we assume it is a Weight . Thus, we need to access the kilos before adding them to the left-hand side.

Here is what the updated class looks like:

Now you can add Weight objects and ints together:

But there is a small problem.

When you reverse the order of the addition:

There is an error, even though one would expect it to work:

Now, let’s think about why this happens.

As you now know, calling a + b is the same as calling a.__add__(b) .

In the failing piece of code, you are calling 200 + w1 , that is, (200).__add__(w1) .

Now, this is problematic.

Trying to add a Weight object to an int object does not work because int has no idea about our Weight class. That is to say that the __add__ method in the int class does not handle adding Weight objects.

To overcome this, you would need to modify the native implementation of the int type.

But this is a no-go.

Instead, Python has a built-in __radd__() method you can use to swap the order of the addition.

The __radd__() Method

The __radd__() method stands for “right addition”.

The idea is simple:

  • If a + b fails, call b.__radd__(a) which is implemented such that a + b does not cause problems.

Let’s implement the __radd__() method to the Weight class:

Now you check that it works:

Now that you understand how addition works in Python, let’s move on to subtraction.

Subtraction

In Python, you can subtract two numeric values from one another by using the subtraction operator (-).

The -= Operator

When decrementing variables, you can combine the subtraction operator (-) with the assignment operator (=) to form the subtraction assignment operator (-=).

The subtraction operator belongs to the lowest precedence group with addition.

This means any other arithmetic operations are calculated first.

Here 2 * 3 is calculated before subtracting it from 1.

Let’s have a look at some advanced use of the subtraction operator.

The __sub__() Method

In Python, you can subtract two numeric types from one another to produce a new value that represents the difference between the two.

This is made possible by the __sub__() method behind the scenes.

The working principle is exactly the same as the __add__() method from the previous section.

Whenever you use the – operator, you are actually calling the __sub__() method.

For example, let’s continue with the Weight class implemented in the previous chapter:

Now, let’s see what happens when you try to subtract two Weight objects:

The error says you cannot use – on two Weight objects.

However, there is a way for you to make this work.

To support subtraction with custom types, implement the __sub__() method into the custom class.

For instance, let’s make it possible to subtract Weight objects from one another by subtracting the kilos of the objects:

The __sub__() method takes two Weight objects:

It subtracts the kilos of the weights, creates a new Weight object, and returns it.

Now you can subtract two Weight objects to get the weight difference as a new Weight object:

Subtracting Different Types

Let’s try to subtract an int from a Weight :

This throws an error:

We have not specified what happens when subtracting something else than a Weight from a Weight object. This is why the above piece of code does not work.

To make subtracting different types work, extend the implementation of the __sub__() method:

  • If the right-hand side is an int , we can directly subtract it from the kilos .
  • If the right-hand side is not an int , we assume it is a Weight . Thus, we need to access the kilos before subtracting.

Now it works:

But there is one more problem.

When you reverse the order of the subtraction:

As you now know, calling a – b is the same as calling a.__sub__(b) .

In the above you are calling 150 – w1 , that is, (150).__sub__(w1) .

This is the problem.

Trying to subtract a Weight object from an int object does not work because the built-in int type has no idea about the Weight class.

To overcome the issue, you would need to modify the native implementation of the int type.

But there is a better way to do it.

Instead, Python has a built-in __rsub__() method you can use to swap the order of the subtraction.

The __rsub__() Method

The __rsub__() method stands for “right subtraction”.

The idea of this is easy to understand:

  • If a – b fails, call b.__rsub__(a) which is implemented such that a – b does not cause problems.

Let’s implement the __rsub__() method to the Weight class:

Now you understand how subtraction works in Python.

Also, you may have noticed there is a clear pattern between each arithmetic operator. Each arithmetic operator corresponds to a special method with a double underscore method that is called behind the scenes. This method can be customized for a custom type.

Anyway, let’s continue with multiplication.

Multiplication

In Python, you can multiply two numeric types by using the multiplication operator (*).

The *= Operator

When multiplying variables, you may combine the multiplication operator (*) with the assignment operator (=) to form the multiplication assignment operator (*=).

The multiplication operator belongs to a higher precedence group than addition and subtraction.

This means multiplication takes place before addition or subtraction.

Here is how you can group the operations in your mind:

Where expressions inside the parenthesis are calculated first.

Next, let’s take a look at the more advanced use of multiplication.

The __mul__() Method

In Python, you can multiply numeric types to produce a new value that represents the product of the two. This is made possible by the __mul__() method that is implemented behind the scenes.

As a matter of fact, whenever you use the * operator, you are actually calling the __mul__() method behind the scenes.

You can try it to see how it works:

Now, let’s see what happens when you try to multiply two Weight objects:

The error says you cannot use * on two Weight objects.

How could the Python interpreter even know what it means to multiply two weights?

Anyway, similar to the other arithmetic operators, there is a way to make this work.

To support multiplication with custom types in Python, implement the __mul__() method into the custom class.

For instance, let’s make it possible to multiply Weight objects by multiplying the kilos of the objects:

The __mul__() method takes two Weight objects:

It then multiplies the kilos of the weights, creates a new Weight object, and returns it.

Let’s make sure it works:

Now you understand how to multiply custom types by one another.

Multiplying Different Types

Let’s try to multiply a Weight object by an int :

This happens because it is not specified what happens when multiplying a Weight by another object.

To make multiplying different types work, extend the implementation of the __mul__() method:

  • If the right-hand side is an int , we can directly multiply it by the kilos of the weight.
  • If the right-hand side is not an int , we assume it is a Weight . So we need to access the kilos before the multiplication.

Here is the updated class:

Now multiplying Weights by ints is possible:

Now there is one more issue.

If you reverse the order of the multiplication:

Let’s see why this error happens.

Calling a * b is the same as calling a.__mul__(b) .

Above you are calling 150 * w1 , that is, (150).__mul__(w1) .

Trying to multiply an int object by a Weight does not work because the built-in int type has no idea about the Weight class.

To overcome the issue, you would need to make changes to the native implementation of the int type.

Instead of doing this, Python has a built-in __rmul__() method you can safely implement to swap the order of the multiplication.

The __rmul__() Method

The __rmul__() method stands for “right multiplication”.

The working principle is simple:

  • If a * b fails, call b.__rmul__(a) which is implemented such that a * b does not cause problems.

Let’s implement the __rmul__() method to the Weight class:

Next, let’s take a look at division.

In Python, you can divide two numeric types using the division operator (/).

The /= Operator

When you want to update a variable by dividing it, you can combine the division operator (/) with the assignment operator (=) to form the division assignment operator (/=).

Division operation precedes addition and subtraction.

Here 6 / 3 is calculated before adding it to 1.

Next, let’s take a look at the more advanced use of division.

The __truediv__() Method

In Python, you can divide numeric types to produce a new value that represents the division of the two.

This is made possible by the __truediv__() method that is implemented behind the scenes.

Whenever you use the / operator, you are actually calling the __truediv__() method under the hood.

You can verify this by running a simple test:

In Python, you can create a custom type by implementing a class.

For example, let’s use the Weight class from earlier examples:

Now, let’s divide two Weight objects:

You cannot use / on two Weight objects. This is because the Python interpreter has no idea what division means in the context of Weight .

Anyway, you can change this.

To support the division of custom types in Python, implement the __truediv__() method into the custom class.

For instance, let’s make it possible to divide Weight objects by dividing the kilos properties:

The __truediv__() method takes two Weight objects:

It then divides the kilos of the weights, creates a new Weight object, and returns it.

Let’s test it:

Now it is possible to divide Weight objects by one another.

Dividing Different Types

Let’s try to divide a Weight object by an int :

This is not a surprise because we have not specified what should happen when dividing a Weight by an integer.

To make the division work, extend the implementation of the __truediv__() method:

  • If the right-hand side is an int , we can directly divide it by the kilos of the Weight object.
  • If the right-hand side is not an int , we assume it is a Weight . Then we need to access the kilos before the the division.

Here is how it looks in code:

Now multiplying Weights by ints works:

Now there is still one problem.

When you reverse the order of the division operands:

You are going to see an error:

Let’s see why this happens.

As you already know, calling a / b is the same as calling a.__truediv__(b) .

In the above piece of code, you are calling 150 / w1 , that is, (150).__truediv__(w1) .

This causes the problem.

Trying to divide an int object by a Weight does not work because the built-in int type has no idea about the Weight class.

To fix the problem, you would need to make changes to the built-in int type’s __truediv__ method. But that would be a bad idea.

Instead, Python has a built-in __rtruediv__() method you can use to swap the order of the division.

The __rtruediv__() Method

The __rtruediv__() method stands for “right division”.

It works such that:

  • If a / b fails, call b.__rtruediv__(a) which is implemented such that a / b does not cause problems.

Let’s implement the __rtruediv__() method to the Weight class:

Now you can divide an int by a Weight object.

Next, let’s take a look at the integer division, also known as the floor division.

Integer Division

In Python, you can integer-divide (floor-divide) two numeric types by using the floor division operator (//).

The floor division divides two numbers and rounds the result down to the nearest integer. The result is thus always an integer.

The //= Operator

When floor-dividing variables, you may combine the floor division operator (//) with the assignment operator (=) to form the floor division assignment operator (//=).

The floor division operator belongs to a higher precedence group than addition and subtraction. This means it takes place before addition or subtraction.

Here 10 // 3 is calculated before adding it to 5.

Next, let’s take a look at the more advanced use of floor division in Python.

The __floordiv__() Method

In Python, you can floor-divide numbers to produce an integer that represents the floor division between the two numbers.

Floor division is made possible by the __floordiv__() method that is implemented under the hood.

When you use the // operator, you are actually calling the __floordiv__() method behind the scenes.

In Python, you can write custom types. This happens by implementing a class that acts as a blueprint for creating objects.

For example, let’s use the Weight class from the earlier examples:

When you try to floor-divide two Weight objects:

You receive an error:

The error states you cannot apply // on two Weight objects.

This is not a real surprise. How could the Python interpreter even know what it means to multiply two weights?

Anyway, there is a way to make it work.

To support floor division between custom types in Python, implement the __floordiv__() method into the custom class.

For instance:

The __floordiv__() method takes two Weight objects:

  • self , the left-hand side of the operator.
  • otherWeight , the right-hand side of the operator.

It then floor-divides the kilos properties, creates a new Weight object, and returns it.

Now you understand how to floor-division works for custom types.

Floor-Dividing Different Types

Let’s try to floor divide a Weight object by an int :

This is because you have not specified what happens when floor-divide a Weight by another object.

To make floor-dividing work this way, you need to extend the implementation of the __floordiv__() method:

  • If the right-hand side is an int , we can directly floordivide it by the kilos property.
  • If the right-hand side is not an int , we assume it is a Weight and access the kilos before the division.

Now floor-division between Weights and ints is possible:

Now there is still one small issue.

When you reverse the order of the operands:

There is an error:

As you learned, calling a // b is the same as calling a.__floordiv__(b) .

Above you are calling 150 // w1 , that is, (150).__floordiv__(w1) .

Trying to floor-divide a Weight object by an int does not work because the built-in int type has no idea about the Weight class.

To fix this, you would need to make changes to the native implementation of the int type.

However, instead of doing it that way, Python has a built-in __rfloordiv__() method you can use to swap the order of the floor division.

The __rfloordiv__() Method

The __rfloordiv__() method stands for “right floor division”.

  • If a // b fails, call b.__rfloordiv__(a) which is implemented such that a // b does not cause problems.

With this in mind, let’s implement the __rfloordiv__() method to the Weight class:

Next, let’s take a look at a closely related arithmetic operator, the modulo.

In Python, you can calculate the remainder in division using the modulo operator (%).

For example, let’s divide 15 pizza slices for 6 guests evenly.

The result is 3.

This means 3 slices of pizza will be leftover.

If you think about it, that makes sense.

Sharing 15 slices of pizza evenly to a group of 6 is not possible. However, you can give 2 slices to each person. At this point, you have shared 12 slices out of 15, so there will be 3 slices left.

The %= Operator

You can combine the modulo operator (%) with the assignment operator (=) to form the modulo assignment operator (%=).

This is a useful shorthand for:

The modulo belongs to a precedence group that is higher than addition or subtraction. This means modulo takes place before them.

Next, let’s take a look at the more advanced use of modulo in Python.

The __mod__() Method

Calculating the modulo is possible via the __mod__() method. This method is implemented behind the scenes.

Whenever you use the % operator, you call the __mod__() method behind the scenes.

For example, let’s continue with the Weight class you saw earlier.

Let’s see what happens when you try to modulo two Weight objects:

This shows an error:

You cannot apply % between two Weight objects. This is because the Python interpreter does not know what it means to take modulo between Weight objects.

However, you can separately specify what this means to make it work.

To support modulo between custom types, implement the __mod__() method into the custom class.

For instance, let’s make it possible to take a remainder between Weight objects based on the kilos :

The __mod__() method takes two Weight objects:

  • Calculates the remainder using the kilos of the weights
  • Creates a new Weight object
  • Returns the new Weight object.

It works! However, please notice that this example is pretty useless. It just demonstrates how you can customize the % operator for custom classes in Python.

Now you understand how to calculate modulos between two Python objects.

Calculating Modulo Between Different Types

Let’s try to mod a Weight object with an int :

You have not specified what happens when multiplying a Weight by another object. This is why you see an error.

To make modulo between different types work, extend the implementation of the __mod__() method:

  • If the right-hand side is an int , we can directly calculate the modulo using the kilos of the weight.
  • If the right-hand side is not an int , we assume it is a Weight . So we need to access the kilos before calculating the modulo.

Here is what the updated code looks like:

Now calculating modulo between Weights and ints is possible:

Even though this works, there is still one little problem we need to address.

When you reverse the order, that is, when you try to calculate modulo between int and a Weight :

You see an error:

Calling a % b is the same as calling a.__mod__(b) .

Above you are calling 20 % w1 , that is, (20).__mod__(w1) .

Trying to calculate the modulo between an int and a Weight does not work. This is because the built-in int type has no idea about the Weight class and what to do with it.

To overcome the issue, you would need to make changes to the native implementation of the int type. But as you already know, this is not what you want to do.

Instead, Python has a built-in __rmod__() method you can use to swap the order of the operation.

The __rmod__() Method

The __rmod__() method stands for “right modulo”.

The idea is:

  • If a % b fails, call b.__rmod__(a) which is implemented such that a % b does not cause problems.

Let’s implement the __rmod__() method:

Awesome. Last but not least, let’s take a look at the power operator in Python.

In maths, power means to multiply a number by itself a number of times.

  • 3 2 means 3 * 3.
  • 3 4 means 3 * 3 * 3 * 3.

In Python, you can raise a number to a power using the power operator (**).

  • x is the number to be raised.
  • y is the number of times x is multiplied by itself.

The **= Operator

When raising variables to power, you may combine the power operator (**) with the assignment operator (=) to form the power assignment operator (**=).

In Python, the power operator has the highest precedence of all arithmetic operators.

This means power takes place before multiplication, division, modulo, floor division, addition, or subtraction.

Next, let’s take a look at the more advanced use of powers in Python.

The __pow__() Method

In Python, you can raise numeric types to a power produce a new value that represents the number multiplied by itself a number of times.

The power operation is made possible by the __pow__() method behind the scenes.

Whenever you use the ** operator, you are actually calling the __pow__() method.

This is easy to verify.

For example, let’s continue with the Weight class from the previous chapters:

Now, let’s see what happens when you try to raise a Weight object to the power of another Weight :

Obviously, this results in an error:

The error says you cannot use ** on two Weight objects. This is because the Python interpreter does not know what it means to raise a Weight to the power of another Weight .

Anyway, there is a way to make this work.

To support power with custom types in Python, implement the __pow__() method into the class.

For example, let’s make it possible to raise a Weight object to the power of another Weight via the kilos property:

The __pow__() method takes two Weight objects:

  • Raises the kilos of the weights to powers accordingly
  • Returns the new Weight .

Let’s test that it works:

Now you understand how to raise types to powers in Python.

Raising Different Types to Power

Let’s try to raise a Weight object to the power of an int :

This happens because you have not specified what happens when raising a Weight to the int power.

To make it work, extend the implementation of the __pow__() method:

  • If the right-hand side is an int , we can directly raise the kilos of the weight to the power of the integer value.
  • If the right-hand side is not an int , we assume it is a Weight . So we need to access the kilos before the raising it.

Here is what the code looks like after the updates:

Now you can test it:

Now there is one more problem to be solved.

When you reverse the order, that is, when you try to raise an int to the power of Weight :

You get an error:

Calling a ** b is the same as calling a.__pow__(b) .

Here you are calling 3 ** w1 , that is, (3).__pow__(w1) .

This is problematic because the int type does not know anything about the Weight class.

To overcome the issue, you would need to make changes to the built-in int type. But this would be bad.

Instead, Python has a built-in __rpow__() method you can use to swap the order of the operation.

The __rpow__() Method

The __rpow__() method stands for “right power”.

  • If a ** b fails, call b.__rpow__(a) which is implemented such that a ** b does not cause problems.

With this information, let’s implement the __rpow__() :

This concludes the comprehensive guide on all the arithmetic operators in Python.

Thanks for reading.

Happy coding!

Further Reading

Increment and Decrement Operators in Python

Learn Python practically and Get Certified .

Popular Tutorials

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

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

Python Fundamentals

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

Python Operators

Python flow control.

Python if...else Statement

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

Python Data types

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

Python Files

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

Python Object & Class

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

Python Operator Overloading

Python Advanced Topics

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

Python Date and Time

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

Additional Topic

Precedence and Associativity of Operators in Python

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

Python Tutorials

Python 3 Tutorial

  • Python Strings
  • Python any()

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

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

  • Types of Python Operators

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

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

1. Python Arithmetic Operators

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

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

Operator Operation Example
Addition
Subtraction
Multiplication
Division
Floor Division
Modulo
Power

Example 1: Arithmetic Operators in Python

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

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

2. Python Assignment Operators

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

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

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

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

Example 2: Assignment Operators

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

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

3. Python Comparison Operators

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

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

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

Example 3: Comparison Operators

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

4. Python Logical Operators

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

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

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

Example 4: Logical Operators

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

5. Python Bitwise operators

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

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

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

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

6. Python Special operators

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

  • Identity operators

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

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

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

Example 4: Identity operators in Python

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

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

  • Membership operators

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

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

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

Example 5: Membership operators in Python

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

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

  • Precedence and Associativity of operators in Python

Table of Contents

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

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

Write a function to split the restaurant bill among friends.

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

Video: Operators in Python

Sorry about that.

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

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Tutorial

Python Programming

Python Operators

Updated on:  November 14, 2021 | 33 Comments

Learning the operators is an excellent place to start to learn Python. Operators are special symbols that perform specific operations on one or more operands (values) and then return a result. For example, you can calculate the sum of two numbers using an addition ( + ) operator.

The following image shows operator and operands

Python operator and operands

  • Python If-else and Loops Exercise
  • Python Operators and Expression Quiz

Python has seven types of operators that we can use to perform different operation and produce a result.

Arithmetic operator

  • Relational operators

Assignment operators

Logical operators, membership operators, identity operators.

  • Bitwise operators

Table of contents

Addition operator +.

  • Subtraction –

Multiplication *

Floor division //, exponent **, relational (comparison) operators, and (logical and), or (logical or), not (logical not), in operator, not in operator, is operator, is not operator, bitwise and &, bitwise or |, bitwise xor ^.

  • Bitwise 1’s complement ~
  • Bitwise left-shift <<
  • Bitwise right-shift >>

Python Operators Precedence

Arithmetic operators are the most commonly used. The Python programming language provides arithmetic operators that perform addition, subtraction, multiplication, and division. It works the same as basic mathematics.

There are seven arithmetic operators we can use to perform different mathematical operations, such as:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • // Floor division)
  • ℅ (Modulus)
  • ** (Exponentiation)

Now, let’s see how to use each arithmetic operator in our program with the help of examples.

It adds two or more operands and gives their sum as a result. It works the same as a unary plus. In simple terms,  It performs the addition of two or more than two values and gives their sum as a result.

Also, we can use the addition operator with strings, and it will become string concatenation.

Subtraction -

Use to subtracts the second value from the first value and gives the difference between them. It works the same as a unary minus. The subtraction operator is denoted by - symbol.

Multiply two operands. In simple terms, it is used to multiplies two or more values and gives their product as a result. The multiplication operator is denoted by a * symbol.

You can also use the multiplication operator with string. When used with string, it works as a repetition.

Divide the left operand (dividend) by the right one (divisor) and provide the result (quotient ) in a float value. The division operator is denoted by a / symbol.

  • The division operator performs floating-point arithmetic. Hence it always returns a float value.
  • Don’t divide any number by zero. You will get a Zero Division Error: Division by zero

Floor division returns the quotient (the result of division) in which the digits after the decimal point are removed. In simple terms, It is used to divide one value by a second value and gives a quotient as a round figure value to the next smallest whole value.

It works the same as a division operator, except it returns a possible integer. The // symbol denotes a floor division operator.

  • Floor division can perform both floating-point and integer arithmetic.
  • If both operands are int type, then the result types. If at least one operand type, then the result is a float type.

The remainder of the division of left operand by the right. The modulus operator is denoted by a % symbol. In simple terms, the Modulus operator divides one value by a second and gives the remainder as a result.

Using exponent operator left operand raised to the power of right. The exponentiation operator is denoted by a double asterisk ** symbol. You can use it as a shortcut to calculate the exponential value.

For example, 2**3 Here 2 is multiplied by itself 3 times, i.e., 2*2*2 . Here the 2 is the base, and 3 is an exponent.

Relational operators are also called comparison operators. It performs a comparison between two values. It returns a boolean  True or False depending upon the result of the comparison.

Python has the following six relational operators.

Assume variable x holds 10 and variable y holds 5

Example
 (Greater than)It returns True if the left operand is greater than the right  
result is 
 (Less than)It returns True if the left operand is less than the right  
result is 
 (Equal to)It returns True if both operands are equal  
result is 
 (Not equal to)It returns True if both operands are equal  
result is 
 (Greater than or equal to)It returns True if the left operand is greater than or equal to the right  
result is 
 (Less than or equal to)It returns True if the left operand is less than or equal to the right  
result is 

You can compare more than two values also. Assume variable x holds 10, variable y holds 5, and variable z holds 2.

So print(x > y > z) will return True because x is greater than y, and y is greater than z, so it makes x is greater than z.

In Python, Assignment operators are used to assigning value to the variable. Assign operator is denoted by = symbol. For example, name = "Jessa" here, 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 .

 (Assign) Assign 5 to variable  a = 5
 (Add and assign) Add 5 to a and assign it as a new value to  a = a+5
 (Subtract and assign) Subtract 5 from variable   and assign it as a new value to  a = a-5
 (Multiply and assign) Multiply variable   by 5 and assign it as a new value to  a = a*5
 (Divide and assign) Divide variable   by 5 and assign a new value to  a = a/5
 (Modulus and assign) Performs modulus on two values and assigns it as a new value to  a = a%5
 (Exponentiation and assign) Multiply   five times and assigns the result to  a = a**5
 (Floor-divide and assign) Floor-divide   by 5 and assigns the result to  a = a//5

Logical operators are useful when checking a condition is true or not. Python has three logical operators. All logical operator returns a boolean value True or False depending on the condition in which it is used.

 (Logical and)True if both the operands are Truea and b
 (Logical or)True if either of the operands is Truea or b
 (Logical not)True if the operand is Falsenot a

The logical and operator returns True if both expressions are True. Otherwise, it will return. False .

In the case of arithmetic values , Logical and always returns the second value ; as a result, see the following example.

The  logical or the operator returns a boolean  True if one expression is true, and it returns False if both values are false .

In the case of arithmetic values , Logical or it always returns the first value; as a result, see the following code.

The  logical not operator returns boolean True if the expression is false .

In the case of arithmetic values , Logical not always return False for nonzero value.

Python’s membership operators are used to check for membership of objects in sequence, such as string, list , tuple . It checks whether the given value or variable is present in a given sequence. If present, it will return True else False .

In Python, there are two membership operator  in  and  not in

It returns a result as True if it finds a given object in the sequence. Otherwise, it returns False .

Let’s check if the number 15 present in a given list using the in operator.

It returns True if the object is not present in a given sequence. Otherwise, it returns False

Use the Identity operator to check whether the value of two variables is the same or not. This operator is known as a reference-quality operator because the identity operator compares values according to two variables’ memory addresses.

Python has 2 identity operators is and is not .

The is operator returns Boolean True or False . It Return True if the memory address first value is equal to the second value. Otherwise, it returns False .

Here, we can use is() function to check whether both variables are pointing to the same object or not.

The is not the operator returns boolean values either True or False . It Return True if the first value is not equal to the second value. Otherwise, it returns False .

Bitwise Operators

In Python, bitwise operators are used to performing bitwise operations on integers. To perform bitwise, we first need to convert integer value to binary (0 and 1) value.

The bitwise operator operates on values bit by bit, so it’s called bitwise . It always returns the result in decimal format. Python has 6 bitwise operators listed below.

  • & Bitwise and
  • | Bitwise or
  • ^ Bitwise xor
  • ~ Bitwise 1’s complement
  • << Bitwise left-shift
  • >>  Bitwise right-shift

It performs  logical AND  operation on the integer value after converting an integer to a binary value and gives the result as a decimal value. It returns True only if both operands are True. Otherwise, it returns False .

Here, every integer value is converted into a binary value. For example, a =7 , its binary value is 0111, and b=4 , its binary value is 0100. Next we performed logical AND, and got 0100 as a result, similarly for a and c, b and c

Following diagram shows AND operator evaluation.

Python bitwise AND

It performs  logical OR  operation on the integer value after converting integer value to binary value and gives the result a decimal value. It returns  False  only if both operands are  True . Otherwise, it returns  True .

Here, every integer value is converted into binary. For example,  a =7 its binary value is 0111, and b=4 , its binary value is 0100, after logical OR, we got 0111 as a result. Similarly for  a  and  c ,  b and  c .

Python bitwise OR

It performs Logical XOR  ^  operation on the binary value of a integer and gives the result as a decimal value.

Example : –

Here, again every integer value is converted into binary. For example,  a =7  its binary value is 0111 and b=4 , and its binary value is 0100, after logical XOR we got 0011 as a result. Similarly for  a  and  c ,  b  and  c .

Python bitwise XOR

Bitwise 1’s complement  ~

It performs 1’s complement operation. It invert each bit of binary value and returns the bitwise negation of a value as a result.

Bitwise left-shift  <<

The left-shift  <<  operator performs a shifting bit of value by a given number of the place and fills 0’s to new positions.

Python bitwise left shift

Bitwise right-shift  >>

The left-shift  >>  operator performs shifting a bit of value to the right by a given number of places. Here some bits are lost.

Python bitwise right shift

In Python, operator precedence and associativity play an essential role in solving the expression. An expression is the combination of variables and operators that evaluate based on operator precedence.

We must know what the precedence (priority) of that operator is and how they will evaluate down to a single value. Operator precedence is used in an expression to determine which operation to perform first.

In the above example. 1st precedence goes to a parenthesis () , then for plus and minus operators. The expression will be executed as.

The following tables shows operator precedence highest to lowest.

1 (Highest) Parenthesis
2 Exponent
3 , , Unary plus, Unary Minus, Bitwise negation
4 , , , Multiplication, Division, Floor division, Modulus
5 , Addition, Subtraction
6 , Bitwise shift operator
7 Bitwise AND
8 Bitwise XOR
9 Bitwise OR
10 , , , , , Comparison
11 , , ,  Identity, Membership
12notLogical NOT
13andLogical AND
14 (Lowest)orLogical OR

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

arithmetic assignment operators in python

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

Python Tutorial

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

Python - Assignment Operators

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

Python Assignment Operator

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

Example of Assignment Operator in Python

Consider following Python statements −

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

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

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

Augmented Assignment Operators in Python

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

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

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

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

The following are the augmented assignment operators in Python:

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

Augmented Addition Operator (+=)

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

It will produce the following output −

Augmented Subtraction Operator (-=)

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

Augmented Multiplication Operator (*=)

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

Augmented Division Operator (/=)

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

Augmented Modulus Operator (%=)

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

Augmented Exponent Operator (**=)

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

Augmented Floor division Operator (//=)

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

site logo2

Arithmetic And Assignment Operators In Python

  • Post author: Maitry
  • Post category: Quick References
  • Post comments: 0 Comments

Hello Pythonistas, here’s a quick reference to arithmetic and assignment operators in Python.

Operators In Python

Operators are simple  symbols  or  keywords (reserved by python) that perform some task between two given values.

These  values  can be string, integer, float, or any data type and even variable.

See simple😇, isn’t it? Let’s in detail find out about all of its 6 types.

Types of operators arithmetic and assignment

Arithmetic Operators

These operators perform mathematical tasks on the two values(operand), like +,-,/,*, etc. Let’s see each one of them in detail.

OPERATORNAMEEXAMPLEEXPLANATION
+Addition adds two numbers
–Subtraction performs subtraction
*Multiplication multiplies two numbers
/Division divides one number with the other
//Floor Division gives the answer in   after dividing
%Modulus gives the remainder after dividing
**Exponentiation raises first to the power of second

Assignment Operators

Has your teacherđŸ‘©â€đŸ« ever assigned you homework?

She might have assigned it to you using blackboard and chalk.

Assignment operators assign values to variables, they work similar to chalk and blackboard, that is, act as a tool for assignment.

For example, a = 10 here, '=' is an assignment operator it gives the variable 'a' which is on the left the value '10' which is on right.

Let’s look at these operators in detail.

OperatorNameExampleTwin toExplanation
=Equals to This is used to to any variable
+=Plus equals to This is used to numbers in a pythonic way.
-=Minus equals to This is used to in a pythonic way.
*=Multiply equals to This is used to in a pythonic way
/=Divide equals to This is used to in a pythonic way
//=Floor division equals to This is used to in a pythonic way
**=Exponentiation equals to This is used to in a pythonic way
%=Modulus equals to This is used to in a pythonic way

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Reddit (Opens in new window)

You Might Also Like

Read more about the article Variables In Python

Variables In Python

Read more about the article Mutable: Are Lists In Python Mutable?

Mutable: Are Lists In Python Mutable?

Setup visual studio code for python.

Read more about the article Types Of String In Python And Where To Use ‘, “, and ”’

Types Of String In Python And Where To Use ‘, “, and ”’

Leave a reply.

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

arithmetic assignment operators in python

đŸ˜¶ Operators

Python operators are the symbols that allow us to perform different types of operations on variables and values. They are the building blocks of any programming language, and Python is no exception. Python provides a wide range of operators that can be used to perform arithmetic, logical, comparison, assignment, and bitwise operations.

Understanding the different types of operators is crucial to writing efficient and error-free code in Python. In this section, we will explore the different types of operators available in Python and learn how to use them effectively in our programs. So buckle up and get ready to dive into the world of Python operators!

I. Arithmetic Operators

Arithmetic operators are used in Python to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. These operators are used on numeric data types such as integers, floats, and complex numbers.

Python provides the following arithmetic operators:

OperatorNameExampleResult

The floor division (//) operator returns the largest integer that is less than or equal to the division result.

a. Addition

Addition is one of the most basic arithmetic operations in Python. It is denoted by the + symbol and is used to add two numbers or concatenate two strings. For example, if we want to add two numbers x and y together, we can use the + operator like this:

Similarly, if we want to concatenate two strings a and b , we can use the + operator like this:

In both cases, the + operator performs the desired operation and returns a new value that we can assign to a variable or use directly.

b. Subtraction

The subtraction operator (-) is used to subtract one value from another. It takes two operands and returns the difference between them. For example, 5 - 3 will return 2, and 10.5 - 3.2 will return 7.3.

In Python, the subtraction operator can also be used with variables. For example:

Note that the subtraction operator can also be used with negative numbers. For example, 5 - (-3) will return 8.

c. Multiplication

Multiplication is a mathematical operation that is represented by the symbol * in Python. It is used to find the product of two or more values. Here's an example:

In the above example, we have two variables a and b with values 10 and 5 respectively. We multiply these two variables using the * operator and store the result in the variable c . Finally, we print the value of c which is 50 (the product of a and b ).

d. Division

In Python, the / operator is used for division. It returns the quotient (result of division) in the form of a float, even if both the operands are integers. If you want to get the quotient as an integer, you can use the // operator, which performs floor division.

Here's an example:

In the example above, we divide a by b using both the / and // operators. The result of the floating point division is stored in c , which is a float, while the result of the integer division is stored in d , which is an integer.

Modulus operator returns the remainder of the division operation between two operands. It is represented by the percentage sign % .

For example, the expression 9 % 4 returns 1 because when 9 is divided by 4, the remainder is 1.

Here is an example code snippet:

e. Exponentiation

Exponentiation is another arithmetic operator in Python represented by the double asterisk symbol (**). It raises the first operand to the power of the second operand.

Here, the base is the first operand, and the exponent is the second operand.

In the above example, 2 is raised to the power of 3, which results in 8.

f. Floor Division

Floor Division operator in Python is represented by two forward slashes // and it returns the quotient of the division operation rounding down to the nearest integer. For example, the floor division of 7 // 3 would be 2 since 3 goes into 7 two whole times with 1 left over.

Here's an example of using floor division operator:

In the above example, we have defined two variables a and b , and then used floor division operator // to divide a by b . Since a is 10 and b is 3 , the result of a // b is 3 .

II. Comparison Operators

Comparison operators, also known as relational operators, are used to compare two values or operands. In Python, comparison operators always return a boolean value - either True or False.

There are six comparison operators in Python:

Equal to (==)

Not equal to (!=)

Greater than (>)

Less than (<)

Greater than or equal to (>=)

Less than or equal to (<=)

These operators are used in conditional statements and loops to test whether a certain condition is true or false.

a. Equal to (==)

The equal to operator ( == ) is a comparison operator used to compare the equality of two operands. It returns True if the values of the two operands are equal, otherwise, it returns False .

In this example, the first comparison returns False because x is not equal to y . The second comparison returns True because x is equal to z .

b. Not equal to (!=)

In Python, the "not equal to" operator is represented by the exclamation mark followed by an equal sign (!=). It is a binary operator and is used to compare two values. The operator returns True if the values are not equal and False if they are equal.

Here's an example of using the "not equal to" operator in Python:

c. Greater than (>)

The greater than operator ( > ) is used to check if the left operand is greater than the right operand. It returns True if the left operand is greater than the right operand, otherwise, it returns False . Here is an example:

In the example above, x is greater than y , so the expression x > y returns True .

d. Less than (<)

In Python, the less than operator < is used to compare two operands. It returns True if the left operand is less than the right operand, and False otherwise.

In this example, x is less than y , so the if statement evaluates to True , and the first print statement is executed.

e. Greater than or equal to (>=)

The greater than or equal to operator (>=) is used to compare two values. It returns True if the left operand is greater than or equal to the right operand, and False otherwise.

For example:

In this example, the first print statement returns True because x (which is 5) is greater than or equal to y (which is 3). The second print statement returns False because y is less than x .

f. Less than or equal to (<=)

The "Less than or equal to" operator is represented by the symbol "<=". It is used to check if one value is less than or equal to another value.

For example, in the expression "5 <= 10", the operator "<=" checks if 5 is less than or equal to 10. Since this is true, the expression evaluates to True. However, in the expression "10 <= 5", the operator "<=" checks if 10 is less than or equal to 5. Since this is false, the expression evaluates to False.

Here's an example code snippet demonstrating the use of the "<=" operator:

This code will output "x is less than or equal to y", since 5 is indeed less than or equal to 10.

III. Logical Operators

Python Logical Operators are used to combine two or more conditions and perform logical operations on them. The following are the three logical operators in Python:

These operators are used to perform logical operations on the operands and return a Boolean value.

The 'and' operator returns True if both operands are True, otherwise, it returns False.

The 'or' operator returns True if either of the operands is True, otherwise, it returns False.

The 'not' operator returns the opposite of the operand.

Let's look at depth with some examples to understand how these operators work.

The and operator returns True if both operands are true and returns False if either one of the operands is false.

Here's the truth table for the and operator:

Operand 1Operand 2Result

Here's an example code snippet:

In this example, the and operator is used to check if x is smaller than both y and z . If this condition is true, then the statement "x is the smallest number" is printed.

The OR operator in Python is represented by or . It is a logical operator that returns True if at least one of the operands is True , and False otherwise. Here are the possible truth tables for the OR operator:

Operand 1Operand 2Result

Here's an example of using the OR operator in Python:

In this example, x is not greater than y or z , so the output will be x is not greater than y or z .

The NOT operator is a unary operator that negates the value of its operand. In Python, the NOT operator is represented by the keyword "not".

The NOT operator returns True if its operand is False, and vice versa. Here's an example:

In this example, the value of x is True. However, the NOT operator negates the value of x and returns False.

IV. Assignment Operators

Have you ever wanted to quickly assign or modify a value in Python without writing a lot of code? That's where assignment operators come in handy! They allow you to perform an operation on a variable and assign the result back to the same variable in a single step. In this section, we will explore the different types of assignment operators in Python.

a. Simple Assignment Operator

The simple assignment operator in Python is denoted by the equal sign "=" and is used to assign a value to a variable. The syntax for simple assignment is:

where variable is the name of the variable and value is the value to be assigned to the variable.

For example, the following code assigns the value 10 to the variable x :

After executing this code, the variable x will have the value 10 .

b. Arithmetic Assignment Operators

Arithmetic assignment operators are a shorthand way of performing arithmetic operations and assignment at the same time. These operators include:

+= : adds the value of the right operand to the value of the left operand and assigns the result to the left operand.

-= : subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

*= : multiplies the value of the left operand by the value of the right operand and assigns the result to the left operand.

/= : divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

%= : computes the modulus of the value of the left operand and the value of the right operand, and assigns the result to the left operand.

//= : performs floor division on the value of the left operand and the value of the right operand, and assigns the result to the left operand.

**= : raises the value of the left operand to the power of the value of the right operand, and assigns the result to the left operand.

These operators can be used with numeric values and variables of numeric types, such as integers and floating-point numbers.

In each of the above examples, the arithmetic operation and the assignment operation are performed at the same time using the shorthand arithmetic assignment operator.

c. Bitwise Assignment Operators

Bitwise assignment operators are used to perform a bitwise operation on a variable and then assign the result to the same variable. The bitwise assignment operators include:

&= : Performs a bitwise AND operation on the variable and the value on the right, then assigns the result to the variable.

|= : Performs a bitwise OR operation on the variable and the value on the right, then assigns the result to the variable.

^= : Performs a bitwise XOR operation on the variable and the value on the right, then assigns the result to the variable.

<<= : Performs a left shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

>>= : Performs a right shift operation on the variable by the number of bits specified on the right, then assigns the result to the variable.

d. Logical Assignment Operators

There are no specific "Logical Assignment Operators" in Python, as the logical operators and , or , and not are already used for combining and negating boolean expressions. However, it is possible to use logical operators in combination with assignment operators to create compound expressions, such as x += y or z , which assigns the value of y to x if y is truthy, or the value of z otherwise.

e. Comparison Assignment Operators

There is no such thing as "Comparison Assignment Operators". The term "comparison operator" refers to operators that compare two values and return a boolean value (True or False), while "assignment operator" refers to operators that assign a value to a variable.

However, there are shorthand ways to perform a comparison and assign the result to a variable in a single line of code. For example:

x = 10 if a > b else 20 : This assigns the value 10 to x if a > b is True, otherwise it assigns the value 20.

x += 1 if a == b else 2 : This adds 1 to x if a == b is True, otherwise it adds 2.

x *= 2 if a < b else 3 : This multiplies x by 2 if a < b is True, otherwise it multiplies it by 3.

V. Bitwise Operators

Bitwise operators are used to manipulate the individual bits of binary numbers. In Python, bitwise operators can be applied to integers. The bitwise operators take two operands and operate on them bit by bit to produce a result. There are six bitwise operators in Python: AND, OR, XOR, NOT, left shift, and right shift. These operators are commonly used in low-level programming, such as device driver development and network packet processing.

a. Bitwise AND

The bitwise AND operator is represented by the & symbol in Python. It performs a logical AND operation on each corresponding bit of its operands. If both bits are 1, the resulting bit is 1. Otherwise, the resulting bit is 0.

In this example, a and b are two integers represented in binary. The & operator is used to perform a bitwise AND operation on the two numbers, resulting in the binary number 0010 , which is equivalent to the decimal number 2. The resulting value is assigned to the variable c .

b. Bitwise OR

Bitwise OR is another binary operator that operates on two integers and performs a bitwise OR operation on their binary representations. The resulting binary representation is converted back to an integer.

The syntax for the bitwise OR operator is the pipe symbol | . For example, a | b performs a bitwise OR operation on a and b .

In the above example, the binary OR operation on a and b results in 0011 1101 , which is equal to 61 in decimal representation.

c. Bitwise XOR

Bitwise XOR (exclusive OR) operator is represented by the symbol ^ in Python. The operator returns a binary number that has a 1 in each bit position where the corresponding bits of either but not both operands are 1.

For example, let's say we have two variables a = 13 and b = 17 . The binary representation of 13 is 1101 and the binary representation of 17 is 10001 . Now, let's perform the bitwise XOR operation on these two variables:

In the above example, the resulting binary number is 11000 , which is equivalent to the decimal number 24 . Therefore, the value of the variable c will be 24 .

Here is another example that demonstrates the use of bitwise XOR:

In this example, we first define a and b as binary numbers using the 0b prefix. We then perform the bitwise XOR operation on these two numbers and store the result in c . The resulting binary number is 0b110 , which is equivalent to the decimal number 6 . Therefore, the value of the variable c will be 6 .

d. Bitwise NOT

Bitwise NOT is a unary operator in Python that flips the bits of a number. It is represented by the tilde (~) symbol. When applied to a binary number, the Bitwise NOT operator returns the complement of the number.

In the above code, the value of x is 7, which is represented in binary as 0000 0111. When we apply the Bitwise NOT operator (~) to x , it flips all the bits of the number, resulting in 1111 1000. The output is in two's complement form, which is the way negative numbers are represented in binary.

VI. Membership Operators

Membership operators are used to test if a sequence is present in an object. In Python, we have two membership operators:

in : Evaluates to True if the sequence is present in the object.

not in : Evaluates to True if the sequence is not present in the object.

These operators are typically used with strings, lists, tuples, and sets to check if a certain element or a sequence of elements is present in them.

VII. Identity Operators

Identity Operators are used to compare the memory locations of two objects. There are two identity operators in Python:

is - Returns True if both variables are the same object.

is not - Returns True if both variables are not the same object.

In this example, x and y have the same values, but they are not the same object. z is assigned the same memory location as x , so x and z are the same object. The is operator returns True when comparing x and z , but False when comparing x and y . The is not operator returns False when comparing x and z , but True when comparing x and y .

Last updated 1 year ago

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Augmented Assignment Operators in Python

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

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

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

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

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

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

Example:  

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming
  • Best 10 IPTV Service Providers in Germany
  • Python 3.13 Releases | Enhanced REPL for Developers
  • IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
  • Best SSL Certificate Providers in 2024 (Free & Paid)
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Guru99

Operators in Python – Logical, Arithmetic, Comparison

Logan Young

What are Logical Operators in Python?

Logical Operators in Python are used to perform logical operations on the values of variables. The value is either true or false. We can figure out the conditions by the result of the truth values. There are mainly three types of logical operators in python: logical AND, logical OR and logical NOT. Operators are represented by keywords or special characters.

Arithmetic Operators

Arithmetic Operators perform various arithmetic calculations like addition, subtraction, multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic calculation in Python like you can use the eval function, declare variable & calculate, or call functions.

Example : For arithmetic operators we will take simple example of addition where we will add two-digit 4+5=9

Similarly, you can use other arithmetic operators like for multiplication(*), division (/), substraction (-), etc.

Comparison Operators

Comparison Operators In Python compares the values on either side of the operand and determines the relation between them. It is also referred to as relational operators. Various comparison operators in python are ( ==, != , <>, >,<=, etc.)

Example : For comparison operators we will compare the value of x to the value of y and print the result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns false.

Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)

Python Assignment Operators

Assignment Operators in Python are used for assigning the value of the right operand to the left operand. Various assignment operators used in Python are (+=, – = , *=, /= , etc.).

Example : Python assignment operators is simply to assign the value, for example

Example of compound assignment operator

We can also use a compound assignment operator, where you can add, subtract, multiply right operand to left and assign addition (or any other arithmetic function) to the left operand.

  • Step 1: Assign value to num1 and num2
  • Step 2: Add value of num1 and num2 (4+5=9)
  • Step 3: To this result add num1 to the output of Step 2 ( 9+4)
  • Step 4: It will print the final result as 13
  • Dictionary in Python with Syntax & Example
  • Python Rename File and Directory using os.rename()
  • 10 BEST Python IDE & Code Editors for Windows (2024)

Logical Operators or Bitwise Operators

Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.

  • For AND operator – It returns TRUE if both the operands (right side and left side) are true
  • For OR operator- It returns TRUE if either of the operand (right side or left side) is true
  • For NOT operator- returns TRUE if operand is false

Example : Here in example we get true or false based on the value of a and b

Membership Operators

These operators test for membership in a sequence such as lists, strings or tuples. There are two membership operators that are used in Python. (in, not in). It gives the result based on the variable present in specified sequence or string

Example : For example here we check whether the value of x=4 and value of y=8 is available in list or not, by using in and not in operators.

  • Declare the value for x and y
  • Declare the value of list
  • Use the “in” operator in code with if statement to check the value of x existing in the list and print the result accordingly
  • Use the “not in” operator in code with if statement to check the value of y exist in the list and print the result accordingly
  • Run the code- When the code run it gives the desired output

Identity Operators

Identity Operators in Python are used to compare the memory location of two objects. The two identity operators used in Python are (is, is not).

  • Operator is: It returns true if two variables point the same object and false otherwise
  • Operator is not: It returns false if two variables point the same object and true otherwise

Following operands are in decreasing order of precedence.

Operators in the same box evaluate left to right

Operators (Decreasing order of precedence) Meaning
** Exponent
*, /, //, % Multiplication, Division, Floor division, Modulus
+, – Addition, Subtraction
<= < > >= Comparison operators
= %= /= //= -= += *= **= Assignment Operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
  • Declare the value for variable x and y
  • Use the operator “is” in code to check if value of x is same as y
  • Next we use the operator “is not” in code if value of x is not same as y
  • Run the code- The output of the result is as expected

Operator Precedence

The operator precedence determines which operators need to be evaluated first. To avoid ambiguity in values, precedence operators are necessary. Just like in normal multiplication method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the answer is 23, to change the order of precedence we use a parentheses (3+4)*5, now the answer is 35. Precedence operator used in Python are (unary + – ~, **, * / %, + – , &) etc.

  • Declare the value of variable v,w
z
  • Now apply the formula and run the code
  • The code will execute and calculate the variable with higher precedence and will give the output

Python 2 Example

Above examples are Python 3 codes, if you want to use Python 2, please consider following codes

Operators in a programming language are used to perform various operations on values and variables. In Python, you can use operators like

  • There are various methods for arithmetic calculation in Python as you can use the eval function, declare variable & calculate, or call functions
  • Comparison operators often referred as relational operators are used to compare the values on either side of them and determine the relation between them
  • Python assignment operators are simply to assign the value to variable
  • Python also allows you to use a compound assignment operator, in a complicated arithmetic calculation, where you can assign the result of one operand to the other
  • There are two membership operators that are used in Python. (in, not in).
  • It gives the result based on the variable present in specified sequence or string
  • The two identify operators used in Python are (is, is not)
  • It returns true if two variables point the same object and false otherwise
  • Precedence operator can be useful when you have to set priority for which calculation need to be done first in a complex calculation.

You Might Like:

Top Python Interview Questions and Answers (PDF) for %currentyear%

C# Corner

  • TECHNOLOGIES
  • An Interview Question

Python

Introduction to Python Operators

arithmetic assignment operators in python

  • Baibhav Kumar
  • Aug 30, 2024
  • Other Artcile

This article explains Python operators, covering arithmetic, comparison, logical, bitwise, membership, identity, and operator overloading. It includes examples for each, emphasizing their importance in performing operations and comparisons.

In Python, operators are symbols that tell the program to perform specific operations on values or variables. They help you add numbers, compare values, or manipulate data. There are different types of operators, like those for math, comparing things, working with bits, and even creating custom actions. In this guide, we'll break down these operators into simple explanations so you can easily understand how they work.

Python Arithmetic Operators

Arithmetic operators provide a set of operators to perform basic mathematical operations:

  • Addition (+): This operator adds two values together.
  • Subtraction (-): Subtracts one value from another.
  • Multiplication (*): Multiplies two values.
  • Division (/): Divides one value by another, resulting in a floating-point number.
  • Floor Division (//): Divides two values and returns the largest integer less than or equal to the result.
  • Exponentiation (**): Raises one value to the power of another.
  • Modulus (%): Returns the remainder after dividing one value by another.

Python Arithmetic Operators Output

Python Comparison Operators

Comparison operators help compare values and return either True or False. These operators include:

  • Greater Than (>): Checks if the value on the left is greater than the value on the right.
  • Less Than (<): Check if the value on the left is less than the value on the right.
  • Equal To (==): Checks if both values are equal.
  • Not Equal To (!=): Checks if both values are not equal.
  • Greater Than or Equal To (>=): Check if the value on the left is greater than or equal to the value on the right.
  • Less Than or Equal To (<=): Check if the value on the left is less than or equal to the value on the right.

Comparison operators are vital for controlling program flow, particularly in decision-making scenarios like if statements and loops.

Python Comparison Operators

Python Logical Operators

Python logical operators are used to perform logical operations on boolean values, returning either True or False. They are primarily used in conditional statements to combine or negate conditions.

  • and: Returns True if both operands are True; otherwise, it returns False.
  • or: Returns True if at least one of the operands is True; returns False only if both are False.
  • not: Negates the boolean value; if the value is True, it returns False, and vice versa.

Logical operators are used to create complex conditions, enabling more flexible and sophisticated decision-making in programs.

Python Logical Operators

Python Bitwise Operators

Bitwise operators in Python work at the bit level, meaning they perform operations on the binary representation of numbers. These operators manipulate individual bits of data, which can be useful for low-level programming tasks like handling binary data or optimizing performance.

  • & (AND): Compares each bit of two numbers. If both bits are 1, the result is 1. Otherwise, it's 0.
  • | (OR): Compares each bit of two numbers. If at least one bit is 1, the result is 1. If both are 0, the result is 0.
  • ^ (XOR): Compares each bit of two numbers. If the bits are different, the result is 1. If they are the same, the result is 0.
  • ~ (NOT): Flips all the bits of a number, turning 1s into 0s and 0s into 1s.
  • << (Left Shift): Shifts the bits of a number to the left by a specified number of positions, effectively multiplying the number by powers of two.
  • >> (Right Shift): Shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by powers of two.

Bitwise operators are often used in scenarios where performance and memory efficiency are critical, such as in systems programming, cryptography, or data compression.

Python Bitwise Operators

Python Membership Operators

Membership operators in Python are used to check if a value is part of a sequence, such as a list, tuple, string, or set. These operators help determine whether a particular item exists within a collection.

  • in: This operator checks if a value exists in a sequence. If the value is found, it returns True; otherwise, it returns False.
  • not in: This operator checks if a value does not exist in a sequence. If the value is not found, it returns True; otherwise, it returns False.

Membership operators are commonly used in conditions or loops to verify the presence or absence of elements in data structures like lists, strings, or dictionaries. For example, you might check if a user’s input exists in a predefined list of valid options.

Python Membership Operators

Python Identity Operators

Identity operators in Python are used to compare the memory locations of two objects. They check whether two variables refer to the same object in memory, rather than just having equal values.

  • is: This operator returns True if two variables point to the same object in memory, meaning they are identical.
  • is not: This operator returns True if two variables do not point to the same object in memory, meaning they are not identical.

Identity operators are helpful when you need to check if two variables reference the same object, particularly when dealing with mutable objects like lists or dictionaries. For instance, in cases where you want to avoid unintentional modifications to a shared object.

Python Identity Operators

Operator overloading in Python allows you to change how operators like +, -, and * work with your custom objects. Normally, these operators work with basic data types like numbers, but with operator overloading, you can define what they do when applied to your objects.

  • Customizing Operators: You can change how operators like +, -, and == behave when used with your objects by defining special methods in your class.
  • Make Objects Behave Like Built-in Types: This allows your objects to interact with operators in a way that feels natural, just like numbers or strings do.
  • Simplifies Complex Data Structures: It is helpful for creating more intuitive code when working with complex objects like matrices, vectors, or custom data types.

Python Operator Overloading Example 2 Output

To write effective Python code, it's important to understand different operators, like those for math, logic, bitwise operations, checking membership, and comparing identity. Python also lets you extend these operators to work with custom objects, making the language more powerful. Whether you're doing calculations or comparing items, operators are a key part of Python that you'll use often.

  • Operator Overloading

C# Corner Ebook

Python Overview

Defining a symbolic syntax for referring to assignment targets

FWIW, aside from the potential performance hit, mutating f_locals should work reliably in 3.13+ due to PEP 667 – Consistent views of namespaces | peps.python.org

I actually had thought about that too but the problem was that we can’t use a soft keyword for it since there is no way syntactically to distinguish the soft keyword from a variable name, and if we make it a hard keyword then it would be too much of a breaking change since the keyword would have to be a commonly used English word that likely collides with variable names in existing code base.

But now it occurred to me that we can just make the magic placeholder a dunder so no existing code base should be using it. As for the name itself, I think __target__ would be good:

The code now looks a lot less cryptic/Perlish to me.

Behind the scene though, __target__ would be a hard keyword rather than a variable name. It won’t be looked up in the namespace but is rather expanded at compilation time.

Similarlly, @'' can be made into a new hard keyword such as __target_name__ to look less cryptic.

Yup, same here. I almost wrote my own POV comparing this to walrus, but decided not to half-way through realising that it isn’t going to be of much use given this is currently at contemplative stage.

And it took me a fair bit of time to stop abusing walrus, however I am happy about it having finally learned to use it responsibly.

The notation, I think is decent - visually and semantically. And been wandering what was the reason for @ for mat_mult - never seen @ used anywhere in math before. There was quite a good example for this - matlab . Can’t do exactly the same, but retaining * might have been better, e.g. \* . So that @ could be used for something more appropriate, e.g. this. But given status quo, I don’t think it would fly. So 2 options:

  • Change matrix multiplication operator. Been thinking about how hard of a sell this would be. I know that no-one would want to do it. All the backwards compatibility etc, but has anyone analysed compound cost of a bad decision? And the fact that the earlier the correction is done, the smaller the damage? I am talking in general, not only this specific case. I mean surely if the goal is best possible version of Python, (as opposed to pleasing unsatisfied and reluctant to adapt users), big breaks of backwards compatibility are inevitable

  • Pick something else for this. One idea would be to go with bash-like argument syntax, but with pythonic slicing:

Or maybe even star, given it being used in expansions:

Could also incorporate string-like formatting:

Alternatively, use * for strings, @ for values (similar to what bash does).

We have space-separated names as arguments in the standard library too, such as collections.namedtuple and enum.Enum :

Using my dunder keyword idea above, it can become:

The matrix multiplication PEP did cover that: PEP 465 – A dedicated infix operator for matrix multiplication | peps.python.org

The __target__ dunder idea is interesting, as it doesn’t provide brevity gains in most cases, but does provide the benefit of avoiding repeated evaluation.

I suspect code that assigns to identifiers would continue to be better off just using the target identifier directly, but attribute access, subscripting, slicing, and tuple assignment could still see some utility.

__target_text__ could replace @'' for both identifier assignment and tuple assignment ( __target_name__ wouldn’t match the latter use case)

I doubt you could reasonably use that form to map function parameters to local variables of the same name, though.

Sounds good indeed. With the name __target_text__ we wouldn’t have to worry about a plural form.

I don’t see why not. We can name the new keyword that forwards local variables to function parameters of the same names, __same__ . The compiler with access to AST can clearly tell which keyword argument a ast.Same node belongs to and produces bytecode that loads the local variable of that name for the argument accordingly:

This is really a completely separate proposal from the assignment target placeholder proposal though, and should be discussed about in a separate thread (perhaps in the PEP-736 thread, in which I have now made a post ).

Yeah the loss of brevity does take away the utility of this idea in cases of a single identifier, particularly as an alternative to PEP-736, where parameter names are always single identifiers.

I agree that we should focus more on its utility for more complex assignment targets.

Going further on the SymPy tangent, I can brainstorm a possible story of how to get that by more straightforward extensions of existing syntax.

The hardest hurdle in this story is the first step. Suppose Python somehow gets dict destructuring assignment:

Sympy then defines a helper whose __getitem__ gives out symbols (if it doesn’t already have it):

By this time PEP 736 has been accepted, and its syntax gets extended to dict destructuring:

(Is that Perlish?) (Is it the direction Python is going?)

People now start writing {Point2D=} = namedtuplemaker('x', 'y') 
 which isn’t straightforward to read today, but maybe it’s better than with @'' ?

“Whatever, we have to pick something.”

If you’re going to give the target a full identifier, you might as well provide the name rather than hardcoding it

some.nested.attribute as x = x.lower()

This doesn’t require new tokens, and the syntax mimics what we have in the match statement (which tries to overlap assignment syntax). It definitely looks more python than perl (keywords vs symbols)

Same as your proposal, this doesn’t cover argument pushing, but only double evaluation (at this point it isn’t much more than a glorified walrus). This is also missing a syntax to capture the name of the target as a str. I’m not sorry convinced on that but I think you could do (a, b, c) as (_, names) = simpy.symbols(names) .

I’m not super sold into this either, but hopefully putting this idea on the table may help someone find a better proposal

For me a big part of this feature was not needing to assign a name for this specific “some.nested.attribute”, so I’m not really sure I like the as proposal

A benefit can be that if the name persists, it can be used more times in the code that follows the assignment.

Quite like it, one issue though:

While naming tuple thing obstruct such intuitive expansion. However might not be an issue as one can always slice it on the right hand side. However, it does not seem very elegant nevertheless. Maybe something like:

This would be the 2nd method that allows extracting identifier name from identifier. First one being f{a=} . However, it would also be the second one which compulsory does more than that, while simple straight forward way to do this still does not exist, namely something similar to C# nameof , that would do exactly that without needing to evaluate anything. Thinking if I could hack this for it:

Interesting idea, for sure.

What I don’t like about it is that it encourages a coding style that binds multiple different values to the same name. Inevitably, one of those values is going to be badly named.

E.g. you might see

At point (1) , the value of sth.this_must_be_lowercase violates requirements: The value is in fact not guaranteed lowercase.

I would rather it was written such that different values have different names. Like this:

This is a fairly marginal coding style distinction, and not something I would usually make a fuss about. But I do think the latter style is marginally better, and it would be unfortunate to add syntax that encourages the former style.

I am -1 to using @ for any of the purposes outlined here, but +1 to long_name as x = foo(x) being sugar for long_name = foo('long_name') .

It should work the same for dotted names and tuples, i.e. a.b. c as x = foo(x) would be sugar for a.b. c = foo('a.b.c') and (a,*b, c) as x = foo(x) would be sugar for (a,*b, c) = foo('a, *b, c') - note my intentional inconsistent whitespace to demonstrate that whitespace ought to be normalised when generating the string representation.

Outer parens in tuple assignment would be required to make it clearly unambiguous; a, b as x would be a syntax error but might later (as a separate proposal) be allowed in order to let x be 'b' . I’m -0 on allowing this from the beginning; probably better to see how the general idea works out before adding in this complication.

I would prefer that this feature be limited to passing the string representation of some name to a function (or otherwise using it in an expression), as that’s an actually important use case (namedtuple, TypeVar). My dislike of using this for accessing the target object itself is pretty much what @AndersMunch has already explained: it’s far less confusing to just use a regular ol’ assignment for that.

“Python is not Perl” indeed!

IMO another good (also English-specific) mnemonic is “at rhymes with that”, and reading @ as “that” is a pretty natural way to speak the statement.

I suspect that I’m in the minority here but I personally found figuring out what assignment target means (i.e. whatever’s on the the left of the = operator) to be more confusing than mapping a punctuation character to the words assignment target . So perlish or not, to me eliminating @ isn’t really fixing anything.

TBH, in this version of the proposal you don’t get much for TypeVar . You are changing:

if you make up a name and copy it over you’re getting more verbosity than the original and still have repetition. Same for namedtuples. That’s whay I didn’t worry too much about the string representation when I covered this, I was more focused on Alyssa’s idea of avoiding re-evaluation of attribute accesses/slicing.

We have __set_name__ so descriptors know their own name. Have we thought of extending __set_name__ to work on objects? Or perhaps there is a reason why it’s not done? I think it would be neat if objects could capture the lhs as a name like in descriptors

Allowing __target__ on the LFS would make the syntax ambiguous when there is also __target__ on the RHS:

Does __target__[:2] on the RHS become foo[:2] or foo[2:][:2] ?

Assignment to a name does not modify an object in-place. It merely sets the name on the LHS to a new reference to the object on the RHS. So __target__ = hex(v) would just set the local name v to a new object for that iteration rather than updating the entry in mydict , which will still hold a reference to the original value.

Alyssa’s elaborate description of how to deal with different assignment targets may seem confusing, but at its heart it’s something quite simple and familiar: It’s how augmented assignment works.

Just like a.b[c].d += 1 only evaluates a.b[c] once, a.b[c].d = @ + 1 would also evaluate a.b[c] just once.

CS 2110: Object-Oriented Programming and Data Structures

Assignment 1.

A1 consists of a series of exercises to help you transition to procedural programming in the Java language. The problem-solving elements are at the level of lab exercises from CS 1110/1112. The assignment comes bundled with a thorough test suite, so you will know when you have implemented each method’s specifications correctly.

You must work on this assignment independently (no partners)—we want to ensure that every student can write, test, and submit Java code on their own. For this reason, we are also grading this assignment for mastery ; if a grader identifies mistakes that you didn’t catch yourself, you may resubmit once to correct them without penalty.

Learning objectives

  • Author Java code in the IntelliJ IDEA IDE.
  • Employ operations on Java’s primitive types ( boolean , int , double ) and strings to solve high-level problems.
  • Employ Java control structures ( if , for , while ) to implement algorithms for solving high-level problems.
  • Select relevant mathematical functions from Java’s standard library by referencing JavaDoc pages.
  • Verify the correctness of implementations by running JUnit test cases.
  • Adopt good programming style to facilitate readability and maintenance.
  • Witness examples of precise method specifications that separate “what” from “how”.

If you are worried that these exercises seem a bit dry and mathematical, that is a consequence of restricting ourselves to Java’s primitive types (which are mostly numbers). Once we get to object-oriented programming in A2, the problem domains will become richer.

Collaboration policy

This assignment is to be completed as an individual. You may talk with others to discuss Java syntax, debugging tips, or navigating the IntelliJ IDE, but you should refrain from discussing algorithms that might be used to solve the problems, and you must never show your in-progress or completed code to another student. Consulting hours are the best way to get individualized assistance at the source code level.

Frequently asked questions

There is a pinned post on Ed where we will post any clarifications for this assignment. Please review it before asking a new question in case your concern has already been addressed. You should also review the FAQ before submitting to see whether there are any new ideas that might help you to improve your solution.

I. Getting started

You already know at least one procedural language (e.g. Python) with which you should be able to solve the problems on this assignment. If that language is not Java, then the goal is for you to become comfortable with procedural Java syntax, as it compares with what you already know, by practicing it in targeted problems. Start by reading transition to Java on the course website, which provides a focused translation guide between Python, MATLAB, and Java.

Download the release code from the CMSX assignment page; it is a ZIP file named “a1-release.zip”. Decide where on your computer’s disk you want your project to be stored (we recommend a “CS2110” directory under your home or documents folder), then extract the contents of the ZIP file to that directory. Find the folder simply named “a1” (depending on your operating system, this may be under another folder named “a1-release”); its contents should look like this:

We assume you have already followed the setup instructions for IntelliJ, possibly in your first discussion section. It is important that JDK 21 has been downloaded.

In IntelliJ, select File | Open , then browse to the location of this “a1” directory, highlight “a1”, and click OK . IntelliJ may ask whether you want to open the project in the same window or a new one; this is up to you, noting that if you choose the same window, whatever project you previously had open (e.g. a discussion activity or old assignment) will be closed.

Please keep track of how much time you spend on this assignment. There is a place in “reflection.txt” for reporting this time, along with asserting authorship.

II. Working with the provided code

Specifications and preconditions.

A recurring theme in this course is distinguishing between the roles of client and implementer . For methods, a client is someone who calls a method, and the implementer is someone who writes the method’s body. Although you might act both as client and implementer in a small project, ideally the two roles have no knowledge of one another, so you should keep track of which role you are currently in and “split your brain” accordingly. For most of this assignment you will be in the implementer role relative to the assignment’s methods.

Each method is accompanied by a specification in a JavaDoc comment. As the implementer, your job is to write a method body that fulfills that specification. Specifications may include a precondition phrased as a “requires” clause. As the implementer, you can assume that the precondition is already satisfied. You do not have to attempt to check the precondition or to handle invalid arguments in any special way. It would be the responsibility of clients to ensure that they do not violate such conditions.

For example, if a specification contains the precondition “ nTerms is non-negative”, then the client is never permitted to pass negative arguments to the function. If the client nonetheless does so, the specification promises nothing about the result. Specifically, the specification does not promise that the function will check for non-negativity, and the specification does not promise that any kind of error will be produced. That means the implementer has an easy job: they can simply ignore the possibility of negative arguments.

You might have been taught in previous programming classes that implementers must always check preconditions, or must always produce an error when a precondition is violated. Those are useful and important defensive programming techniques! (And we will see how to employ them in Java soon.) But the point we are making here is that they are not mandated by a “requires” clause. So in this assignment, you do not have to use such techniques, and it’s likely to be easier for you to omit them entirely.

Replacing method “stubs”

The body of each method initially looks like this:

This is a placeholder —it allows the method to compile even though it doesn’t return a value yet, but it will cause any tests of the method to fail. You should delete these lines as the first step when implementing each method. (We’ll discuss the meaning of these lines later in the course when we cover exceptions, objects, and so forth.)

Use the TODO comments to guide you to work that still needs to be done. As you complete each task, remove the comment line with the TODO since it doesn’t need doing anymore! Temporary comment prefixes like TODO and FIXME are a convenient way to keep track of your progress when writing and debugging code; IntelliJ will even track them for you in its TODO window .

Finally, some method bodies contain comments with “implementation constraints.” These are not part of the specification, as they do not affect potential clients. Instead, they are requirements of the assignment to ensure that you get practice with the necessary skills. Violating these constraints will not cause unit tests to fail, but points will be deducted by your grader, so make sure you obey them.

Test cases for each method are in “tests/cs2110/A1Test.java”. You are encouraged to read the test suites to see what corner cases are considered, but you do not need to add any tests of your own for this assignment.

To run a test case, click the green arrow to the left of the method name, then select “Run”; the results will be shown at the bottom of the screen. To run all test cases, use the arrow to the left of the class name ( A1Test ). If a test fails with a yellow “X”, that means it returned the wrong result. By reading the messages in the output window, you should be able to determine which case failed and what your implementation computed instead. If it fails with a red “!”, that means it encountered an error (or you forgot to delete the placeholder throw line).

Take note of the style of these tests. While you may not understand all of the Java syntax yet, you should see that related tests are grouped together and given descriptive names. This makes it easier to debug your code, since your IDE will clearly show which scenarios are behaving as expected and which are not. You are expected to adopt this style for your own tests on future assignments.

III. Assignment walkthrough

Implement the methods one at a time. As soon as you implement one, run the corresponding test case to verify your work. Do not modify any method signatures (or return types or throws clauses)—not only would that change the class type we provided, but it would make it impossible for our autograder to interoperate with your code. And do not leave print statements in your final submission unless the method specification mentions printing output as a side effect.

Each of the numbered exercises below references a section of the Supplement 1 chapter of the primary course textbook, Data Structures and Abstraction with Java , 5th edition, to which you should have access in Canvas through the “Course Materials” link. That supplement is designed to help students who know how to program, but are new to Java. It is a great resource for making the transition to Java.

1. Regular polygons

[Textbook: S1.29: The Class Math ]

The area of a regular polygon with n sides of length s is given by the formula:

$$A = \frac{1}{4} s^2 \frac{n}{\tan(\pi/n)}$$

Implement this formula. You will need one or more math functions and/or constants from Java’s standard library. Skim the JavaDoc page for the static methods in the Math class to learn which functions are available. Remember that a Math. prefix is required when calling them (so to compute the absolute value of -5, you would write Math.abs(-5) ).

Take some time to explore these functions and get a feel for how Java’s standard library is documented. The functions you are most likely to use later in the course include: abs() , min() , max() , sqrt() , pow() , and the trigonometric functions.

Note: methods dealing with dimensionful quantities (like length and area) should always say something about what units (e.g. meters, acres) those quantities are measured in. In this case, the formula makes no assumptions about units, so the specification simply tells the client that the units of the output are compatible with the units of the input.

2. Collatz sequence

[Textbook: S1.59: The while Statement]

The Collatz conjecture is a fun piece of mathematical trivia: by repeatedly performing one of two simple operations on a positive integer (depending on whether it is even or odd), you always seem to get back to 1. The rules for determining the next number in the sequence are:

  • If the last number was even, divide it by 2.
  • If the last number was odd, multiply it by 3 and add 1.

Our objective is to sum all of the terms in the sequence starting from a given “seed” number until we get to 1. This involves indefinite iteration , and you should use a while loop for this.

This is also a chance to practice problem decomposition and defining new methods. Declare and implement a method named nextCollatz() that takes one int argument and returns an int value according to the given specification. When you have done this, remove the TODO and uncomment the relevant test case in A1Test (it was commented out because the test case will not compile unless that method is at least declared, preventing you from running tests for other methods in the suite). Tip: there is an IntelliJ keyboard shortcut for commenting and uncommenting whole selections of code; can you find it?

3. Median of three

[Textbook: S1.38: The if-else Statement]

The median value of a collection of numbers is the value that would be in the middle if the collection were sorted. A special case is median-of-three voting , which is used in fault-tolerant systems to decide how to proceed when not all components agree. This small function is actually one of the most commonly-run procedures in SpaceX’s flight software, helping it determine which sensors and commands to trust dozens of times per second.

You need to develop an algorithm for determining which of three numbers is the middle value. The numbers could be in any order, and there could be duplicates. Use a chain of conditional statements ( if / else ), possibly nested, to find the middle value.

4. Interval overlaps

[Textbook: S1.41: Boolean Expressions]

Intervals are a useful abstraction when working with schedules. For example, if class meeting times are represented as intervals over the seconds of a day, then an overlap would imply that two classes conflict.

This exercise is designed to help you avoid a common “anti-pattern” among new programmers:

(here, expr is a Boolean expression, like x > 0 ). Remember that the conditions used in if statements are expressions that yield a boolean value and can be used anywhere a boolean value like true or false could be used. Therefore, the above code can (and should) be rewritten as:

Keeping this in mind, implement intervalsOverlap() using a single return statement.

5. Estimating pi

[Textbook: S1.61: The for Statement]

The Madhava-Leibniz series is an infinite sum of numbers that is related to π:

$$\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \ldots$$

Observe that the denominators of the terms are the sequence of odd integers and that the sign alternates between plus and minus.

By truncating this series after a finite number of terms, we get an approximation for π (though this particular formula requires many terms for even modest accuracy). Use a for -loop to evaluate this approximation for a specified number of terms (this is an example of definite iteration ). Recall that integer division in Java rounds down to another integer, so you may need to cast some numbers to a floating-point type when evaluating the fractions.

As a corner case, note that the sum of zero terms is 0.

6. Palindromes

[Textbook: S1.67: The Class String ]

With control structures and primitive types out of the way, it’s time to get some experience with our first aggregate type : String (an aggregate type is one that groups together multiple values, like how a String contains multiple char s). Strings get some special treatment in Java; while they are objects , they are immutable (their contents can’t be changed), which means they behave much like primitive values. And unlike other objects, they have their own literals and even an operator ( + for concatenation). But as a sequence of characters they are like arrays, giving you some early practice with algorithms that iterate over data.

A palindrome has the same sequence of characters when written backwards as when written normally. To examine the i th character in string s , use s.charAt(i) . The total number of characters in s is given by s.length() . In Java, the index of the first character is 0 , and the index of the last character is s.length() - 1 . The specifications for these methods are in the API documentation for String ; by calling them, you are now in the client role with respect to the String class.

7. Formatting messages

[Textbook: S1.70: Concatenation of Strings]

A common task in computing systems is to format information to be read by humans. The system may need to support translations in multiple languages, and sometimes words will change depending on the data being explained (e.g. singular vs. plural nouns, “a” vs. “an” depending on the following word, etc.). To manage this potential complexity, it is a good idea to move formatting logic into its own function (Java actually provides a sophisticated infrastructure for managing this in large applications, but that is beyond the scope of this course).

This exercise requires you to concatenate strings and to format numerical data as a string. There are several approaches you can take; the + operator is probably most convenient, but if you have used a format or printf feature in another language, you might be interested in String ’s format() method. This is also a good opportunity to get practice with Java’s ternary operator ?: , an awkward-to-read but extremely useful bit of syntax; use this to decide between the singular and plural forms of “item” without using an if -statement.

8. Making a program

Now it’s time to step into the client role. Add a main() method so that the A1 class can be run as a program. Find a way to use at least four of the methods in A1 in combination, then print the final result. Is is okay to be silly here! Ideas include:

  • Compute the sums of three Collatz sequences of your choice, then take their median; use this as the number of sides of a polygon. For the length of the polygon’s sides, use an estimate of π. Print the polygon’s area.
  • Compute the median of three numbers of your choice, then find the next number in the Collatz sequence after it. Use this as the number of items in an order, then determine whether that order’s confirmation message is a palindrome.

You can be creative here and provide arbitrary inputs as necessary, but all four methods must contribute somehow to the final result. For this assignment, you should hard-code your inputs, rather than expecting program arguments (in other words, ignore args ).

Your program’s printed output should be a complete sentence written in English. It should describe what final operation was performed, what its inputs were, and what the result was (the inputs and outputs should not be baked into the printed text; instead, you should print the values of program variables or expressions). For example, “The area of a polygon with 4 sides of length 0.5 m is 0.25 m^2.” When you run your program, make sure this is the only output (i.e., that there are no “debugging prints” in the other methods you are calling).

9. Reflecting on your work

Stepping back and thinking about how you approached an assignment (a habit called metacognition ) will help you make new mental connections and better retain the skills you just practiced. Therefore, each assignment will ask you to write a brief reflection in a file called “reflection.txt”. This file is typically divided into three sections:

  • Submitter metadata: Assert authorship over your work, and let us know how long the assignment took you to complete.
  • Verification questions: These will ask for a result that is easily obtained by running your assignment. (Do not attempt to answer these using analysis; the intent is always for you to run your program, possibly provide it with some particular input, and copy its output.)
  • Reflection questions: These will ask you write about your experience completing the assignment. We’re not looking for an essay, but we do generally expect a few complete sentences.

Respond to the four TODOs in “reflection.txt” (you can edit this file in IntelliJ).

IV. Scoring

This assignment is evaluated in the following categories (note: weights are approximate and may be adjusted slightly in final grading):

  • Submitted and compiles (25%)
  • Fulfills specifications (41%)
  • Complies with implementation constraints (25%)
  • Exhibits good code style (5%)
  • Responds to reflection questions (4%)

You can maximize the “fulfilling specifications” portion of your score by passing all of the included unit tests (don’t forget to uncomment the ones for nextCollatz() ). The smoketester will also run these tests for you when you submit so you can be sure that your code works as well for us as it does for you.

Formatting is a subset of style. To be on the safe side, ensure that our style scheme is installed and that you activate “Reformat Code” before submitting. Graders will deduct for obvious violations that detract from readability, including improper indentation and misaligned braces.

But beyond formatting, choose meaningful local variable names, follow Java’s capitalization conventions (camelCase), and look for ways to simplify your logic. If the logic is subtle or the intent of a statement is not obvious, clarify with an implementation comment.

V. Submission

Upload your “A1.java” and “reflection.txt” files to CMSX before the deadline. If you forgot where your project is saved on your computer, you can right-click on “A1.java” in IntelliJ’s project browser and select “Open In”, then your file explorer (e.g. “Explorer” for Windows, “Finder” for Mac). Be careful to only submit “.java” files, not files with other extensions (e.g. “.class”).

After you submit, CMSX will automatically send your submission to a smoketester , which is a separate system that runs your solution against the same tests that we provided to you in the release code. The purpose of the smoketester is to give you confidence that you submitted correctly. You should receive an email from the smoketester shortly after submitting. Read it carefully, and if it doesn’t match your expectations, confirm that you uploaded the intended version of your file (it will be attached to the smoketester feedback). Be aware that these emails occasionally get misclassified as spam, so check your spam folder. It is also possible that the smoketester may fall behind when lots of students are submitting at once. Remember that the smoketester is just running the same tests that you are running in IntelliJ yourself, so don’t panic if its report gets lost—we will grade all work that is submitted to CMSX, whether or not you receive the email.

(Note: it may take us a day after the assignment is released before the smoketester is up and running.)

IMAGES

  1. Operators in Python

    arithmetic assignment operators in python

  2. [Class 11] Operators: Performing Operations in Python

    arithmetic assignment operators in python

  3. What is an operator in Python ?

    arithmetic assignment operators in python

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

    arithmetic assignment operators in python

  5. Lùge adulte adverbe monticule division operators in python joue du piano cartouche froissé

    arithmetic assignment operators in python

  6. Python Operators Arithmetic Comparison Logical Bitwise Identity And

    arithmetic assignment operators in python

VIDEO

  1. Python_Tutorial_Part10

  2. L-5.4 Assignment Operators

  3. Operators in Python

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

  5. Vid 5- Operators in Python(Arithmetic, Relational, Assignment & Logical operators)

  6. DAY 2- PYTHON Operators In Details || Arithmetic Operators #nsclasses #dsssbtgtcomputerscience

COMMENTS

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

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

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

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

  5. Assignment Operators in Python

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

  6. Operators and Expressions in Python

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

  7. Arithmetic operators in Python (+, -, *, /, //, %, **)

    This article explains the arithmetic operators in Python. For numbers, such as integers ( int) and floating point numbers ( float ), you can perform basic arithmetic operations like addition, subtraction, multiplication, division, and exponentiation. For lists or strings, you can perform operations such as concatenation and repetition. Contents.

  8. Python Assignment Operators

    Login to Save. 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)

  9. Python Assignment Operators

    Operator Multiplication (*=) Operator Division (/=) Operator Modulus (%=) Operator Exponentiation (**=) Operator Floor Division (//=) Conclusion. Python assignment operators are one of the operator types and assign values to variables. We use arithmetic operators here in combination with a variable. Let's take a look at some examples.

  10. Python Assignment Operators

    Multiplication and Assignment Operator. The multiplication and assignment operator multiplies the right-side operand with the left-side operand, and then the result is assigned to the left-hand side operand. Below code is equivalent to: a = a * 2. In [1]: a = 3 a *= 2 print(a) 6.

  11. PDF Expressions in Python Operators and

    Concatenation and Repetition Augmented Assignment Operators. OperatorDescriptionExample+=Runs an augmented concatenati. operation on the target sequence.Mut. le sequences are updated in place.If the sequence is immutable, then a new sequence is created a. target name.seq_1 += se.

  12. 7. Basic Python Operators: Arithmetic, Comparison, and Assignment

    Diving into Python, one of the most popular programming languages today, it's crucial to grasp the basics. Operators in Python are the building blocks for performing calculations, making decisions, and storing values. I'll walk you through the essentials of arithmetic, comparison, and assignment operators, which are foundational for anyone looking to code in Python.

  13. Python Operators

    Python Identity Operators. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator. Description. Example. Try it. is. Returns True if both variables are the same object. x is y.

  14. Python Arithmetic Operators: A Complete Guide (50+ Examples)

    When adding variables, you can combine the addition operator (+) with the assignment operator (=) to form the addition assignment operator (+=). x += y. This is a shorthand for: x = x + y. For example: ... This concludes the comprehensive guide on all the arithmetic operators in Python. Thanks for reading.

  15. Python Operators (With Examples)

    1. Python Arithmetic Operators. Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example, sub = 10 - 5 # 5. Here, -is an arithmetic operator that subtracts two values or variables.

  16. Python Operators

    The Python programming language provides arithmetic operators that perform addition, subtraction, multiplication, and division. It works the same as basic mathematics. There are seven arithmetic operators we can use to perform different mathematical operations, such as: + (Addition) - (Subtraction) * (Multiplication)

  17. Python

    Python - Assignment Operators - 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. ... Python has the augmented assignment operators for all arithmetic and comparison operators. Python augmented assignment operators combines addition and ...

  18. Python Arithmetic Operators

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

  19. Arithmetic And Assignment Operators In Python

    Assignment operators assign values to variables, they work similar to chalk and blackboard, that is, act as a tool for assignment. For example, a = 10 here, '=' is an assignment operator it gives the variable 'a' which is on the left the value '10' which is on right. Let's look at these operators in detail. This is used to add numbers in a ...

  20. Operators

    Python provides a wide range of operators that can be used to perform arithmetic, logical, comparison, assignment, and bitwise operations. Understanding the different types of operators is crucial to writing efficient and error-free code in Python.

  21. Augmented Assignment Operators in Python

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

  22. Python Operators

    đŸ”„Edureka Python Developer Master's Course: https://www.edureka.co/masters-program/python-developer-trainingThis Edureka Video on Python Operators is a part ...

  23. Operators in Python

    Various comparison operators in python are ( ==, != , <>, >,<=, etc.) Example: For comparison operators we will compare the value of x to the value of y and print the result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we print the value as x>y, it actually compares the value of x to y and since it ...

  24. Introduction to Python Operators

    Python Arithmetic Operators. Arithmetic operators provide a set of operators to perform basic mathematical operations: Addition (+): This operator adds two values together. Subtraction (-): Subtracts one value from another. Multiplication (*): Multiplies two values. Division (/): Divides one value by another, resulting in a floating-point number.

  25. Defining a symbolic syntax for referring to assignment targets

    I suspect that I'm in the minority here but I personally found figuring out what assignment target means (i.e. whatever's on the the left of the = operator) to be more confusing than mapping a punctuation character to the words assignment target. So perlish or not, to me eliminating @ isn't really fixing anything.

  26. Assignment 1 (CS 2110 Fall 2024)

    Assignment 1. A1 consists of a series of exercises to help you transition to procedural programming in the Java language. The problem-solving elements are at the level of lab exercises from CS 1110/1112. The assignment comes bundled with a thorough test suite, so you will know when you have implemented each method's specifications correctly.