ASSIGNMENT
Easy now … we’re talking about assigning values in Python not a class assignment.
Before we talk about addition, subtraction, multiplication, division and brackets and exponents, let’s talk about ‘=’.
Notice I never said ‘equal sign’. Start by calling ‘=’ the assignment operator.
To understand ‘=’ you must understand that assignment moves from RIGHT to LEFT.
When you write y = x, the computer understands to move the value in x to the variable y.
Assignment can only happen from RIGHT to LEFT.
So, what does 2 + 2 look like?
For starters it DOES NOT look like:
2 + 2 = 4
It looks like:
4 = 2 + 2
Always. Forever and ever.
Operands
The operands are the values on either side of the operator. So in the statement:
x + y
x and y are the operands and + is the operator.
Operators
Operators are symbols that help us perform calculations.
Here are a couple you’ve picked up over the years thanks to your math teachers: +, -, ×, ÷
Addition, subtraction and multiplication all behave the way you think they should.
Sometimes division doesn’t give you the answer you expect.
Addition (+)
Adds values on either side of the operator.
answer = 3 + 2 print(answer) #OUTPUT: 5
Subtraction (-)
Subtracts right hand operand from the left hand operand.
answer = 3 - 2 print(answer) #OUTPUT: 1
Multiplication (*)
Multiplies values on either side of the operator.
answer = 3 * 2 print(answer) #OUTPUT: 6
Division (/)
If you divide 6 by 3, you get a predictable answer.
answer = 6 / 3 print(answer) #OUTPUT: 2.0
You will get the answer 2.0 because in Python 3 all divisions will result in a floating point value (decimal).
If you divide 3 by 2, you might be surprised by the answer.
answer = 3 / 2 print(answer) #OUTPUT: 1.5
If that’s the answer you were expecting, the why did I say you might be surprised by the answer? That’s because in Python 2, if you give Python 2 integers (whole number type) and ask it to perform division, will result in integer. In order to get a floating point answer, you must add a floating point type your operand(s).
In Python 3, however, you do not have to do this. Isn’t that great?! The code segments below will all result in the same output.
answer = 3 / 2 print(answer) #OUTPUT: 1.5 answer = 3.0/2 print(answer) #OUTPUT: 1.5 answer = 3.0/2.0 print(answer) #OUTPUT: 1.5
Floor Division (//)
Floor division is the same as division EXCEPT that the resulting decimal (if there is one) will rounded down to 0 (think of being dropped to the floor).
If the two operands involved in the equation are integers, then there will be no decimal value.
Let’s take the same example as before and see if the result is any different.
answer = 3 // 2 print(answer) #OUTPUT: 1 -->No decimal as both operands are integers answer = 3.0//2 print(answer) #OUTPUT: 1.0 -->Decimal as at least one operand is a floating point value answer = 3//2.0 print(answer) #OUTPUT: 1.0 -->Decimal as at least one operand is a floating point value answer = 3.0//2.0 print (answer) #OUTPUT: 1.0 -->Decimal as at least one operand is a floating point value
Exponents (**)
Performs exponential (power) calculation on operands.
answer = 3**2 #3 to the power of 2 print(answer) #OUTPUT: 9
Modulus (%)
%, the modulus operator allows us to calculate the remainder in integer division. Using % allows you to calculate if a number is even or odd, or it can be used to strip a digit into places.
answer = 6 % 2 print(answer) #OUTPUT: 0 --> 6/2 has a remainder of 0 answer = 17 % 2 print(answer) #OUTPUT: 1 --> 17/2 has a remainder of 1 print(132 % 100) #OUTPUT: 32 -->> 132/100 has a remainder of 32 print(132 % 10) #OUTPUT: 2 --> 132/10 has a remainder of 2
You Try
What values would be printed from the following code? Check your answer using the interpreter below.
print(9/3) print(24%7) print(-2+5) print(77-10) print(4*-2) print(.5**2) print(17//4)
Shortcuts
Often, you’ll find yourself adding or subtracting 1 to a variable.
This looks like
x = x + 1
Python, like most programming languages, has a shortcut for this:
x+=1 #This will take the value of x and add 1
Here are some other shortcuts as examples:
#Long Method x = x + 4 #Python Shortcut x += 4 #Long Method x = x - (-7) #Python Shortcut x -= -7 #Long Method x = x * 9 #Python Shortcut x *=9 #Long Method x = x / (-2) #Python Shortcut x /= -2
This can also be used for other variables. For instance:
thisNumber = thisNumber / 3
can also be represented by
thisNumber /=3
The shortcut method is the preferred method of most programmers. Get used to using it.
You Try
Try running the code shown above in the interpreter below. Feel free to change the code up to see the different results.
Order of Operations
Python has an order of operations (BEDMAS) just like in math class. Parenthesis work just like they do in math class.
Brackets
Exponents
Division
Multiplication
Addition
Subtraction
Although there are more operators to discuss, we will stick with the ones listed above for now.
Watch what happens when we run an expression involving mixed operators:
print(1+2*3) #OUTPUT: 7 #Python will multiply 2 and 3 FIRST and THEN add 1
If we were the change the expression by adding brackets (parentheses), we would get a different result:
print((1+2)*3) #OUTPUT: 9 #--> This time Python will add 1 and 2 FIRST and THEN multiply by 3
Let’s kick it up an notch shall we? See you you can determine the output of the following code snippet before executing it.
print ( ( ( ( ( 13 + 5 ) * 2 ) - 4 ) / 2) - 13 )
SPOILER ALERT: The answer is 3.0
Can you figure out why?
Formatting Output
Rounding Floating Point Values
There are times when you want to take control over the number that is displayed on the screen. For instance, if you are displaying a dollar amount you would not like to see this as your output:
Your Total Amount is: 1234.9876 dollars
You can change how a number is displayed by using the format function. Let’s look at the following example.
myValue = 12345.6789
Here we set assigned a floating point value to the variable myValue. If we were to print it we would simply get
12345.6789
We will use the format specifier to change how the code will be output. For example:
myValue = 12345.6789 print (format(12345.6789, '.2f')) print ( format(myValue, '.2f')) """ OUTPUT 12345.68 12345.68 """
In this example, we are formatting the number 12345.6789 whether it is assigned to a variable or not. It’s the second part, .2f, where things get interesting.
- The .2 specifies the precision. It indicates that we want to round the number to two decimal places.
- The f specifies that the data type of the number we are formatting is a floating-point number. This cannot be used with integers
You can easily adapt the code above to round to different decimal values.
myValue = 12345.6789 print (format(myValue, '.1f')) print (format(myValue, '.2f')) print ( format(myValue, '.3f')) """ OUTPUT 12345.7 12345.68 12345.679 """
Notice that Python will round the decimal value up or down (eg. 3.426 could become 3.43 and 2.812 could become 2.8 when rounded).
Inserting Comma Seperators
If you want the number to be formatted with comma separators, you can insert a comma into the format specifier, as shown here:
print(format(32765.4321, ',.2f')) #OUTPUT 32,765.43 print(format(123456.789, ',.1f')) #OUTPUT 123,3456.8
Putting the comma (,) before the decimal in the format specifier will allow Python to separate your number using commas.
Scientific Notation
If you prefer to display floating-point numbers in scientific notation, you can use the letter e or the letter E instead of f. For instance:
print(format(12345.6789, 'e')) #OUTPUT 1.234568e+04 print(format(12345.6789, '.2E')) #OUTPUT 1.23E+04
Notice that using a lowercase e will result in a lowercase e in the scientific notation. Alternatively, using an uppercase E will result in an uppercase E in the scientific notation.
Specifying a Minimum Width Field
The format specifier can also include a minimum field width, which is the minimum number of spaces that should be used to display the value.
The following example prints a number in a field that is 12 spaces wide:
print('The number is', format(75984.6814, '12,.2f')) """ OUTPUT The number is 75,984.68 """
In this example, since our output is only 9 characters in length, the output is right justified.
To clarify, we assigned 12 spaces for output:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
But our output is only 9 characters:
7 | 5 | , | 9 | 8 | 4 | . | 6 | 8 |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Python will then display our answer in the 12 spaces but will right-justify the output.
7 | 5 | , | 9 | 8 | 4 | . | 6 | 8 | |||
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
Notice that the first three spaces will be blank.
If a value is too large to fit in the specified field width, the field is automatically enlarged to accommodate it.
Field widths can help when you need to print numbers aligned in columns. For example:
#assign values to the variables num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 num5 = 88.081 num6 = 799.999 #dispay each value using 7 spaces and 2 decimal points print (format(num1, '7.2f')) print (format(num2, '7.2f')) print (format(num3, '7.2f')) print (format(num4, '7.2f')) print (format(num5, '7.2f'))
Your output will look like this:
127.90 3465.15 3.78 264.82 88.08 800.00
Alternatively, if we were to adapt the code to only allow for 6 spaces, it would look like
#assign values to the variables num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 num5 = 88.081 num6 = 799.999 #dispay each value using 7 spaces and 2 decimal points print (format(num1, '6.2f')) print (format(num2, '6.2f')) print (format(num3, '6.2f')) print (format(num4, '6.2f')) print (format(num5, '6.2f'))
The output would only affect num 2, since it has 7 characters in its output. The output would look like
127.9 3465.15 3.78 264.82 88.08 800.00
You Try
Create a program that stores the following numbers:
num1 = 127.899
num2 = 3465.148
num3 = 3.776
num4 = 264.821
num5 = 88.081
num6 = 799.999
Have your program output each value on a new line using 9 spaces and rounded to 1 decimal place.
Mixted Type Operations
When you perform a math operation on two operands, the data type of the result will depend on the data type of the operands. Python follows these rules when evaluating mathematical expressions:
- When an operation is performed on two int values, the result will be an int.
- When an operation is performed on two float values, the result will be a float.
- When an operation is performed on an int and a float, the int value will be temporarily converted to a float and the result of the operation will be a float.
(An expression that uses operands of different data types is called a mixed-type expression.)