0%

Values and Variables · practice

Let Python Do the Math

Numbers in a program can take part in calculations. You write the calculation, and Python produces a new .

print(8 + 4)

Python adds the two integers before print() runs, so the output is 12.

The calculation 8 + 4 is an . An expression is code that produces a value.

Four arithmetic operators

Python uses familiar symbols for addition and subtraction. Multiplication and division use symbols that are easy to type on a keyboard.

OperationPython ExampleResult
Addition+8 + 412
Subtraction-8 - 44
Multiplication*8 * 432
Division/8 / 42.0

Run all four:

Try it

Division with / produces a float, even when the result is a whole amount. That is why Python displays 2.0 instead of 2.

Numbers are not strings

Quotation marks still make an important difference:

Try it

The first line calculates. The second line prints text literally.

More than one operation

Python follows the usual arithmetic order: multiplication and division happen before addition and subtraction.

Try it

The first result is 14. In the second expression, parentheses tell Python to add first, so the result is 20.

Parentheses are useful even when they are not strictly required. They can make your intended order easier for another person to see.

Which expression asks Python to multiply 6 by 4?

Complete four calculations

The starter program already prints the sum and difference of 9 and 3.

Add two more print instructions:

  1. Multiply 9 by 3 with *.

  2. Divide 9 by 3 with /.

The complete output must be:

12
6
27
3.0

Write calculations inside print(). Do not type the results as quoted text. Python should do the arithmetic.

Task

Keep the existing addition and subtraction. Add two print instructions that multiply 9 by 3 and divide 9 by 3.

The output must be:

12
6
27
3.0