Python Operators Cheat Sheet

Author's photo

  • python basics
  • learn python

Discover the essential Python operators and how to effectively use them with our comprehensive cheat sheet. We cover everything from arithmetic to bitwise operations!

If you’ve ever written a few lines of Python code, you are likely familiar with Python operators. Whether you're doing basic arithmetic calculations, creating variables, or performing complex logical operations, chances are that you had to use a Python operator to perform the task. But just how many of them exist, and what do you use them for?

In this cheat sheet, we will cover every one of Python’s operators:

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

Additionally, we will discuss operator precedence and its significance in Python.

If you're just starting out with Python programming, you may want to look into our Python Basics Track . Its nearly 40 hours of content covers Python operators and much more; you’ll get an excellent foundation to build your coding future on.

Without further ado, let's dive in and learn all about Python operators.

What Are Python Operators?

Python operators are special symbols or keywords used to perform specific operations. Depending on the operator, we can perform arithmetic calculations, assign values to variables, compare two or more values, use logical decision-making in our programs, and more.

How Operators Work

Operators are fundamental to Python programming (and programming as a whole); they allow us to manipulate data and control the flow of our code. Understanding how to use operators effectively enables programmers to write code that accomplishes a desired task.

In more specific terms, an operator takes two elements – called operands – and combines them in a given manner. The specific way that this combination happens is what defines the operator. For example, the operation A + B takes the operands A and B , performs the “sum” operation (denoted by the + operator), and returns the total of those two operands.

The Complete List of Python Operators

Now that we know the basic theory behind Python operators, it’s time to go over every single one of them.

In each section below, we will explain a family of operators, provide a few code samples on how they are used, and present a comprehensive table of all operators in that family. Let’s get started!

Python Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division, exponentiation, and modulus. Most arithmetic operators look the same as those used in everyday mathematics (or in spreadsheet formulas).

Here is the complete list of arithmetic operators in Python:

+

Addition

2 + 3

5

-

Subtraction

5 - 2

3

*

Multiplication

4 * 6

24

/

Division

11 / 4

2.75

//

Floor division

11 // 4

2

%

Modulo ( )

11 % 4

3

**

Exponentiation ( )

2 ** 3

8

