# Python 3 Assignment Operators

Operators are used to perform operations on values and variables. Operators can manipulate individual items and returns a result. The data items are referred as operands or arguments. Operators are either represented by keywords or special characters. For example, for identity operators we use keyword "is" and "is not".

In this tutorial, we going to learn various operators

## Arithmetic Operators

Arithmetic Operators perform various arithmetic calculations like addition, subtraction, multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic calculation in Python like you can use the eval function, declare variable & calculate, or call functions.

**Example**: For arithmetic operators we will take simple example of addition where we will add two-digit 4+5=9

Similarly, you can use other arithmetic operators like for multiplication(*), division (/), substraction (-), etc.

## Comparison Operators

These operators compare the values on either side of the operand and determine the relation between them. It is also referred as relational operators. Various comparison operators are ( ==, != , <>, >,<=, etc)

**Example**: For comparison operators we will compare the value of x to the value of y and print the result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns false.

Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)

## Python Assignment Operators

Python assignment operators are used for assigning the value of the right operand to the left operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.)

**Example**: Python assignment operators is simply to assign the value, for example

**Example of compound assignment operator**

We can also use a compound assignment operator, where you can add, subtract, multiply right operand to left and assign addition (or any other arithmetic function) to the left operand.

- Step 1: Assign value to num1 and num2
- Step 2: Add value of num1 and num2 (4+5=9)
- Step 3: To this result add num1 to the output of Step 2 ( 9+4)
- Step 4: It will print the final result as 13

## Logical Operators

Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.

- For AND operator – It returns TRUE if both the operands (right side and left side) are true
- For OR operator- It returns TRUE if either of the operand (right side or left side) is true
- For NOT operator- returns TRUE if operand is false

**Example**: Here in example we get true or false based on the value of a and b

## Membership Operators

These operators test for membership in a sequence such as lists, strings or tuples. There are two membership operators that are used in Python. (in, not in). It gives the result based on the variable present in specified sequence or string

**Example**: For example here we check whether the value of x=4 and value of y=8 is available in list or not, by using **in** and **not in **operators.

- Declare the value for x and y
- Declare the value of list
- Use the "in" operator in code with if statement to check the value of x existing in the list and print the result accordingly
- Use the "not in" operator in code with if statement to check the value of y exist in the list and print the result accordingly
- Run the code- When the code run it gives the desired output

## Identity Operators

To compare the memory location of two objects, Identity Operators are used. The two identify operators used in Python are (is, is not).

- Operator is: It returns true if two variables point the same object and false otherwise
- Operator is not: It returns false if two variables point the same object and true otherwise

Following operands are in decreasing order of precedence.

Operators in the same box evaluate left to right

Operators (Decreasing order of precedence) | Meaning |
---|---|

** | Exponent |

*, /, //, % | Multiplication, Division, Floor division, Modulus |

+, - | Addition, Subtraction |

<= < > >= | Comparison operators |

= %= /= //= -= += *= **= | Assignment Operators |

is is not | Identity operators |

in not in | Membership operators |

not or and | Logical operators |

**Example**:

- Declare the value for variable x and y
- Use the operator "is" in code to check if value of x is same as y
- Next we use the operator "is not" in code if value of x is not same as y
- Run the code- The output of the result is as expected

## Operator precedence

The operator precedence determines which operators need to be evaluated first. To avoid ambiguity in values, precedence operators are necessary. Just like in normal multiplication method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the answer is 23, to change the order of precedence we use a square bracket (3+4)*5, now the answer is 35. Precedence operator used in Python are (unary + - ~, **, * / %, + - , &) etc.

v = 4 w = 5 x = 8 y = 2 z = 0 z = (v+w) * x / y; print("Value of (v+w) * x/ y is ", z)- Declare the value of variable v,w…z
- Now apply the formula and run the code
- The code will execute and calculate the variable with higher precedence and will give the output

### Python 2 Example

Above examples are Python 3 codes, if you want to use Python 2, please consider following codes

