Numbers and math¶
Goal: do arithmetic in Python and understand how integers and floats behave.
Why this matters¶
Almost every program does some math: totals, averages, scores, countdowns. Python handles it well, but there are a few surprises that trip up beginners. This lesson gets them out of the way early.
The operators¶
Python has seven arithmetic operators. Here they all are in one program:
print(7 + 3)
print(7 - 3)
print(7 * 3)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(2 ** 10)
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
addition | 7 + 3 |
10 |
- |
subtraction | 7 - 3 |
4 |
* |
multiplication | 7 * 3 |
21 |
/ |
division | 7 / 2 |
3.5 |
// |
floor division | 7 // 2 |
3 |
% |
modulo (remainder) | 7 % 2 |
1 |
** |
power | 2 ** 10 |
1024 |
The first three are what you expect. The last four deserve a closer look.
Division always gives a float¶
7 / 2 is 3.5, which makes sense. But 6 / 2 is 3.0, not 3. In Python, the / operator always produces
a float, even when the answer is a whole number. Keep this in mind when you print results: 3.0 and 3 look different on screen.
Floor division and modulo¶
// divides and throws away the fractional part, so 7 // 2 is 3. It answers "how many whole times does 2 fit into 7?"
% gives what is left over after that division, so 7 % 2 is 1. It answers "what remains?"
These two are a team. Together they split a number into whole parts and a remainder, which is exactly what you need for turning minutes into hours and minutes, or cents into dollars and cents:
The text after # is a comment. Python ignores it. Comments are notes for humans reading the code.
Is a number even or odd?
number % 2 is 0 for even numbers and 1 for odd numbers. You will use this trick constantly.
Power¶
2 ** 10 means 2 to the power of 10. 5 ** 2 is 5 squared, which is 25.
Order of operations¶
Python follows the same rules as school math: multiplication and division before addition and subtraction. Use parentheses to change the order.
When in doubt, add parentheses. Extra parentheses never hurt, and they make your intention clear to anyone reading the code.
Integers, floats, and rounding¶
Mixing an integer with a float gives a float: 3 * 1.5 is 4.5. Fine so far. But try this:
That is not a bug in Python. Computers store floats in binary, and some decimal fractions cannot be stored exactly, in the same way that one third cannot be written exactly in decimal. The error is tiny, but it shows up when you print.
The practical fix is round(). Give it the number and how many decimal places you want:
price = 19.99
quantity = 3
total = price * quantity
print(total)
print(round(total, 2))
print(round(total))
With no second argument, round() rounds to the nearest whole number and returns an integer.
Money and floats
For a course exercise, round(total, 2) is fine. Real banking software avoids floats entirely
and uses special decimal types instead. You will meet those much later.
Shorthand for updating a variable¶
Programs often do "take a variable, change it a bit, store it back", like score = score + 10.
Python has a shorter way to write that:
score = 0
score += 10
score += 5
score -= 3
print(score)
lives = 3
lives -= 1
print(lives)
score += 10 means exactly the same as score = score + 10. The same shorthand exists for every operator:
-=, *=, /=, //=, %=, **=.
Try it¶
Write a program that stores a price of 49.99 and a quantity of 4, then prints the total rounded to two decimal places.
Then change the quantity to 3 and run it again.
Common mistakes¶
ZeroDivisionError: division by zero
You divided by 0, possibly through a variable that happened to hold 0. Python refuses, because the answer is undefined.
TypeError: unsupported operand type(s) for +: 'int' and 'str'
You tried to add a number and text, often because you forgot to convert an input() value with int() or float().
The answer is 3.0 but I wanted 3
Not an error, but confusing. / always gives a float. If you want an integer result, use //, or wrap the result in int().
Exercises¶
- Tip calculator. Ask for the bill amount, then print a 15% tip and the total, both rounded to two decimal places.
- Minutes to hours. Ask for a number of minutes and print it as hours and minutes, for example
135 minutes is 2 hours and 15 minutes. - Temperature converter. Ask for a temperature in Celsius and print it in Fahrenheit, rounded to one decimal place.
The formula is
F = C * 9 / 5 + 32.
Solution 1
bill = float(input("Bill amount: "))
tip = bill * 0.15
total = bill + tip
print(f"Tip: {round(tip, 2)}")
print(f"Total: {round(total, 2)}")
We use float() rather than int() because a bill can have cents.
Solution 2
Solution 3
celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius} C is {round(fahrenheit, 1)} F.")
Try 100 and 0 to check your program. They should give 212.0 and 32.0.
Summary¶
- Seven operators:
+,-,*,/,//,%,**. /always gives a float.//and%split a division into whole part and remainder.- Multiplication and division happen before addition and subtraction. Parentheses override that.
- Floats can be slightly imprecise. Use
round(value, places)when printing. score += 10is shorthand forscore = score + 10.- Text after
#is a comment, ignored by Python.