Most of these operators are self-explanatory, but a few are somewhat tricky. The floor division operator ( // ), for example, returns the integer portion of the division between two numbers.

The modulo operator ( % ) is also uncommon: it returns the remainder of an integer division, i.e. what remains when you divide a number by another. When dividing 11 by 4, the number 4 divides “perfectly” up to the value 8. This means that there’s a remainder of 3 left, which is the value returned by the modulo operator.

Also note that the addition ( + ) and subtraction ( - ) operators are special in that they can operate on a single operand; the expression +5 or -5 is considered an operation in itself. When used in this fashion, these operators are referred to as unary operators . The negative unary operator (as in -5 ) is used to invert the value of a number, while the positive unary operator (as in +5 ) was mostly created for symmetrical reasons, since writing +5 is effectively the same as just writing 5 .

Python Assignment Operators

Assignment operators are used to assign values to variables . They can also perform arithmetic operations in combination with assignments.

The canonical assignment operator is the equal sign ( = ). Its purpose is to bind a value to a variable: if we write x = 10 , we store the value 10 inside the variable x. We can then later refer to the variable x in order to retrieve its value.

The remaining assignment operators are collectively known as augmented assignment operators . They combine a regular assignment with an arithmetic operator in a single line. This is denoted by the arithmetic operator placed directly before the “vanilla” assignment operator.

Augmented assignment operators are simply used as a shortcut. Instead of writing x = x + 1 , they allow us to write x += 1 , effectively “updating” a variable in a concise manner. Here’s a code sample of how this works:

In the table below, you can find the complete list of assignment operators in Python. Note how there is an augmented assignment operator for every arithmetic operator we went over in the previous section:

=

Assign a value to a variable

x = 5

N/A

+=

Add and assign

x += 3

x = x + 3

-=

Subtract and assign

x -= 2

x = x - 2

*=

Multiply and assign

x *= 4

x = x * 4

/=

Divide and assign

x /= 2

x = x / 2

%=

Modulo and assign

x %= 3

x = x // 3

//=

Floor divide and assign

x //= 2

x = x % 2

**=

Exponentiate and assign

x **= 2

x = x ** 2

Python Comparison Operators

Comparison operators are used to compare two values . They return a Boolean value ( True or False ) based on the comparison result.

These operators are often used in conjunction with if/else statements in order to control the flow of a program. For example, the code block below allows the user to select an option from a menu:

The table below shows the full list of Python comparison operators:

==

Equal to

2 == 2

True

!=

Not equal to

3 != 4

True

Greater than

5 > 10

False

Less than

2 < 6

True

>=

Greater than or equal

4 >= 5

False

<=

Less than or equal

2 <= 2

True

Note: Pay attention to the “equal to” operator ( == ) – it’s easy to mistake it for the assignment operator ( = ) when writing Python scripts!

If you’re coming from other programming languages, you may have heard about “ternary conditional operators”. Python has a very similar structure called conditional expressions, which you can learn more about in our article on ternary operators in Python . And if you want more details on this topic, be sure to check out our article on Python comparison operators .

Python Logical Operators

Logical operators are used to combine and manipulate Boolean values . They return True or False based on the Boolean values given to them.

Logical operators are often used to combine different conditions into one. You can leverage the fact that they are written as normal English words to create code that is very readable. Even someone who isn’t familiar with Python could roughly understand what the code below attempts to do:

Here is the table with every logical operator in Python:

and

Returns True only if Boolean values are True; otherwise returns False

(10 > 5) and (10 < 50)

True

(True  ) and (True   )

or

Returns True if value is True; otherwise returns False

(1 < 0) or (1 < 100)

False

(False) or (True  ) 

not

Returns True if the value is False (and False if it is True)

not (10 > 5)

False

not (True  )

Note: When determining if a value falls inside a range of numbers, you can use the “interval notation” commonly used in mathematics; the expression x > 0 and x < 100 can be rewritten as 0 < x < 100 .

Python Identity Operators

Identity operators are used to query whether two Python objects are the exact same object . This is different from using the “equal to” operator ( == ) because two variables may be equal to each other , but at the same time not be the same object .

For example, the lists list_a and list_b below contain the same values, so for all practical purposes they are considered equal. But they are not the same object – modifying one list does not change the other:

The table below presents the two existing Python identity operators:

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 value is contained inside another object .

Objects that can contain other values in them are known as collections . Common collections in Python include lists, tuples, and sets.

in

Returns True if the value is in the collection

3 in [1, 2, 3]

True

not in

Returns True if the value is not in the collection

4 not in [1, 2, 3]

True

Python Bitwise Operators

Bitwise operators in Python are the most esoteric of them all. They are used to perform bit-level operations on integers. Although you may not use these operators as often in your day to day coding, they are a staple in low-level programming languages like C.

As an example, let’s consider the numbers 5 (whose binary representation is 101 ), and the number 3 (represented as 011 in binary).

In order to apply the bitwise AND operator ( & ), we take the first digit from each number’s binary representation (in this case: 1 for the number 5, and 0 for the number 3). Then, we perform the AND operation, which works much like Python’s logical and operator except True is now 1 and False is 0 .

This gives us the operation 1 AND 0 , which results in 0 .

We then simply perform the same operation for each remaining pair of digits in the binary representation of 5 and 3, namely:

  • 0 AND 1 = 0
  • 1 AND 1 = 1

We end up with 0 , 0 , and 1 , which is then put back together as the binary number 001 – which is, in turn, how the number 1 is represented in binary. This all means that the bitwise operation 5 & 3 results in 1 . What a ride!

The name “bitwise” comes from the idea that these operations are performed on “bits” (the numbers 0 or 1), one pair at a time. Afterwards, they are all brought up together in a resulting binary value.

The table below presents all existing bitwise operations in Python:

&

Bitwise AND

5 & 3

101 & 001

1

|

Bitwise OR

5 | 3

101 | 011

7

^

Bitwise XOR (exclusive OR)

5 ^ 3

101 ^ 011

6

~

Bitwise NOT (complement)

~5

~101

-6

<< 

Left shift

5 << 1

101 << 1

10

>> 

Right shift

5 >> 1

101 >> 1

2

Operator Precedence in Python

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first.

For example, the fact that the exponentiation operator ( ** ) has a higher precedence than the addition operator ( + ) means that the expression 2 ** 3 + 4 is seen by Python as (2 ** 3) + 4 . The order of operation is exponentiation and then addition. To override operator precedence, you need to explicitly use parentheses to encapsulate a part of the expression, i.e. 2 ** (3 + 4) .

The table below illustrates the operator precedence in Python. Operators in the earlier rows have a higher precedence:

1

Parentheses

( )

2

Exponentiation

**

3

Unary operators, Bitwise NOT

+x, -x, ~x

4

Multiplication, division, and modulo

*, /, //, %

5

Addition and subtraction

+, -

6

Bitwise shifts

<<, >>

7

Bitwise AND

&

8

Bitwise XOR

^

9

Bitwise OR

|

10

Comparison, identity, and membership

<, <=, >, >=, ==, !=, is, is not, in, not in

11

Logical not

not

12

Logical and

and

13

Logical or

or

Want to Learn More About Python Operators?

In this article, we've covered every single Python operator. This includes arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Understanding these operators is crucial for writing Python code effectively!

For those looking to dive deeper into Python, consider exploring our Learn Programming with Python track . It consists of five in-depth courses and over 400 exercises for you to master the language. You can also challenge yourself with our article on 10 Python practice exercises for beginners !

You may also like

assignments and shortcut operators in python

How Do You Write a SELECT Statement in SQL?

assignments and shortcut operators in python

What Is a Foreign Key in SQL?

assignments and shortcut operators in python

Enumerate and Explain All the Basic Elements of an SQL Query

Shortcut Operators in Python

  • PCEP - The Complete Python Course
  • What is Programming
  • Python Basics
  • Install Python
  • Python Print Function
  • Escape Sequences in Python
  • Python Data Types & Literals
  • Python Literal - Character, String and Boolean
  • Python Arithmetic Operators
  • Python Variable
  • Comments in Python
  • Python Input Function
  • Python String Operator
  • Python Bitwise Operators
  • Python Boolean Operators
  • Comparison Operators In Python
  • Conditional Statements in Python
  • For Loop in Python
  • Python While Loop
  • Python Break, Continue and Pass Statements
  • Python Lists
  • Python Tuples
  • Python Dictionaries

Enroll in Selenium Training

We have seen the assignment operator (=) , and how we can use it to assign data to variables. Additionally, we have also seen the usage of arithmetic operations . Subsequently, in this tutorial, we will learn a quicker way to do these operations.  We called these shortcut operators . We will discuss in detail:-

What are Shortcut Operators?

Let's take an example of variable assignment and increment

count = count + 1;

If we look at this operation, we have got the count variable on both sides of the expression. In addition to that, it is a time-consuming and less efficient way of writing code. Most programming languages have a more efficient way to write this. In the same vein, Python also follows the same.

With Python's shortcut operators , we can write the same expression as

count += 1;

Additionally, we can use shortcut operators on any of the arithmetic binary operators.

The general rule is - If ? is an operator then our long-form will be

variable = variable ? expression

Subsequently, we can write the above expression in shorthand notation as follows.

variable ?= expression

We can place any arithmetic operator in place ?. Let's see some examples in Python IDE.

For example, see the regular operation using the +.

Code_1

In the statement  count = count + 1 , we have the same variable on the left the right sides of the operation. So, we can use shortcut variations of the addition operation. Let's see the same example with the shortcut addition operator.

  • The variable count has a value  0  in the first line.
  • In the second line, we have added  1  to the count .

What's the output? You can say it as  1 . And it's perfect.

shortcut operator usage in the code

If you see the output of the above program and the previous one, both are the same. There is no difference. And this is how we reduce the length of the expressions using  shortcut operators .

Similarly, see the following example with the integer  division.

Another example of shortcut operator usage in the code

We can use all the arithmetic operators as shortcut operators. Here are some more examples

We can represent a = a 3 as a*=3*

We can represent b = b/4 as b/=4

Key Takeaways

  • Firstly, we can use the shortcut operator of the assignment if we have the same operand on both sides of the operation .
  • Moreover, using shortcut operators reduce redundancy .
  • We have all shortcut variations for binary arithmetic operators .
  • *Additionally, c = c * 5 can be written as c = 5 in shortcut operation .
  • Also, rev = rev + num % 10 =can be written as rev += num % 10 in shortcut operation .

Shortcut Operators - Practice Yourself

We got a fair idea of shortcut operations; let's practice some code. Remember, practice will make you perfect, so don't skip this section.

Solutions

To conclude, make sure you have practiced and understood the expressions that are present at the end of the tutorial. Moreover, we will use the shortcut operators frequently in coding. Understand them before going to the next tutorial.

You would have seen the first line of code snaps in each tutorial. Additionally, it starts with a particular character hash (#) . What's that, and why do we use it? Let's find the answers in the next tutorial .

Happy Coding :)

Python Variable

Similar Articles

Python Boolean Operators

  • Selenium Training

Operators and Expressions in Python

Operators and Expressions in Python

Table of Contents

Getting Started With Operators and Expressions

The assignment operator and statements, arithmetic operators and expressions in python, comparison of integer values, comparison of floating-point values, comparison of strings, comparison of lists and tuples, boolean expressions involving boolean operands, evaluation of regular objects in a boolean context, boolean expressions involving other types of operands, compound logical expressions and short-circuit evaluation, idioms that exploit short-circuit evaluation, compound vs chained expressions, conditional expressions or the ternary operator, identity operators and expressions in python, membership operators and expressions in python, concatenation and repetition operators and expressions, the walrus operator and assignment expressions, bitwise operators and expressions in python, operator precedence in python, augmented assignment operators and expressions.

In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation. So, operators are the building blocks of expressions, which you can use to manipulate your data. Therefore, understanding how operators work in Python is essential for you as a programmer.

In this tutorial, you’ll learn about the operators that Python currently supports. You’ll also learn the basics of how to use these operators to build expressions.

In this tutorial, you’ll:

  • Get to know Python’s arithmetic operators and use them to build arithmetic expressions
  • Explore Python’s comparison , Boolean , identity , and membership operators
  • Build expressions with comparison, Boolean, identity, and membership operators
  • Learn about Python’s bitwise operators and how to use them
  • Combine and repeat sequences using the concatenation and repetition operators
  • Understand the augmented assignment operators and how they work

To get the most out of this tutorial, you should have a basic understanding of Python programming concepts, such as variables , assignments , and built-in data types .

Free Bonus: Click here to download your comprehensive cheat sheet covering the various operators in Python.

Take the Quiz: Test your knowledge with our interactive “Python Operators and Expressions” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python operators and expressions.

In programming, an operator is usually a symbol or combination of symbols that allows you to perform a specific operation. This operation can act on one or more operands . If the operation involves a single operand, then the operator is unary . If the operator involves two operands, then the operator is binary .

For example, in Python, you can use the minus sign ( - ) as a unary operator to declare a negative number. You can also use it to subtract two numbers:

In this code snippet, the minus sign ( - ) in the first example is a unary operator, and the number 273.15 is the operand. In the second example, the same symbol is a binary operator, and the numbers 5 and 2 are its left and right operands.

Programming languages typically have operators built in as part of their syntax. In many languages, including Python, you can also create your own operator or modify the behavior of existing ones, which is a powerful and advanced feature to have.

In practice, operators provide a quick shortcut for you to manipulate data, perform mathematical calculations, compare values, run Boolean tests, assign values to variables, and more. In Python, an operator may be a symbol, a combination of symbols, or a keyword , depending on the type of operator that you’re dealing with.

For example, you’ve already seen the subtraction operator, which is represented with a single minus sign ( - ). The equality operator is a double equal sign ( == ). So, it’s a combination of symbols:

In this example, you use the Python equality operator ( == ) to compare two numbers. As a result, you get True , which is one of Python’s Boolean values.

Speaking of Boolean values, the Boolean or logical operators in Python are keywords rather than signs, as you’ll learn in the section about Boolean operators and expressions . So, instead of the odd signs like || , && , and ! that many other programming languages use, Python uses or , and , and not .

Using keywords instead of odd signs is a really cool design decision that’s consistent with the fact that Python loves and encourages code’s readability .

You’ll find several categories or groups of operators in Python. Here’s a quick list of those categories:

  • Assignment operators
  • Arithmetic operators
  • Comparison operators
  • Boolean or logical operators
  • Identity operators
  • Membership operators
  • Concatenation and repetition operators
  • Bitwise operators

All these types of operators take care of specific types of computations and data-processing tasks. You’ll learn more about these categories throughout this tutorial. However, before jumping into more practical discussions, you need to know that the most elementary goal of an operator is to be part of an expression . Operators by themselves don’t do much:

As you can see in this code snippet, if you use an operator without the required operands, then you’ll get a syntax error . So, operators must be part of expressions, which you can build using Python objects as operands.

So, what is an expression anyway? Python has simple and compound statements. A simple statement is a construct that occupies a single logical line , like an assignment statement. A compound statement is a construct that occupies multiple logical lines, such as a for loop or a conditional statement. An expression is a simple statement that produces and returns a value.

You’ll find operators in many expressions. Here are a few examples:

In the first two examples, you use the addition and division operators to construct two arithmetic expressions whose operands are integer numbers. In the last example, you use the equality operator to create a comparison expression. In all cases, you get a specific value after executing the expression.

Note that not all expressions use operators. For example, a bare function call is an expression that doesn’t require any operator:

In the first example, you call the built-in abs() function to get the absolute value of -7 . Then, you compute 2 to the power of 8 using the built-in pow() function. These function calls occupy a single logical line and return a value. So, they’re expressions.

Finally, the call to the built-in print() function is another expression. This time, the function doesn’t return a fruitful value, but it still returns None , which is the Python null type . So, the call is technically an expression.

Note: All Python functions have a return value, either explicit or implicit. If you don’t provide an explicit return statement when defining a function, then Python will automatically make the function return None .

Even though all expressions are statements, not all statements are expressions. For example, pure assignment statements don’t return any value, as you’ll learn in a moment. Therefore, they’re not expressions. The assignment operator is a special operator that doesn’t create an expression but a statement.

Note: Since version 3.8, Python also has what it calls assignment expressions. These are special types of assignments that do return a value. You’ll learn more about this topic in the section The Walrus Operator and Assignment Expressions .

Okay! That was a quick introduction to operators and expressions in Python. Now it’s time to dive deeper into the topic. To kick things off, you’ll start with the assignment operator and statements.

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.

Note: As you already learned, the assignment operator doesn’t create an expression. Instead, it creates a statement that doesn’t return any value.

The assignment operator allows you to assign values to variables . Strictly speaking, in Python, this operator makes variables or names refer to specific objects in your computer’s memory. In other words, an assignment creates a reference to a concrete object and attaches that reference to the target variable.

Note: To dive deeper into using the assignment operator, check out Python’s Assignment Operator: Write Robust Assignments .

For example, all the statements below create new variables that hold references to specific objects:

In the first statement, you create the number variable, which holds a reference to the number 42 in your computer’s memory. You can also say that the name number points to 42 , which is a concrete object.

In the rest of the examples, you create other variables that point to other types of objects, such as a string , tuple , and list , respectively.

You’ll use the assignment operator in many of the examples that you’ll write throughout this tutorial. More importantly, you’ll use this operator many times in your own code. It’ll be your forever friend. Now you can dive into other Python operators!

Arithmetic operators are those operators that allow you to perform arithmetic operations on numeric values. Yes, they come from math, and in most cases, you’ll represent them with the usual math signs. The following table lists the arithmetic operators that Python currently supports:

Operator Type Operation Sample Expression Result
Unary Positive without any transformation since this is simply a complement to negation
Binary Addition The arithmetic sum of and
Unary Negation The value of but with the opposite sign
Binary Subtraction subtracted from
Binary Multiplication The product of and
Binary Division The quotient of divided by , expressed as a float
Binary Modulo The remainder of divided by
Binary Floor division or integer division The quotient of divided by , rounded to the next smallest whole number
Binary Exponentiation raised to the power of

Note that a and b in the Sample Expression column represent numeric values, such as integer , floating-point , complex , rational , and decimal numbers.

Here are some examples of these operators in use:

In this code snippet, you first create two new variables, a and b , holding 5 and 2 , respectively. Then you use these variables to create different arithmetic expressions using a specific operator in each expression.

Note: The Python REPL will display the return value of an expression as a way to provide immediate feedback to you. So, when you’re in an interactive session, you don’t need to use the print() function to check the result of an expression. You can just type in the expression and press Enter to get the result.

Again, the standard division operator ( / ) always returns a floating-point number, even if the dividend is evenly divisible by the divisor:

In the first example, 10 is evenly divisible by 5 . Therefore, this operation could return the integer 2 . However, it returns the floating-point number 2.0 . In the second example, 10.0 is a floating-point number, and 5 is an integer. In this case, Python internally promotes 5 to 5.0 and runs the division. The result is a floating-point number too.

Note: With complex numbers, the division operator doesn’t return a floating-point number but a complex one:

Here, you run a division between an integer and a complex number. In this case, the standard division operator returns a complex number.

Finally, consider the following examples of using the floor division ( // ) operator:

Floor division always rounds down . This means that the result is the greatest integer that’s smaller than or equal to the quotient. For positive numbers, it’s as though the fractional portion is truncated, leaving only the integer portion.

Comparison Operators and Expressions in Python

The Python comparison operators allow you to compare numerical values and any other objects that support them. The table below lists all the currently available comparison operators in Python:

Operator Operation Sample Expression Result
Equal to • if the value of is equal to the value of
• otherwise
Not equal to • if isn’t equal to
• otherwise
Less than • if is less than
• otherwise
Less than or equal to • if is less than or equal to
• otherwise
Greater than • if is greater than
• otherwise
Greater than or equal to • if is greater than or equal to
• otherwise

The comparison operators are all binary. This means that they require left and right operands. These operators always return a Boolean value ( True or False ) that depends on the truth value of the comparison at hand.

Note that comparisons between objects of different data types often don’t make sense and sometimes aren’t allowed in Python. For example, you can compare a number and a string for equality with the == operator. However, you’ll get False as a result:

The integer 2 isn’t equal to the string "2" . Therefore, you get False as a result. You can also use the != operator in the above expression, in which case you’ll get True as a result.

Non-equality comparisons between operands of different data types raise a TypeError exception:

In this example, Python raises a TypeError exception because a less than comparison ( < ) doesn’t make sense between an integer and a string. So, the operation isn’t allowed.

It’s important to note that in the context of comparisons, integer and floating-point values are compatible, and you can compare them.

You’ll typically use and find comparison operators in Boolean contexts like conditional statements and while loops . They allow you to make decisions and define a program’s control flow .

The comparison operators work on several types of operands, such as numbers, strings, tuples, and lists. In the following sections, you’ll explore the differences.

Probably, the more straightforward comparisons in Python and in math are those involving integer numbers. They allow you to count real objects, which is a familiar day-to-day task. In fact, the non-negative integers are also called natural numbers . So, comparing this type of number is probably pretty intuitive, and doing so in Python is no exception.

Consider the following examples that compare integer numbers:

In the first set of examples, you define two variables, a and b , to run a few comparisons between them. The value of a is less than the value of b . So, every comparison expression returns the expected Boolean value. The second set of examples uses two values that are equal, and again, you get the expected results.

Comparing floating-point numbers is a bit more complicated than comparing integers. The value stored in a float object may not be precisely what you’d think it would be. For that reason, it’s bad practice to compare floating-point values for exact equality using the == operator.

Consider the example below:

Yikes! The internal representation of this addition isn’t exactly equal to 3.3 , as you can see in the final example. So, comparing x to 3.3 with the equality operator returns False .

To compare floating-point numbers for equality, you need to use a different approach. The preferred way to determine whether two floating-point values are equal is to determine whether they’re close to one another, given some tolerance.

The math module from the standard library provides a function conveniently called isclose() that will help you with float comparison. The function takes two numbers and tests them for approximate equality:

In this example, you use the isclose() function to compare x and 3.3 for approximate equality. This time, you get True as a result because both numbers are close enough to be considered equal.

For further details on using isclose() , check out the Find the Closeness of Numbers With Python isclose() section in The Python math Module: Everything You Need to Know .

You can also use the comparison operators to compare Python strings in your code. In this context, you need to be aware of how Python internally compares string objects. In practice, Python compares strings character by character using each character’s Unicode code point . Unicode is Python’s default character set .

You can use the built-in ord() function to learn the Unicode code point of any character in Python. Consider the following examples:

The uppercase "A" has a lower Unicode point than the lowercase "a" . So, "A" is less than "a" . In the end, Python compares characters using integer numbers. So, the same rules that Python uses to compare integers apply to string comparison.

When it comes to strings with several characters, Python runs the comparison character by character in a loop.

The comparison uses lexicographical ordering , which means that Python compares the first item from each string. If their Unicode code points are different, this difference determines the comparison result. If the Unicode code points are equal, then Python compares the next two characters, and so on, until either string is exhausted:

In this example, Python compares both operands character by character. When it reaches the end of the string, it compares "o" and "O" . Because the lowercase letter has a greater Unicode code point, the first version of the string is greater than the second.

You can also compare strings of different lengths:

In this example, Python runs a character-by-character comparison as usual. If it runs out of characters, then the shorter string is less than the longer one. This also means that the empty string is the smallest possible string.

In your Python journey, you can also face the need to compare lists with other lists and tuples with other tuples. These data types also support the standard comparison operators. Like with strings, when you use a comparison operator to compare two lists or two tuples, Python runs an item-by-item comparison.

Note that Python applies specific rules depending on the type of the contained items. Here are some examples that compare lists and tuples of integer values:

In these examples, you compare lists and tuples of numbers using the standard comparison operators. When comparing these data types, Python runs an item-by-item comparison.

For example, in the first expression above, Python compares the 2 in the left operand and the 2 in the right operand. Because they’re equal, Python continues comparing 3 and 3 to conclude that both lists are equal. The same thing happens in the second example, where you compare tuples containing the same data.

It’s important to note that you can actually compare lists to tuples using the == and != operators. However, you can’t compare lists and tuples using the < , > , <= , and >= operators:

Python supports equality comparison between lists and tuples. However, it doesn’t support the rest of the comparison operators, as you can conclude from the final two examples. If you try to use them, then you get a TypeError telling you that the operation isn’t supported.

You can also compare lists and tuples of different lengths:

In the first two examples, you get True as a result because 5 is less than 8 . That fact is sufficient for Python to solve the comparison. In the second pair of examples, you get False . This result makes sense because the compared sequences don’t have the same length, so they can’t be equal.

In the final pair of examples, Python compares 5 with 5 . They’re equal, so the comparison continues. Because there are no more values to compare in the right-hand operands, Python concludes that the left-hand operands are greater.

As you can see, comparing lists and tuples can be tricky. It’s also an expensive operation that, in the worst case, requires traversing two entire sequences. Things get more complex and expensive when the contained items are also sequences. In those situations, Python will also have to compare items in a value-by-value manner, which adds cost to the operation.

Boolean Operators and Expressions in Python

Python has three Boolean or logical operators: and , or , and not . They define a set of operations denoted by the generic operators AND , OR , and NOT . With these operators, you can create compound conditions.

In the following sections, you’ll learn how the Python Boolean operators work. Especially, you’ll learn that some of them behave differently when you use them with Boolean values or with regular objects as operands.

You’ll find many objects and expressions that are of Boolean type or bool , as Python calls this type. In other words, many objects evaluate to True or False , which are the Python Boolean values.

For example, when you evaluate an expression using a comparison operator, the result of that expression is always of bool type:

In this example, the expression age > 18 returns a Boolean value, which you store in the is_adult variable. Now is_adult is of bool type, as you can see after calling the built-in type() function.

You can also find Python built-in and custom functions that return a Boolean value. This type of function is known as a predicate function. The built-in all() , any() , callable() , and isinstance() functions are all good examples of this practice.

Consider the following examples:

In this code snippet, you first define a variable called number using your old friend the assignment operator. Then you create another variable called validation_conditions . This variable holds a tuple of expressions. The first expression uses isinstance() to check whether number is an integer value.

The second is a compound expression that combines the modulo ( % ) and equality ( == ) operators to create a condition that checks whether the input value is an even number. In this condition, the modulo operator returns the remainder of dividing number by 2 , and the equality operator compares the result with 0 , returning True or False as the comparison’s result.

Then you use the all() function to determine if all the conditions are true. In this example, because number = 42 , the conditions are true, and all() returns True . You can play with the value of number if you’d like to experiment a bit.

In the final two examples, you use the callable() function. As its name suggests, this function allows you to determine whether an object is callable . Being callable means that you can call the object with a pair of parentheses and appropriate arguments, as you’d call any Python function.

The number variable isn’t callable, and the function returns False , accordingly. In contrast, the print() function is callable, so callable() returns True .

All the previous discussion is the basis for understanding how the Python logical operators work with Boolean operands.

Logical expressions involving and , or , and not are straightforward when the operands are Boolean. Here’s a summary. Note that x and y represent Boolean operands:

Operator Sample Expression Result
• if both and are
• otherwise
• if either or is
• otherwise
• if is
• if is

This table summarizes the truth value of expressions that you can create using the logical operators with Boolean operands. There’s something to note in this summary. Unlike and and or , which are binary operators, the not operator is unary, meaning that it operates on one operand. This operand must always be on the right side.

Now it’s time to take a look at how the operators work in practice. Here are a few examples of using the and operator with Boolean operands:

In the first example, both operands return True . Therefore, the and expression returns True as a result. In the second example, the left-hand operand is True , but the right-hand operand is False . Because of this, the and operator returns False .

In the third example, the left-hand operand is False . In this case, the and operator immediately returns False and never evaluates the 3 == 3 condition. This behavior is called short-circuit evaluation . You’ll learn more about it in a moment.

Note: Short-circuit evaluation is also called McCarthy evaluation in honor of computer scientist John McCarthy .

In the final example, both conditions return False . Again, and returns False as a result. However, because of the short-circuit evaluation, the right-hand expression isn’t evaluated.

What about the or operator? Here are a few examples that demonstrate how it works:

In the first three examples, at least one of the conditions returns True . In all cases, the or operator returns True . Note that if the left-hand operand is True , then or applies short-circuit evaluation and doesn’t evaluate the right-hand operand. This makes sense. If the left-hand operand is True , then or already knows the final result. Why would it need to continue the evaluation if the result won’t change?

In the final example, both operands are False , and this is the only situation where or returns False . It’s important to note that if the left-hand operand is False , then or has to evaluate the right-hand operand to arrive at a final conclusion.

Finally, you have the not operator, which negates the current truth value of an object or expression:

If you place not before an expression, then you get the inverse truth value. When the expression returns True , you get False . When the expression evaluates to False , you get True .

There is a fundamental behavior distinction between not and the other two Boolean operators. In a not expression, you always get a Boolean value as a result. That’s not always the rule that governs and and or expressions, as you’ll learn in the Boolean Expressions Involving Other Types of Operands section.

In practice, most Python objects and expressions aren’t Boolean. In other words, most objects and expressions don’t have a True or False value but a different type of value. However, you can use any Python object in a Boolean context, such as a conditional statement or a while loop.

In Python, all objects have a specific truth value. So, you can use the logical operators with all types of operands.

Python has well-established rules to determine the truth value of an object when you use that object in a Boolean context or as an operand in an expression built with logical operators. Here’s what the documentation says about this topic:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false: constants defined to be false: None and False . zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1) empty sequences and collections: '' , () , [] , {} , set() , range(0) ( Source )

You can determine the truth value of an object by calling the built-in bool() function with that object as an argument. If bool() returns True , then the object is truthy . If bool() returns False , then it’s falsy .

For numeric values, you have that a zero value is falsy, while a non-zero value is truthy:

Python considers the zero value of all numeric types falsy. All the other values are truthy, regardless of how close to zero they are.

Note: Instead of a function, bool() is a class. However, because Python developers typically use this class as a function, you’ll find that most people refer to it as a function rather than as a class. Additionally, the documentation lists this class on the built-in functions page. This is one of those cases where practicality beats purity .

When it comes to evaluating strings, you have that an empty string is always falsy, while a non-empty string is truthy:

Note that strings containing white spaces are also truthy in Python’s eyes. So, don’t confuse empty strings with whitespace strings.

Finally, built-in container data types, such as lists, tuples, sets , and dictionaries , are falsy when they’re empty. Otherwise, Python considers them truthy objects:

To determine the truth value of container data types, Python relies on the .__len__() special method . This method provides support for the built-in len() function, which you can use to determine the number of items in a given container.

In general, if .__len__() returns 0 , then Python considers the container a falsy object, which is consistent with the general rules you’ve just learned before.

All the discussion about the truth value of Python objects in this section is key to understanding how the logical operators behave when they take arbitrary objects as operands.

You can also use any objects, such as numbers or strings, as operands to and , or , and not . You can even use combinations of a Boolean object and a regular one. In these situations, the result depends on the truth value of the operands.

Note: Boolean expressions that combine two Boolean operands are a special case of a more general rule that allows you to use the logical operators with all kinds of operands. In every case, you’ll get one of the operands as a result.

You’ve already learned how Python determines the truth value of objects. So, you’re ready to dive into creating expressions with logic operators and regular objects.

To start off, below is a table that summarizes what you get when you use two objects, x and y , in an and expression:

If is returns
Truthy
Falsy

It’s important to emphasize a subtle detail in the above table. When you use and in an expression, you don’t always get True or False as a result. Instead, you get one of the operands. You only get True or False if the returned operand has either of these values.

Here are some code examples that use integer values. Remember that in Python, the zero value of numeric types is falsy. The rest of the values are truthy:

In the first expression, the left-hand operand ( 3 ) is truthy. So, you get the right-hand operand ( 4 ) as a result.

In the second example, the left-hand operand ( 0 ) is falsy, and you get it as a result. In this case, Python applies the short-circuit evaluation technique. It already knows that the whole expression is false because 0 is falsy, so Python returns 0 immediately without evaluating the right-hand operand.

In the final expression, the left-hand operand ( 3 ) is truthy. Therefore Python needs to evaluate the right-hand operand to make a conclusion. As a result, you get the right-hand operand, no matter what its truth value is.

Note: To dive deeper into the and operator, check out Using the “and” Boolean Operator in Python .

When it comes to using the or operator, you also get one of the operands as a result. This is what happens for two arbitrary objects, x and y :

Again, the expression x or y doesn’t evaluate to either True or False . Instead, it returns one of its operands, x or y .

As you can conclude from the above table, if the left-hand operand is truthy, then you get it as a result. Otherwise, you get the second operand. Here are some examples that demonstrate this behavior:

In the first example, the left-hand operand is truthy, and or immediately returns it. In this case, Python doesn’t evaluate the second operand because it already knows the final result. In the second example, the left-hand operand is falsy, and Python has to evaluate the right-hand one to determine the result.

In the last example, the left-hand operand is truthy, and that fact defines the result of the expression. There’s no need to evaluate the right-hand operand.

An expression like x or y is truthy if either x or y is truthy, and falsy if both x and y are falsy. This type of expression returns the first truthy operand that it finds. If both operands are falsy, then the expression returns the right-hand operand. To see this latter behavior in action, consider the following example:

In this specific expression, both operands are falsy. So, the or operator returns the right-hand operand, and the whole expression is falsy as a result.

Note: To learn more about the or operator, check out Using the “or” Boolean Operator in Python .

Finally, you have the not operator. You can also use this one with any object as an operand. Here’s what happens:

The not operator has a uniform behavior. It always returns a Boolean value. This behavior differs from its sibling operators, and and or .

Here are some code examples:

In the first example, the operand, 3 , is truthy from Python’s point of view. So, the operator returns False . In the second example, the operand is falsy, and not returns True .

Note: To better understand the not operator, check out Using the “not” Boolean Operator in Python .

In summary, the Python not operator negates the truth value of an object and always returns a Boolean value. This latter behavior differs from the behavior of its sibling operators and and or , which return operands rather than Boolean values.

So far, you’ve seen expressions with only a single or or and operator and two operands. However, you can also create compound logical expressions with multiple logical operators and operands.

To illustrate how to create a compound expression using or , consider the following toy example:

This expression returns the first truthy value. If all the preceding x variables are falsy, then the expression returns the last value, xn .

Note: In an expression like the one above, Python uses short-circuit evaluation . The operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true. At that point, Python stops evaluating operands. The value of the entire expression is that of the x that terminates the evaluation.

To help demonstrate short-circuit evaluation, suppose that you have an identity function , f() , that behaves as follows:

  • Takes a single argument
  • Displays the function and its argument on the screen
  • Returns the argument as its return value

Here’s the code to define this function and also a few examples of how it works:

The f() function displays its argument, which visually confirms whether you called the function. It also returns the argument as you passed it in the call. Because of this behavior, you can make the expression f(arg) be truthy or falsy by specifying a value for arg that’s truthy or falsy, respectively.

Now, consider the following compound logical expression:

In this example, Python first evaluates f(0) , which returns 0 . This value is falsy. The expression isn’t true yet, so the evaluation continues from left to right. The next operand, f(False) , returns False . That value is also falsy, so the evaluation continues.

Next up is f(1) . That evaluates to 1 , which is truthy. At that point, Python stops the evaluation because it already knows that the entire expression is truthy. Consequently, Python returns 1 as the value of the expression and never evaluates the remaining operands, f(2) and f(3) . You can confirm from the output that the f(2) and f(3) calls don’t occur.

A similar behavior appears in an expression with multiple and operators like the following one:

This expression is truthy if all the operands are truthy. If at least one operand is falsy, then the expression is also falsy.

In this example, short-circuit evaluation dictates that Python stops evaluating as soon as an operand happens to be falsy. At that point, the entire expression is known to be false. Once that’s the case, Python stops evaluating operands and returns the falsy operand that terminated the evaluation.

Here are two examples that confirm the short-circuiting behavior:

In both examples, the evaluation stops at the first falsy term— f(False) in the first case, f(0.0) in the second case—and neither the f(2) nor the f(3) call occurs. In the end, the expressions return False and 0.0 , respectively.

If all the operands are truthy, then Python evaluates them all and returns the last (rightmost) one as the value of the expression:

In the first example, all the operands are truthy. The expression is also truthy and returns the last operand. In the second example, all the operands are truthy except for the last one. The expression is falsy and returns the last operand.

As you dig into Python, you’ll find that there are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression, performance, and safety. For example, you can take advantage of this type of evaluation for:

  • Avoiding an exception
  • Providing a default value
  • Skipping a costly operation

To illustrate the first point, suppose you have two variables, a and b , and you want to know whether the division of b by a results in a number greater than 0 . In this case, you can run the following expression or condition:

This code works. However, you need to account for the possibility that a might be 0 , in which case you’ll get an exception :

In this example, the divisor is 0 , which makes Python raise a ZeroDivisionError exception. This exception breaks your code. You can skip this error with an expression like the following:

When a is 0 , a != 0 is false. Python’s short-circuit evaluation ensures that the evaluation stops at that point, which means that (b / a) never runs, and the error never occurs.

Using this technique, you can implement a function to determine whether an integer is divisible by another integer:

In this function, if b is 0 , then a / b isn’t defined. So, the numbers aren’t divisible. If b is different from 0 , then the result will depend on the remainder of the division.

Selecting a default value when a specified value is falsy is another idiom that takes advantage of the short-circuit evaluation feature of Python’s logical operators.

For example, say that you have a variable that’s supposed to contain a country’s name. At some point, this variable can end up holding an empty string. If that’s the case, then you’d like the variable to hold a default county name. You can also do this with the or operator:

If country is non-empty, then it’s truthy. In this scenario, the expression will return the first truthy value, which is country in the first or expression. The evaluation stops, and you get "Canada" as a result.

On the other hand, if country is an empty string , then it’s falsy. The evaluation continues to the next operand, default_country , which is truthy. Finally, you get the default country as a result.

Another interesting use case for short-circuit evaluation is to avoid costly operations while creating compound logical expressions. For example, if you have a costly operation that should only run if a given condition is false, then you can use or like in the following snippet:

In this construct, your clean_data() function represents a costly operation. Because of short-circuit evaluation, this function will only run when data_is_clean is false, which means that your data isn’t clean.

Another variation of this technique is when you want to run a costly operation if a given condition is true. In this case, you can use the and operator:

In this example, the and operator evaluates data_is_updated . If this variable is true, then the evaluation continues, and the process_data() function runs. Otherwise, the evaluation stops, and process_data() never runs.

Sometimes you have a compound expression that uses the and operator to join comparison expressions. For example, say that you want to determine if a number is in a given interval. You can solve this problem with a compound expression like the following:

In this example, you use the and operator to join two comparison expressions that allow you to find out if number is in the interval from 0 to 10 , both included.

In Python, you can make this compound expression more concise by chaining the comparison operators together. For example, the following chained expression is equivalent to the previous compound one:

This expression is more concise and readable than the original expression. You can quickly realize that this code is checking if the number is between 0 and 10 . Note that in most programming languages, this chained expression doesn’t make sense. In Python, it works like a charm.

In other programming languages, this expression would probably start by evaluating 0 <= number , which is true. This true value would then be compared with 10 , which doesn’t make much sense, so the expression fails.

Python internally processes this type of expression as an equivalent and expression, such as 0 <= number and number <= 10 . That’s why you get the correct result in the example above.

Python has what it calls conditional expressions . These kinds of expressions are inspired by the ternary operator that looks like a ? b : c and is used in other programming languages. This construct evaluates to b if the value of a is true, and otherwise evaluates to c . Because of this, sometimes the equivalent Python syntax is also known as the ternary operator.

However, in Python, the expression looks more readable:

This expression returns expression_1 if the condition is true and expression_2 otherwise. Note that this expression is equivalent to a regular conditional like the following:

So, why does Python need this syntax? PEP 308 introduced conditional expressions as an effort to avoid the prevalence of error-prone attempts to achieve the same effect of a traditional ternary operator using the and and or operators in an expression like the following:

However, this expression doesn’t work as expected, returning expression_2 when expression_1 is falsy.

Some Python developers would avoid the syntax of conditional expressions in favor of a regular conditional statement. In any case, this syntax can be handy in some situations because it provides a concise tool for writing two-way conditionals.

Here’s an example of how to use the conditional expression syntax in your code:

When day is equal to "Sunday" , the condition is true and you get the first expression, "11AM" , as a result. If the condition is false, then you get the second expression, "9AM" . Note that similarly to the and and or operators, the conditional expression returns the value of one of its expressions rather than a Boolean value.

Python provides two operators, is and is not , that allow you to determine whether two operands have the same identity . In other words, they let you check if the operands refer to the same object. Note that identity isn’t the same thing as equality. The latter aims to check whether two operands contain the same data.

Note: To learn more about the difference between identity and equality, check out Python ‘!=’ Is Not ‘is not’: Comparing Objects in Python .

Here’s a summary of Python’s identity operators. Note that x and y are variables that point to objects:

Operator Sample Expression Result
• if and hold a reference to the same in-memory object
• otherwise
• if points to an object different from the object that points to
• otherwise

These two Python operators are keywords instead of odd symbols. This is part of Python’s goal of favoring readability in its syntax.

Here’s an example of two variables, x and y , that refer to objects that are equal but not identical:

In this example, x and y refer to objects whose value is 1001 . So, they’re equal. However, they don’t reference the same object. That’s why the is operator returns False . You can check an object’s identity using the built-in id() function:

As you can conclude from the id() output, x and y don’t have the same identity. So, they’re different objects, and because of that, the expression x is y returns False . In other words, you get False because you have two different instances of 1001 stored in your computer’s memory.

When you make an assignment like y = x , Python creates a second reference to the same object. Again, you can confirm that with the id() function or the is operator:

In this example, a and b hold references to the same object, the string "Hello, Pythonista!" . Therefore, the id() function returns the same identity when you call it with a and b . Similarly, the is operator returns True .

Note: You should note that, on your computer, you’ll get a different identity number when you call id() in the example above. The key detail is that the identity number will be the same for a and b .

Finally, the is not operator is the opposite of is . So, you can use is not to determine if two names don’t refer to the same object:

In the first example, because x and y point to different objects in your computer’s memory, the is not operator returns True . In the second example, because a and b are references to the same object, the is not operator returns False .

Note: The syntax not x is y also works the same as x is not y . However, the former syntax looks odd and is difficult to read. That’s why Python recognizes is not as an operator and encourages its use for readability.

Again, the is not operator highlights Python’s readability goals. In general, both identity operators allow you to write checks that read as plain English.

Sometimes you need to determine whether a value is present in a container data type, such as a list, tuple, or set. In other words, you may need to check if a given value is or is not a member of a collection of values. Python calls this kind of check a membership test .

Note: For a deep dive into how Python’s membership tests work, check out Python’s “in” and “not in” Operators: Check for Membership .

Membership tests are quite common and useful in programming. As with many other common operations, Python has dedicated operators for membership tests. The table below lists the membership operators in Python:

Operator Sample Expression Result
• if present in
• otherwise
• if present in of values
• otherwise

As usual, Python favors readability by using English words as operators instead of potentially confusing symbols or combinations of symbols.

Note: The syntax not value in collection also works in Python. However, this syntax looks odd and is difficult to read. So, to keep your code clean and readable, you should use value not in collection , which almost reads as plain English.

The Python in and not in operators are binary. This means that you can create membership expressions by connecting two operands with either operator. However, the operands in a membership expression have particular characteristics:

  • Left operand : The value that you want to look for in a collection of values
  • Right operand : The collection of values where the target value may be found

To better understand the in operator, below you have two demonstrative examples consisting of determining whether a value is in a list:

The first expression returns True because 5 is in the list of numbers. The second expression returns False because 8 isn’t in the list.

The not in membership operator runs the opposite test as the in operator. It allows you to check whether an integer value is not in a collection of values:

In the first example, you get False because 5 is in the target list. In the second example, you get True because 8 isn’t in the list of values. This may sound like a tongue twister because of the negative logic. To avoid confusion, remember that you’re trying to determine if the value is not part of a given collection of values.

There are two operators in Python that acquire a slightly different meaning when you use them with sequence data types, such as lists, tuples, and strings. With these types of operands, the + operator defines a concatenation operator , and the * operator represents the repetition operator :

Operator Operation Sample Expression Result
Concatenation A new sequence containing all the items from both operands
Repetition A new sequence containing the items of repeated times

Both operators are binary. The concatenation operator takes two sequences as operands and returns a new sequence of the same type. The repetition operator takes a sequence and an integer number as operands. Like in regular multiplication, the order of the operands doesn’t alter the repetition’s result.

Note: To learn more about concatenating string objects, check out Efficient String Concatenation in Python .

Here are some examples of how the concatenation operator works in practice:

In the first example, you use the concatenation operator ( + ) to join two strings together. The operator returns a completely new string object that combines the two original strings.

In the second example, you concatenate two tuples of letters together. Again, the operator returns a new tuple object containing all the items from the original operands. In the final example, you do something similar but this time with two lists.

Note: To learn more about concatenating lists, check out the Concatenating Lists section in the tutorial Python’s list Data Type: A Deep Dive With Examples .

When it comes to the repetition operator, the idea is to repeat the content of a given sequence a certain number of times. Here are a few examples:

In the first example, you use the repetition operator ( * ) to repeat the "Hello" string three times. In the second example, you change the order of the operands by placing the integer number on the left and the target string on the right. This example shows that the order of the operands doesn’t affect the result.

The next examples use the repetition operators with a tuple and a list, respectively. In both cases, you get a new object of the same type containing the items in the original sequence repeated three times.

Regular assignment statements with the = operator don’t have a return value, as you already learned. Instead, the assignment operator creates or updates variables. Because of this, the operator can’t be part of an expression.

Since Python 3.8 , you have access to a new operator that allows for a new type of assignment. This new assignment is called assignment expression or named expression . The new operator is called the walrus operator , and it’s the combination of a colon and an equal sign ( := ).

Note: The name walrus comes from the fact that this operator resembles the eyes and tusks of a walrus lying on its side. For a deep dive into how this operator works, check out The Walrus Operator: Python’s Assignment Expressions .

Unlike regular assignments, assignment expressions do have a return value, which is why they’re expressions . So, the operator accomplishes two tasks:

  • Returns the expression’s result
  • Assigns the result to a variable

The walrus operator is also a binary operator. Its left-hand operand must be a variable name, and its right-hand operand can be any Python expression. The operator will evaluate the expression, assign its value to the target variable, and return the value.

The general syntax of an assignment expression is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, in certain situations, you won’t need them. Either way, they won’t hurt you, so it’s safe to use them.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand. It’s particularly useful in the context of a conditional statement. To illustrate, the example below shows a toy function that checks the length of a string object:

In this example, you use a conditional statement to check whether the input string has fewer than 8 characters.

The assignment expression, (n := len(string)) , computes the string length and assigns it to n . Then it returns the value that results from calling len() , which finally gets compared with 8 . This way, you guarantee that you have a reference to the string length to use in further operations.

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. Currently, Python supports the following bitwise operators:

Operator Operation Sample Expression Result
Bitwise AND • Each bit position in the result is the logical AND of the bits in the corresponding position of the operands.
• if both bits are , otherwise .
Bitwise OR • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if either bit is , otherwise .
Bitwise NOT • Each bit position in the result is the logical negation of the bit in the corresponding position of the operand.
• if the bit is and if the bit is .
Bitwise XOR (exclusive OR) • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if the bits in the operands are different, if they’re equal.
Bitwise right shift Each bit is shifted right places.
Bitwise left shift Each bit is shifted left places.

As you can see in this table, most bitwise operators are binary, which means that they expect two operands. The bitwise NOT operator ( ~ ) is the only unary operator because it expects a single operand, which should always appear at the right side of the expression.

You can use Python’s bitwise operators to manipulate your data at its most granular level, the bits. These operators are commonly useful when you want to write low-level algorithms, such as compression, encryption, and others.

Note: For a deep dive into the bitwise operators, check out Bitwise Operators in Python . You can also check out Build a Maze Solver in Python Using Graphs for an example of using bitwise operators to construct a binary file format.

Here are some examples that illustrate how some of the bitwise operators work in practice:

In the first example, you use the bitwise AND operator. The commented lines begin with # and provide a visual representation of what happens at the bit level. Note how each bit in the result is the logical AND of the bits in the corresponding position of the operands.

The second example shows how the bitwise OR operator works. In this case, the resulting bits are the logical OR test of the corresponding bits in the operands.

In all the examples, you’ve used the built-in bin() function to display the result as a binary object. If you don’t wrap the expression in a call to bin() , then you’ll get the integer representation of the output.

Up to this point, you’ve coded sample expressions that mostly use one or two different types of operators. However, what if you need to create compound expressions that use several different types of operators, such as comparison, arithmetic, Boolean, and others? How does Python decide which operation runs first?

Consider the following math expression:

There might be ambiguity in this expression. Should Python perform the addition 20 + 4 first and then multiply the result by 10 ? Should Python run the multiplication 4 * 10 first, and the addition second?

Because the result is 60 , you can conclude that Python has chosen the latter approach. If it had chosen the former, then the result would be 240 . This follows a standard algebraic rule that you’ll find in virtually all programming languages.

All operators that Python supports have a precedence compared to other operators. This precedence defines the order in which Python runs the operators in a compound expression.

In an expression, Python runs the operators of highest precedence first. After obtaining those results, Python runs the operators of the next highest precedence. This process continues until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order.

Here’s the order of precedence of the Python operators that you’ve seen so far, from highest to lowest:

Operators Description
Exponentiation
, , Unary positive, unary negation, bitwise negation
, , , Multiplication, division, floor division,
, Addition, subtraction
, Bitwise shifts
Bitwise AND
Bitwise XOR
Bitwise OR
, , , , , , , , , Comparisons, identity, and membership
Boolean NOT
Boolean AND
Boolean OR
Walrus

Operators at the top of the table have the highest precedence, and those at the bottom of the table have the lowest precedence. Any operators in the same row of the table have equal precedence.

Getting back to your initial example, Python runs the multiplication because the multiplication operator has a higher precedence than the addition one.

Here’s another illustrative example:

In the example above, Python first raises 3 to the power of 4 , which equals 81 . Then, it carries out the multiplications in order from left to right: 2 * 81 = 162 and 162 * 5 = 810 .

You can override the default operator precedence using parentheses to group terms as you do in math. The subexpressions in parentheses will run before expressions that aren’t in parentheses.

Here are some examples that show how a pair of parentheses can affect the result of an expression:

In the first example, Python computes the expression 20 + 4 first because it’s wrapped in parentheses. Then Python multiplies the result by 10 , and the expression returns 240 . This result is completely different from what you got at the beginning of this section.

In the second example, Python evaluates 4 * 5 first. Then it raises 3 to the power of the resulting value. Finally, Python multiplies the result by 2 , returning 6973568802 .

There’s nothing wrong with making liberal use of parentheses, even when they aren’t necessary to change the order of evaluation. Sometimes it’s a good practice to use parentheses because they can improve your code’s readability and relieve the reader from having to recall operator precedence from memory.

Consider the following example:

Here the parentheses are unnecessary, as the comparison operators have higher precedence than and . However, some might find the parenthesized version clearer than the version without parentheses:

On the other hand, some developers might prefer this latter version of the expression. It’s a matter of personal preference. The point is that you can always use parentheses if you feel that they make your code more readable, even if they aren’t necessary to change the order of evaluation.

So far, you’ve learned that a single equal sign ( = ) represents the assignment operator and allows you to assign a value to a variable. Having a right-hand operand that contains other variables is perfectly valid, as you’ve also learned. In particular, the expression to the right of the assignment operator can include the same variable that’s on the left of the operand.

That last sentence may sound confusing, so here’s an example that clarifies the point:

In this example, total is an accumulator variable that you use to accumulate successive values. You should read this example as total is equal to the current value of total plus 5 . This expression effectively increases the value of total , which is now 15 .

Note that this type of assignment only makes sense if the variable in question already has a value. If you try the assignment with an undefined variable, then you get an error:

In this example, the count variable isn’t defined before the assignment, so it doesn’t have a current value. In consequence, Python raises a NameError exception to let you know about the issue.

This type of assignment helps you create accumulators and counter variables, for example. Therefore, it’s quite a common task in programming. As in many similar cases, Python offers a more convenient solution. It supports a shorthand syntax called augmented assignment :

In the highlighted line, you use the augmented addition operator ( += ). With this operator, you create an assignment that’s fully equivalent to total = total + 5 .

Python supports many augmented assignment operators. In general, the syntax for this type of assignment looks something like this:

Note that the dollar sign ( $ ) isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. The above statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the assignment operator ( = ), using the current value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

The table below shows a summary of the augmented operators for arithmetic operations:

Operator Description Sample Expression Equivalent Expression
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

As you can conclude from this table, all the arithmetic operators have an augmented version in Python. You can use these augmented operators as a shortcut when creating accumulators, counters, and similar objects.

Did the augmented arithmetic operators look neat and useful to you? The good news is that there are more. You also have augmented bitwise operators in Python:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

Finally, the concatenation and repetition operators have augmented variations too. These variations behave differently with mutable and immutable data types:

Operator Description Example
• Runs an augmented concatenation operation on the target sequence.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.
• Adds to itself times.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator works on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Now you know what operators Python supports and how to use them. Operators are symbols, combinations of symbols, or keywords that you can use along with Python objects to build different types of expressions and perform computations in your code.

In this tutorial, you’ve learned:

  • What Python’s arithmetic operators are and how to use them in arithmetic expressions
  • What Python’s comparison , Boolean , identity , membership operators are
  • How to write expressions using comparison, Boolean, identity, and membership operators
  • Which bitwise operators Python supports and how to use them
  • How to combine and repeat sequences using the concatenation and repetition operators
  • What the augmented assignment operators are and how they work

In other words, you’ve covered an awful lot of ground! If you’d like a handy cheat sheet that can jog your memory on all that you’ve learned, then click the link below:

With all this knowledge about operators, you’re better prepared as a Python developer. You’ll be able to write better and more robust expressions in your code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Dan Bader

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Operators and Expressions in Python (Cheat Sheet)

🔒 No spam. We take your privacy seriously.

assignments and shortcut operators in python

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.

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

assignments and shortcut 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

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

ADVERTISEMENT

Coding Essentials Guidebook for Developers

This book covers core coding concepts and tools. It contains chapters on computer architecture, the Internet, Command Line, HTML, CSS, JavaScript, Python, Java, SQL, Git, and more.

Learn more!

Image of the cover of the Coding Essentials Guidebook for Developers

Decoding Git Guidebook for Developers

This book dives into the initial commit of Git's C code in detail to help developers learn what makes Git tick. If you're curious how Git works under the hood, you'll enjoy this.

Image of the cover of the Decoding Git Guidebook for Developers

Decoding Bitcoin Guidebook for Developers

This book dives into the initial commit of Bitcoin's C++ code. The book strives to unearth and simplify the concepts that underpin the Bitcoin software system, so that beginner and intermediate developers can understand how it works.

Image of the cover of the Decoding Bitcoin Guidebook for Developers

Subscribe to be notified when we release new content and features!

Follow us on your favorite channels!

Assignment Operators in Python

Image of Assignment Operators in Python

Table of Contents

Introduction, what are the assignment operators and why would you use them in python, how do you use the assignment operators in python and what are the benefits of doing so, what are the benefits of using the assignment operators in python, what are the potential drawbacks of using the assignment operators in python, when is it best to use the assignment operators in python, when is it not recommended to use the assignments operators in python, is there ++ in python, why isn't there ++ and -- in python.

Whether you are an old hand or you are just learning to program , assignment operators are a useful tool to add to your programming arsenal. Assignment operators are often used when you want to make a variable change by a specific amount in shorthand.

In this blog post, we will discuss what the assignment operators are, how to use them in Python, and the benefits and drawbacks of doing so. We will also explore when it is best to use assignment operators in Python, and when it may not be the best option. Finally, we will answer the question of whether or not the incrementing operator ++ is available in Python.

An assignment operator is a symbol that you use in Python to indicate that you want to perform some action and then assign the value to a . You would use an addition or subtraction operator in Python when you want to calculate the result of adding or subtracting two numbers. There are two types of addition operators: the plus sign + and the asterisk * . There are also two types of subtraction operators: the minus sign - and the forward slash / .

The plus sign + is used to indicate that you want to add two numbers together. The asterisk * is used to indicate that you want to multiply two numbers together. The minus sign - is used to indicate that you want to subtract two numbers. The forward slash / is used to indicate that you want to divide two numbers.

Here are some examples of how to use the addition and subtraction operators in Python:

The += operator is used to add two numbers together. The result of the addition will be stored in the variable that is on the left side of the += symbol. In this example, the result of adding y (15) to x (25) is stored in the variable x .

The -= operator is used to subtract one number from another. The result of the subtraction will be stored in the variable that is on the left side of the -= symbol. In this example, the result of subtracting y (15) from x (25) is stored in the variable x.

These operators are convenient ways to add or subtract values from a variable without having to use an intermediate variable. For example, if you want to add two numbers together and store the result in a new variable, you would write:

first_number = first_number + second_number

However, if you want to use the += operator instead, you can simply write:

first_number += second_number

This will save you a few keystrokes and also make your code more readable.

The -= operator is similarly useful for subtracting values from a variable. For example:

first_number -= second_number

This will subtract the second_number from the variable first_number .

One potential drawback to using the += and -= assignment operators in Python is that they can be confusing for beginners.

Another potential drawback is that they can lead to code that is difficult to read and understand.

However, these drawbacks are outweighed by the benefits of using these operators, which include increased readability and brevity of code. For these reasons, I recommend using the += , -= , *= , and /= assignment operators in Python whenever possible.

The increment operator is best used when you want to increment or decrement a variable by a number and you want to eliminate some keystrokes or create some brevity in your code.

In addition, it can also be used with other operators, such as the multiplication operator * . The following example shows how to use the increment operator with the multiplication operator:

This will print out the value of x as "120".

You may consider not using the assignment operators when you are dealing with a team of new programmers who may find the syntax confusing.

There are ways to mitigate this though, with training, lunch and learns, and more you can bring up the developers to the place where using some of the intricacies of Python.

No, the ++ (and -- ) operators available in C and other languages were not brought over to Python.

If you attempt to use ++ and -- the way they are used in C you will not get the results you are expecting. Use the += and -= operators.

Python doesn't have a ++ operator because it can be easily replaced with the += operator. Having both was probably thought to create more confusion.

There's a certain amount of ambiguity in the operator to the language parser. It could interpret the ++ in Python as two unary operators (+ and +) or it could be one unary operator (++).

Lastly, it can cause confusing side effects and Python likes to eliminate edge cases when interpreting the code. Look up C precedence issues of pre and post incrementation if you want to know more. It's not fun.

The += and -= assignment operators in Python are convenient ways to add or subtract values from a variable without having to use an intermediate variable. They are also more readable than traditional methods of adding or subtracting values. For these reasons, I recommend using the += and -= assignment operators whenever possible. You can learn more in the Python documentation . Start using these powerful tools today!

If you're interested in learning more about the basics of coding, programming, and software development, check out our Coding Essentials Guidebook for Developers , where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to [email protected] .

Final Notes

Recommended product: Coding Essentials Guidebook for Developers

Related Articles

Python zfill method.

Image of the Git logo

Python Yield vs Return

Python zip two lists, using raw_input() in python 3, python list print, numpy around() in python, get the first 5 chapters of our coding essentials guidebook for developers free , the programming guide i wish i had when i started learning to code... 🚀👨‍💻📚.

Image of the cover of the Coding Essentials Guidebook for Developers

Check out our Coding Essentials Guidebook for Developers

01 Career Opportunities

02 beginner, 03 intermediate, 04 training programs, what are operators in python - types of operators in python ( with examples ), python operators: an overview, what are operators in python, types of python operators, 1. python arithmetic operators.

+Addition10 + 20 = 30
-Subtraction20 – 10 = 10
*Multiplication10 * 20 = 200
/Division20 / 10 = 2
%Modulus22 % 10 = 2
**Exponent4**2 = 16
//Floor Division9//2 = 4

Example of Python Arithmetic Operators in Python Compiler

2. python comparison operators.

==Equal4 == 5 is not true.
!=Not Equal4 != 5 is true.
>Greater Than4 > 5 is not true
<Less Than4 < 5 is true
>=Greater than or Equal to4 >= 5 is not true.
<=Less than or Equal to4 <= 5 is true.

Example of Python Comparison Operators

3. python assignment operators.

=Assignment Operatora = 10
+=Addition Assignmenta += 5 (Same as a = a + 5)
-=Subtraction Assignmenta -= 5 (Same as a = a - 5)
*=Multiplication Assignmenta *= 5 (Same as a = a * 5)
/=Division Assignmenta /= 5 (Same as a = a / 5)
%=Remainder Assignmenta %= 5 (Same as a = a % 5)
**=Exponent Assignmenta **= 2 (Same as a = a ** 2)
//=Floor Division Assignmenta //= 3 (Same as a = a // 3)

Example of Python Assignment Operators

4. python bitwise operators.

&Binary ANDSets each bit to 1 if both bits are 1
|Binary ORSets each bit to 1 if one of the two bits is 1
^Binary XORSets each bit to 1 if only one of two bits is 1
~Binary Ones ComplementInverts all the bits
~Binary Ones ComplementInverts all the bits
<<Binary Left ShiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Binary Right ShiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Example of Python Bitwise Operators

5. python logical operators.

and Logical ANDIf both of the operands are true then the condition becomes true.(a and b) is true.
or Logical ORIf any of the two operands is non-zero then the condition becomes true.(a or b) is true.
not Logical NOTUsed to reverse the logical state of its operandNot(a and b) is false.

Example of Python Logical Operators in Python Online Editor

6. python membership operators.

OperatorDescriptionExample
inEvaluates to true if it finds a variable in the specified sequence and false otherwise.x in y, here in results in a 1 if x is a member of sequence y.
not inEvaluates to true if it does not find a variable in the specified sequence and false otherwise.x not in y, here not in results in a 1 if x is not a member of sequence y.

Example of Python Membership Operators

7. python identity operators.

isEvaluates to true if the variables on either side of the operator point to the same object and false otherwisex is y, here are results in 1 if id(x) equals id(y)
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwisex is not y, there are no results in 1 if id(x) is not equal to id(y).

Example of Python Identity Operators

Python operators precedence.

Sr.No.OperatorDescription
1.**Exponentiation (raise to the power)
2.~ + -Complement, unary plus and minus (method names for the last two are +@ and -@)
3.* / % //Multiply, divide, modulo, and floor division
4.+ -Addition and subtraction
5.>> <<Right and left bitwise shift
6.&Bitwise 'AND'
7.^ |Bitwise exclusive `OR' and regular `OR'
8.<= < > >=Comparison operators
9.<> == !=Equality operators
10.= %= /= //= -= += *= **=Assignment operators
11.is is notIdentity operators
12in not inMembership operators
13.not or andLogical operators

Guidelines for using operators effectively

Q1. define the operator in python., q2. what are the operators used in the python list, q3. what are the 7 arithmetic operators in python, q4. what is python and its operators, q5. what are the different types of operators 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
Filling Fast

About Author

assignments and shortcut operators in python

Assignment Operators in Python

Assignment Operators in Python

Table of Contents

Assignment Operators will work on values and variables. They are the special symbols that hold arithmetic, logical, and bitwise computations. The value which the operator operates is referred to as the Operand.

Read this article about Assignment Operators in Python

What are Assignment Operators?

The assignment operator will function to provide value to variables. The table below is about the different types of Assignment operator

+= will add right side operand with left side operand, assign to left operand a+=b
= It will assign the value of the right side of the expression to the left side operandx=y+z
-= can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala -= b  
*= can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala *= b     
/= will divide the left operand with right operand and then assign to the left operanda /= b
%= will divide the left operand with the right operand and then assign to the left operanda %= b  
<<=
It functions bitwise left on operands and will assign value to the left operand a <<= b 
>>=
This operator will perform right shift on operands and can assign value to the left operanda >>= b     

^=
This will function the bitwise xOR operands and can assign value to the left operand a ^= b    

|=
This will function Bitwise OR operands and will provide value to the left operand.a |= b    

&=
This operator will perform Bitwise AND on operand and can provide value to the left operanda&=b
**=
operator will evaluate the exponent value with the help of operands an assign value to the left operanda**=b

Here we have listed each of the Assignment operators

1. What is Assign Operator?

This assign operator will provide the value of the right side of the expression to the left operand.

2. What is Add and Assign

This Add and Assign operator will function to add the right side operand with the left side operator, and provide the result to the left operand.

3. What is Subtract and assign ?

This subtract and assign operator works to subtract the right operand from the left operand and give the result to the left operand.

4. What is Multiply and assign ?

This Multiply and assign will function to multiply the right operand with the left operand and will provide the result in the left operand.

5. What is Divide and assign Operator?

This functions to divide the left operand and provides results at the left operand.

6. What is Modulus and Assign Operator?

This operator functions using the modulus with the left and the right operand and provides results at the left operand.

7. What is Divide ( floor)and Assign Operator?

This operator will divide the left operand with the right operand, and provide the result at the left operand.

8. What is Exponent and Assign Operator?

This operator will function to evaluate the exponent and value with the operands and, provide output in the left operand.

9.What is Bitwise and Assign Operator?

This operator will function Bitwise AND on both the operand and provide the result on the left operand.

10. What is Bitwise OR and Assign Operator?

This operand will function Bitwise OR on the operand, and can provide result at the left operand.

11. What is Bitwise XOR and Assign Operator?

This operator will function for Bitwise XOR on the operands, and provide result at the left operand.

12. What is Bitwise Right Shift and Assign Operator?

This operator will function by providing the Bitwise shift on the operands and giving the result at the left operand.

13. What is Bitwise Left shift and Assign Operator?

This operator will function Bitwise left shift by providing the Bitwise left shift on the operands and giving the result on the left operand.

To conclude, different types of assignment operators are discussed in this. Beginners can improve their knowledge and understand how to apply the assignment operators through reading this.

Assignment Operators in Python- FAQs

Q1. what is an assignment statement in python.

Ans. It will calculate the expression list and can provide a single resulting object to each target list from left to right

Q2. What is the compound operator in Python?

Ans. The compound operator will do the operation of a binary operator and will save the result of the operation at the left operand.

Q3. What are the two types of assignment statements

Ans. Simple Assignment Statements and Reference Assignment Statements are the two types of assignment statements.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Python Logical Operators

Python Bitwise Operator

Leave a Comment Cancel reply

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

Reach Out to Us for Any Query

SkillVertex is an edtech organization that aims to provide upskilling and training to students as well as working professionals by delivering a diverse range of programs in accordance with their needs and future aspirations.

© 2024 Skill Vertex

  • Read Tutorial
  • Watch Guide Video

If that is about as clear as mud don't worry we're going to walk through a number of examples. And one very nice thing about the syntax for assignment operators is that it is nearly identical to a standard type of operator. So if you memorize the list of all the python operators then you're going to be able to use each one of these assignment operators quite easily.

The very first thing I'm going to do is let's first make sure that we can print out the total. So right here we have a total and it's an integer that equals 100. Now if we wanted to add say 10 to 100 how would we go about doing that? We could reassign the value total and we could say total and then just add 10. So let's see if this works right here. I'm going to run it and you can see we have a hundred and ten. So that works.

large

However, whenever you find yourself performing this type of calculation what you can do is use an assignment operator. And so the syntax for that is going to get rid of everything here in the middle and say plus equals and then whatever value. In this case I want to add onto it.

So you can see we have our operator and then right afterward you have an equal sign. And this is going to do is exactly like what we had before. So if I run this again you can see total is a hundred and ten

large

I'm going to just so you have a reference in the show notes I'm going to say that total equals total plus 10. This is exactly the same as what we're doing right here we're simply using assignment in order to do it.

I'm going to quickly go through each one of the other elements that you can use assignment for. And if you go back and you reference the show notes or your own notes for whenever you kept track of all of the different operators you're going to notice a trend. And that is because they're all exactly the same. So here if I want to subtract 10 from the total I can simply use the subtraction operator here run it again. And now you can see we have 90. Now don't be confused because we only temporarily change the value to 1 10. So when I commented this out and I ran it from scratch it took the total and it subtracted 10 from that total and that's what got printed out.

large

I'm going to copy this and the next one down the line is going to be multiplication. So in this case I'm going to say multiply with the asterisk the total and I'm just going to say times two just so we can see exactly what the value is going to be. And now we can see that's 200 which makes sense.

large

So we've taken total we have multiplied it by two and we have piped the entire thing into the total variable. So far so good. As you may have guessed next when we're going to do is division. So now I'm going to say total and then we're going to perform this division assignment and we're going to say divide this by 10 run it and you can see it gives us the value and it converts it to a float of ten point zero.

large

Now if this is starting to get a little bit much. Let's take a quick pause and see exactly what this is doing. Remember that all we're doing here is it's a shortcut. You could still perform it the same way we have in number 3 I could say total is equal to the total divided by 10. And if I run this you'll see we get ten point zero. And let's see what this warning is it says redefinition of total type from int to float. So we don't have to worry about this and this for if you're building Python programs you're very rarely ever going to see the syntax and it's because we have this assignment operator right here. So that is for division. And we also have the ability to use floor division as well. So if I run this you're going to see it's 10. But one thing you may notice is it's 10 it's not ten point zero. So remember that our floor division returns an integer it doesn't return a floating-point number. So if that is what you want then you can perform that task just like we did there.

Next one on the list is our exponents. I'm going to say the total and we're going to say we're going to assign that to the total squared. So going to run this and we get ten thousand. Just like you'd expect. And we have one more which is the modulus operator. So here remember it is the percent equals 2. And this is going to return zero because 100 is even if we changed 100 to be 101. This is going to return one because remember the typical purpose of the modulus operator is to let you know if you're working with an event or an odd value.

large

Now with all this being said, I wanted to show you every different option that you could use the assignment operator on. But I want to say that the most common way that you're going to use this or the most common one is going to be this one right here where we're adding or subtracting. So those are going to be the two most common. And what usually you're going to use that for is when you're incrementing or decrementing values so a very common way to do this would actually be like we have our total right here. So we have a total of 100 and you could imagine it being a shopping cart and it's 100 dollars and you could say product 2 and set this equal to 120. And then if I say product 3 and set this equal to 10. And so what I could do here is I could say total plus equals product to and then we could take the value and say product 3 and now if I run this you can see the value is 230.

large

So that's a very common way whenever you want to generate a sum you can use this type of syntax which is much faster and it's also going to be a more pythonic way it's going to be the way you're going to see in standard Python programs whenever you're wanting to generate a sum and then reset and reassign the value.

So in review, that is how you can use assignment operators in Python.

devCamp does not support ancient browsers. Install a modern version for best experience.

  • Python Home
  • Python 2 vs 3
  • Python Installation
  • Python IDLE
  • CGI Programming
  • Python Syntax
  • Python Print Statement
  • Python Variable
  • Python Data Type

Python Operators

  • Python If elif else
  • Python For Loop
  • Python While Loop
  • Python break, continue
  • Python Bytes, Bytearray
  • Python Regular Expression
  • Python String
  • Python Lists
  • Python Dictionary
  • Python Tuples
  • Python Sets
  • Python Date and Time
  • Python User define function
  • Python Module
  • Python Library
  • Python Calendar Module
  • Python Classes
  • Python Built-in Functions
  • Python Standard Library
  • Python Functions Examples
  • ..More to come..

Operators and Operands

In computer programming languages operators are special symbols which represent computations, conditional matching etc. The values the operator uses are called operands.

Python supports following operators.

  • Operators commands
  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Bitwise Operator

Conditional Operators

Operator precedence.

Operator: Commands

Module of functions that provide the functionality of operators.

Python Arithmetic Operators

Operator Name Example Result
+ Addition x+y Sum of x and y.
- Subtraction x-y Difference of x and y.
* Multiplication x*y Product of x and y.
/ Division x/y Quotient of x and y.
% Modulus x%y Remainder of x divided by y.
** Exponent x**y x**y will give x to the power y
// Floor Division x/ y The division of operands where the result is the quotient in which the digits after the decimal point are removed.

See the following statements in Python Shell.

Python arithmetic operators

Python Comparison Operators

Operator Name Example Result
== Equal x==y True if x is exactly equal to y.
!= Not equal x!=y True if x is exactly not equal to y.
> Greater than x>y True if x (left-hand argument) is greater than y (right-hand argument).
< Less than x<y True if x (left-hand argument) is less than y (right-hand argument).
>= Greater than or equal to x>=y True if x (left-hand argument) is greater than or equal to y (left-hand argument).
<= Less than or equal to x<=y True if x (left-hand argument) is less than or equal to y (right-hand argument).

Python comparison operators

Python Logical Operators

Operator Example Result
and (x and y) is True if both x and y are true.
or (x or y) is True if either x or y is true.
not (x not y) If a condition is true then Logical not operator will make false.

Python Logical Operators

Python Assignment Operators

Operator Shorthand Expression Description
+= x+=y x = x + y Adds 2 numbers and assigns the result to left operand.
-= x-= y x = x -y Subtracts 2 numbers and assigns the result to left operand.
*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand.
/= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.
%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result to left operand.
**= x**=y x = x**y Performs exponential (power) calculation on operators and assign value to the equivalent to left operand.
//= x//=y x = x//y Performs floor division on operators and assign value to the left operand.

Python assignment operators

Python Bitwise Operators

Operator Shorthand Expression Description
& And x & y Bits that are set in both x and y are set.
| Or x | y Bits that are set in either x or y are set.
^ Xor x ^ y Bits that are set in x or y but not both are set.
~ Not ~x Bits that are set in x are not set, and vice versa.
<< Shift left x <<y Shift the bits of x, y steps to the left
>> Shift right x >>y Shift the bits of x, y steps to the right.

# Each step means 'multiply by two' * Each step means 'divide by two'

Conditional expressions or ternary operator have the lowest priority of all Python operations. The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

Operator precedence determines how operators are parsed concerning each other. The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

Note: Comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

Operator Name Description
:= Assignment expression
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, Comparisons, including membership tests and identity tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
Shifts
+, - Addition and subtraction
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference
(expressions...),[expressions...], {key: value...}, {expressions...} Binding or parenthesized expression, list display, dictionary display, set display

Previous: Python Data Type Next: Python If elif else

Test your Python skills with w3resource's quiz

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • 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

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Vertical bar in Python bitwise assignment operator

There is a code and in class' method there is a line:

I can't understand what it means. I didn't find (|=) in the list of basic Python operators.

Jeffrey Bauer's user avatar

4 Answers 4

That is a bitwise or with assignment. It is equivalent to

Read more here .

Elliott Frisch's user avatar

  • 3 Mostly equivalent - it might be done in-place, depending on the object. –  user2357112 Commented Jan 20, 2014 at 20:49

In python, | is short hand for calling the object's __or__ method, as seen here in the docs and this code example:

Let's see what happens when use | operator with this generic object.

As you can see the, the __or__ method was called. int , 'set', 'bool' all have an implementation of __or__ . For numbers and bools, it is a bitwise OR. For sets, it's a union. So depending on the type of the attribute or variable, the behavior will be different. Many of the bitwise operators have set equivalents, see more here .

Alejandro's user avatar

I should add that "bar-equals" is now (in 2018) most popularly used as a set-union operator to append elements to a set if they're not there yet.

One use-case for this, say, in natural language processing, is to extract the combined alphabet of several languages:

russian_spy's user avatar

For an integer this would correspond to Python's "bitwise or" method. So in the below example we take the bitwise or of 4 and 1 to get 5 (or in binary 100 | 001 = 101):

More generalised (as Alejandro says) is to call an object's or method, which can be defined for a class in the form:

So in the specific case of an integer, we are calling the or method which resolves to a bitwise or, as defined by Python.

Sami Start's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python python-2.7 operators or ask your own question .

  • The Overflow Blog
  • Battling ticket bots and untangling taxes at the frontiers of e-commerce
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • What do all branches of Mathematics have in common to be considered "Mathematics", or parts of the same field?
  • Are "lie low" and "keep a low profile" interchangeable?
  • If a body in free fall, according to general relativity is weightless, that is, not experiencing force, how does the object gain kinetic energy?
  • Ecuador: what not to take into the rainforest due to humidity?
  • Why do only 2 USB cameras work while 4 USB cameras cannot stream at once?
  • Choosing a relative large density subsequence from a low density sequence
  • Is this misleading "convenience fee" legal?
  • Trigger (after delete) restricts from deleting records
  • How can I understand op-amp operation modes?
  • The number of triple intersections of lines
  • One number grid, two ways to divide it
  • VerificationTest leaks message?
  • How to report the between study variance through tau2 for vaccine effectiveness using R's metafor?
  • Did anyone ever ask Neil Armstrong whether he said "for man" or "for a man?"
  • What is this surface feature near Shackleton crater classified as?
  • Has any spacecraft ever been severely damaged by a micrometeriote?
  • Is it possible to create your own toy DNS root zone?
  • What is the rationale behind requiring ATC to retire at age 56?
  • Is "UN law" a thing?
  • Who is affected by Obscured areas?
  • Fitting the 9th piece into the pizza box
  • What prevents applications from misusing private keys?
  • Does the Telephone Consumer Protection Act apply to iMessages?
  • Which BASIC dialect first featured a single-character comment introducer?

assignments and shortcut operators in python

IMAGES

  1. What are Shortcut Operators in Python and How to use Shortcut Operator?

    assignments and shortcut operators in python

  2. How to Use Assignment Operators in Python

    assignments and shortcut operators in python

  3. Operators and Types of Operators

    assignments and shortcut operators in python

  4. Assignment Operators in Python

    assignments and shortcut operators in python

  5. Python Operators

    assignments and shortcut operators in python

  6. Python operators

    assignments and shortcut operators in python

COMMENTS

  1. Python Operators Cheat Sheet

    Augmented assignment operators are simply used as a shortcut. Instead of writing x = x + 1, they allow us to write x += 1, effectively "updating" a variable in a concise manner. Here's a code sample of how this works: # Initial assignment. x = 10. print(x) . # output: 10. # Augmented assignment operator: subtraction. x -= 2.

  2. Assignment Operators in Python

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

  3. Shortcut Operators in Python

    Firstly, we can use the shortcut operator of the assignment if we have the same operand on both sides of the operation. Moreover, using shortcut operators reduce redundancy. We have all shortcut variations for binary arithmetic operators. *Additionally, c = c * 5 can be written as c = 5 in shortcut operation. Also, rev = rev + num % 10 =can be ...

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

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

  6. Operators and Expressions in Python

    For a deep dive into how this operator works, check out The Walrus Operator: Python's Assignment Expressions. Unlike regular assignments, assignment expressions do have a return value ... all the arithmetic operators have an augmented version in Python. You can use these augmented operators as a shortcut when creating accumulators, counters ...

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

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

    Moreover, Python's assignment operators support chaining, which brings another layer of elegance to variable management. ... 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 ...

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

  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. Operators and Expressions

    This shortcut works for all of the math operators we have seen so far: +, -, *, /, //, %, and ** by adding = to the end of the operator. Exercise. Given the variable x, use the assignment shortcuts to modify its value with the following operations: Multiply x by 3; Divide x by 2; Add 10 to x

  12. Assignment Operators in Python

    An assignment operator is a symbol that you use in Python to indicate that you want to perform some action and then assign the value to a . You would use an addition or subtraction operator in Python when you want to calculate the result of adding or subtracting two numbers. There are two types of addition operators: the plus sign + and the ...

  13. Types of Operators in Python ( With Examples )

    3. Python Assignment Operators. Python assignment operators are used to assign values to variables in Python. The single equal symbol (=) is the most fundamental assignment operator. It assigns the value on the operator's right side to the variable on the operator's left side.

  14. Assignment Operators in Python

    a /= b. %=. Divide AND will divide the left operand with the right operand and then assign to the left operand. a %= b. <<=. It functions bitwise left on operands and will assign value to the left operand. a <<= b. >>=. This operator will perform right shift on operands and can assign value to the left operand.

  15. How exactly do the shortcut operators work in python?

    1. I started learning python and while i was checking some of the examples about shortcut operators I ran into this one. a = 6. b = 3. a /= 2 * b. print(a) which print 1.0 as the result which i'm sure is wrong because it's supposed to be the simplified version of: a = a / 2 * b.

  16. python

    Since Python 3.8, code can use the so-called "walrus" operator (:=), documented in PEP 572, for assignment expressions.This seems like a really substantial new feature, since it allows this form of assignment within comprehensions and lambdas.. What exactly are the syntax, semantics, and grammar specifications of assignment expressions?

  17. How to Use Assignment Operators in Python

    So if you memorize the list of all the python operators then you're going to be able to use each one of these assignment operators quite easily. The very first thing I'm going to do is let's first make sure that we can print out the total. So right here we have a total and it's an integer that equals 100. Now if we wanted to add say 10 to 100 ...

  18. Assignment Operators in Python:

    Python offers several compound assignment operators, which combine an operation with assignment. They provide a shortcut to perform an operation and update a variable in a single step. 1.Addition ...

  19. Python Operators

    In computer programming languages operators are special symbols which represent computations, conditional matching etc. The values the operator uses are called operands. c = a + b Here a and b are called operands and '+' is an operator. Python supports following operators. Contents: Operators commands. Arithmetic Operators. Comparison Operators.

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

  21. Python Operator Precedence with Shortcut Operator?

    My understanding is that the assignment operators are calculated at the moment of assigning the value to the variable. Python first works on the operations to the right of the assignment operator 2 * 3 then lastly works on the shortcut (assignment) operator calculation x /= 6. if x=6, then x /= 2 * 3 is calculated as: x = x / (2 * 3) x = 6 / (2 ...

  22. Python if-else short-hand

    The most readable way is. x = 10 if a > b else 11. but you can use and and or, too: x = a > b and 10 or 11. The "Zen of Python" says that "readability counts", though, so go for the first way. Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False. However, if more than the assignment depends on this ...

  23. Vertical bar in Python bitwise assignment operator

    Vertical bar in Python bitwise assignment operator. Ask Question Asked 10 years, 7 months ago. Modified 6 years, 6 months ago. ... I didn't find (|=) in the list of basic Python operators. python; python-2.7; operators; Share. Follow edited Jan 20, 2014 at 21:21. Jeffrey Bauer. 14k 9 9 gold badges 53 53 silver badges 74 74 bronze badges.