#Arithmetic Operators x= 4 y= 5 print x + y #Comparison Operators x = 4 y = 5 print('x > y is',x>y) #Assignment Operators num1 = 4 num2 = 5 print ("Line 1 - Value of num1 : ", num1) print ("Line 2 - Value of num2 : ", num2) #compound assignment operator num1 = 4 num2 = 5 res = num1 + num2 res += num1 print ("Line 1 - Result of + is ", res) #Logical Operators a = True b = False print('a and b is',a and b) print('a or b is',a or b) print('not a is',not a) #Membership Operators x = 4 y = 8 list = [1, 2, 3, 4, 5 ]; if ( x in list ): print "Line 1 - x is available in the given list" else: print "Line 1 - x is not available in the given list" if ( y not in list ): print "Line 2 - y is not available in the given list" else: print "Line 2 - y is available in the given list" #Identity Operators x = 20 y = 20 if ( x is y ): print "x & y SAME identity" y=30 if ( x is not y ): print "x & y have DIFFERENT identity" #Operator precedence v = 4 w = 5 x = 8 y = 2 z = 0 z = (v+w) * x / y; print "Value of (v+w) * x/ y is ", z### Summary:

Operators in a programming language are used to perform various operations on values and variables. In Python, you can use operators like

- There are various methods for arithmetic calculation in Python as you can use the eval function, declare variable & calculate, or call functions
- Comparison operators often referred as relational operators are used to compare the values on either side of them and determine the relation between them
- Python assignment operators are simply to assign the value to variable
- Python also allows you to use a compound assignment operator, in a complicated arithmetic calculation, where you can assign the result of one operand to the other
- For AND operator – It returns TRUE if both the operands (right side and left side) are true
- For OR operator- It returns TRUE if either of the operand (right side or left side) is true
- For NOT operator- returns TRUE if operand is false
- There are two membership operators that are used in Python. (in, not in).
- It gives the result based on the variable present in specified sequence or string
- The two identify operators used in Python are (is, is not)
- It returns true if two variables point the same object and false otherwise
Precedence operator can be useful when you have to set priority for which calculation need to be done first in a complex calculation.

## 2. Variables, expressions and statements¶

## 2.1. Values and data types¶

A **value** is one of the fundamental things — like a letter or a number — that a program manipulates. The values we have seen so far are (the result when we added ), and .

These values belong to different **data types**: is an *integer*, and is a *string*, so-called because it contains a string of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

The print statement also works for integers.

If you are not sure what type a value has, the interpreter can tell you.

Not surprisingly, strings belong to the type **str** and integers belong to the type **int**. Less obviously, numbers with a decimal point belong to a type called **float**, because these numbers are represented in a format called *floating-point*.

What about values like and ? They look like numbers, but they are in quotation marks like strings.

They’re strings.

Strings in Python can be enclosed in either single quotes (‘) or double quotes (”):

Double quoted strings can contain single quotes inside them, as in , and single quoted strings can have double quotes inside them, as in .

When you type a large integer, you might be tempted to use commas between groups of three digits, as in . This is not a legal integer in Python, but it is legal:

Well, that’s not what we expected at all! Python interprets as a list of three items to be printed. So remember not to put commas in your integers.

## 2.2. Variables¶

One of the most powerful features of a programming language is the ability to manipulate **variables**. A variable is a name that refers to a value.

The **assignment statement** creates new variables and gives them values:

This example makes three assignments. The first assigns the string to a new variable named . The second gives the integer to , and the third gives the floating-point number to .

The **assignment operator**, , should not be confused with an equals sign (even though it uses the same character). Assignment operators link a *name*, on the left hand side of the operator, with a *value*, on the right hand side. This is why you will get an error if you enter:

A common way to represent variables on paper is to write the name with an arrow pointing to the variable’s value. This kind of figure is called a **state diagram** because it shows what state each of the variables is in (think of it as the variable’s state of mind). This diagram shows the result of the assignment statements:

The print statement also works with variables.

In each case the result is the value of the variable. Variables also have types; again, we can ask the interpreter what they are.

The type of a variable is the type of the value it refers to.

## 2.3. Variable names and keywords¶

Programmers generally choose names for their variables that are meaningful — they document what the variable is used for.

**Variable names** can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. Although it is legal to use uppercase letters, by convention we don’t. If you do, remember that case matters. and are different variables.

The underscore character ( ) can appear in a name. It is often used in names with multiple words, such as or .

If you give a variable an illegal name, you get a syntax error:

is illegal because it does not begin with a letter. is illegal because it contains an illegal character, the dollar sign. But what’s wrong with ?

It turns out that is one of the Python **keywords**. Keywords define the language’s rules and structure, and they cannot be used as variable names.

Python has thirty-one keywords:

and | as | assert | break | class | continue |

def | del | elif | else | except | exec |

finally | for | from | global | if | import |

in | is | lambda | not | or | pass |

raise | return | try | while | with | |

yield |

You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.

## 2.4. Statements¶

A **statement** is an instruction that the Python interpreter can execute. We have seen two kinds of statements: print and assignment.

When you type a statement on the command line, Python executes it and displays the result, if there is one. The result of a print statement is a value. Assignment statements don’t produce a result.

A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.

For example, the script

produces the output:

Again, the assignment statement produces no output.

## 2.5. Evaluating expressions¶

An **expression** is a combination of values, variables, and operators. If you type an expression on the command line, the interpreter **evaluates** it and displays the result:

The *evaluation of an expression* produces a value, which is why expressions can appear on the right hand side of assignment statements. A value all by itself is a simple expression, and so is a variable.

Confusingly, evaluating an expression is not quite the same thing as printing a value.

When the Python shell displays the value of an expression, it uses the same format you would use to enter a value. In the case of strings, that means that it includes the quotation marks. But the print statement prints the value of the expression, which in this case is the contents of the string.

In a script, an expression all by itself is a legal statement, but it doesn’t do anything. The script

produces no output at all. How would you change the script to display the values of these four expressions?

## 2.6. Operators and operands¶

**Operators** are special symbols that represent computations like addition and multiplication. The values the operator uses are called **operands**.

The following are all legal Python expressions whose meaning is more or less clear:

The symbols , , and , and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk () is the symbol for multiplication, and is the symbol for exponentiation.

When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed.

Addition, subtraction, multiplication, and exponentiation all do what you expect, but you might be surprised by division. The following operation has an unexpected result:

The value of is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing **integer division**.

When both of the operands are integers, the result must also be an integer, and by convention, integer division always rounds *down*, even in cases like this where the next integer is very close.

A possible solution to this problem is to calculate a percentage rather than a fraction:

Again the result is rounded down, but at least now the answer is approximately correct. Another alternative is to use floating-point division. We’ll see in the chapter 4 how to convert integer values and variables to floating-point values.

## 2.7. Order of operations¶

When more than one operator appears in an expression, the order of evaluation depends on the **rules of precedence**. Python follows the same precedence rules for its mathematical operators that mathematics does. The acronym PEMDAS is a useful way to remember the order of operations:

**P**arentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, is 4, and is 8. You can also use parentheses to make an expression easier to read, as in , even though it doesn’t change the result.**E**xponentiation has the next highest precedence, so is 3 and not 4, and is 3 and not 27.**M**ultiplication and**D**ivision have the same precedence, which is higher than**A**ddition and**S**ubtraction, which also have the same precedence. So yields 5 rather than 4, and is -1, not 1 (remember that in integer division, 2/3=0).- Operators with the same precedence are evaluated from left to right. So in the expression , the multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had been evaluated from right to left, the result would have been , which is 59, which is wrong.

## 2.8. Operations on strings¶

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal (assuming that has type string):

Interestingly, the operator does work with strings, although it does not do exactly what you might expect. For strings, the operator represents **concatenation**, which means joining the two operands by linking them end-to-end. For example:

The output of this program is . The space before the word is part of the string, and is necessary to produce the space between the concatenated strings.

The operator also works on strings; it performs repetition. For example, is . One of the operands has to be a string; the other has to be an integer.

On one hand, this interpretation of and makes sense by analogy with addition and multiplication. Just as is equivalent to , we expect to be the same as , and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition and multiplication have that string concatenation and repetition do not?

## 2.9. Input¶

There are two built-in functions in Python for getting keyboard input:

A sample run of this script would look something like this:

Each of these functions allows a *prompt* to be given to the function between the parentheses.

## 2.10. Composition¶

So far, we have looked at the elements of a program — variables, expressions, and statements — in isolation, without talking about how to combine them.

One of the most useful features of programming languages is their ability to take small building blocks and **compose** them. For example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:

In reality, the addition has to happen before the printing, so the actions aren’t actually happening at the same time. The point is that any expression involving numbers, strings, and variables can be used inside a print statement. You’ve already seen an example of this:

You can also put arbitrary expressions on the right-hand side of an assignment statement:

This ability may not seem impressive now, but you will see other examples where composition makes it possible to express complex computations neatly and concisely.

Warning: There are limits on where you can use certain expressions. For example, the left-hand side of an assignment statement has to be a

variablename, not an expression. So, the following is illegal: .

## 2.12. Glossary¶

- assignment operator
- is Python’s assignment operator, which should not be confused with the mathematical comparison operator using the same symbol.
- assignment statement
A statement that assigns a value to a name (variable). To the left of the assignment operator, , is a name. To the right of the assignment operator is an expression which is evaluated by the Python interpreter and then assigned to the name. The difference between the left and right hand sides of the assignment statement is often confusing to new programmers. In the following assignment:

plays a very different role on each side of the . On the right it is a

*value*and makes up part of the*expression*which will be evaluated by the Python interpreter before assigning it to the name on the left.- Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.
- composition
- The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.
- concatenate
- To join two strings end-to-end.
- data type
- A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are integers (type ), floating-point numbers (type ), and strings (type ).
- evaluate
- To simplify an expression by performing the operations in order to yield a single value.
- expression
- A combination of variables, operators, and values that represents a single result value.
- float
- A Python data type which stores
*floating-point*numbers. Floating-point numbers are stored internally in two parts: a*base*and an*exponent*. When printed in the standard format, they look like decimal numbers. Beware of rounding errors when you use s, and remember that they are only approximate values. - int
- A Python data type that holds positive and negative whole numbers.
- integer division
- An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.
- keyword
- A reserved word that is used by the compiler to parse program; you cannot use keywords like , , and as variable names.
- operand
- One of the values on which an operator operates.
- operator
- A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
- rules of precedence
- The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.
- state diagram
- A graphical representation of a set of variables and the values to which they refer.
- statement
- An instruction that the Python interpreter can execute. Examples of statements include the assignment statement and the print statement.
- str
- A Python data type that holds a string of characters.
- value
- A number or string (or other things to be named later) that can be stored in a variable or computed in an expression.
- variable
- A name that refers to a value.
- variable name
- A name given to a variable. Variable names in Python consist of a sequence of letters (a..z, A..Z, and _) and digits (0..9) that begins with a letter. In best programming practice, variable names should be chosen so that they describe their use in the program, making the program
*self documenting*.

## 2.13. Exercises¶

Record what happens when you print an assignment statement:

How about this?

Or this?

Can you think of a general rule for what can follow the statement? What does the statement return?

>>> print5.2,"this",4-2,"that",5/2.0Take the sentence:

*All work and no play makes Jack a dull boy.*Store each word in a separate variable, then print out the sentence on one line using print.Add parenthesis to the expression to change its value from 4 to -6.

Place a comment before a line of code that previously worked, and record what happens when you rerun the program.

The difference between and is that evaluates the input string and does not. Try the following in the interpreter and record what happens:

What happens if you try the example above without the quotation marks?

Describe and explain each result.

>>> x=input()3.14>>> type(x)>>> x=raw_input()3.14>>> type(x)>>> x=input()'The knights who say "ni!"'>>> x>>> x=input()The knights who say "ni!">>> x>>> x=raw_input()'The knights who say "ni!"'>>> xStart the Python interpreter and enter at the prompt. This will give you an error:

Assign a value to so that evaluates to .

NameError:name'bruce'isnotdefinedWrite a program (Python script) named , which asks the user to enter a series of nouns, verbs, adjectives, adverbs, plural nouns, past tense verbs, etc., and then generates a paragraph which is syntactically correct but semantically ridiculous (see http://madlibs.org for examples).