3 Numbers
In This Chapter
So far we have learned how to save and run our programs, get some input from the user, and print text to the screen. We also briefly met the different materials that make up a program: Integers, Floats, and Strings.
But before we can build more complex software, we really need to know our materials better. In this chapter, we will cover:
- Integers & Floats: The two ways computers handle numbers.
- Math Operators: Addition, subtraction, multiplication, and two types of division.
- Order of Operations: Controlling how the computer solves math.
- Advanced Expressions: Using exponents and the modulo operator.
- Updating Numbers: The shortcut for changing variables.
- Type Casting: Forcing data to change its shape.
- The Project: The Epic Loot Splitter!
3.1 Integers (int)
Integers are whole numbers without a decimal point or fraction. They can be positive, negative, or zero. Integers are great to use for any number value that will remain a whole number, like counting how many items are in a shopping cart, or tracking the days of the week.
# Examples of integers
lives = 3
current_level = 5
apples_in_basket = 12
# For very large numbers, you can use underscores to make them easier to read!
stars_in_galaxy = 200_000_000_000
# Integers can be negative too!
bank_balance = -1003.2 Floating-Point Numbers (float)
Floats are numbers that have a decimal point. Floats are used for measuring things that require precision beyond whole numbers, like weight, height, temperature, or money.
# Examples of floats
temperature = 98.6
pi = 3.14159
item_price = 4.99
time_adjustment = -0.25
# Floats can be whole numbers too, but they will always have a decimal point.
score_multiplier = 100.03.3 Number Math
Python can do all the basic math you already know. However, when doing math with numbers, Python will automatically handle the data types for you based on a few strict rules.
If you do math that mixes an integer and a float, Python will always turn the final answer into a float. Furthermore, using the division operator (/) will always result in a float, even if it divides perfectly! (10 / 2 becomes 5.0).
Let’s go back to the IDLE shell and test this out:
>>> 5 + 2
7
>>> 5 + 2.0
7.0
>>> 10 / 2
5.0
>>> 10.0 / 2
5.0
>>> 10.0 - 2
8.0Floor Division (//)
Because standard division (/) always gives you a float, sometimes it can cause problems if you strictly need a whole number.
Python gives us a second way to divide called Floor Division. It uses two slashes (//). Floor division divides the numbers and then instantly chops off the decimal, leaving you with a clean integer.
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3Notice how it doesn’t round up! Even if the answer is 3.9, floor division simply deletes the decimal and gives you 3.
3.4 Order of Operations
Maybe you learned about something called the order of operations in math class. Python also follows the order of operations. It is often remembered as PEMDAS. We calculate expressions in this order:
- Parentheses
- Exponents
- Multiplication
- Division
- Addition
- Subtraction
So if you want to force Python to do addition before multiplication, you could wrap that part of the expression in parentheses ().
# Multiplication happens first: 2 * 3 = 6, then 10 + 6 = 16
standard_math = 10 + 2 * 3
print(standard_math)
# Output: 16
# Parentheses force the addition first: 10 + 2 = 12, then 12 * 3 = 36
parentheses_math = (10 + 2) * 3
print(parentheses_math)
# Output: 36Just like in math, it is often wise to use parentheses to make your expressions more clear, even if they are not strictly necessary. It makes it easier for other programmers (and your future self) to read your code.
3.5 Exponents
If you want to multiply a number by itself (like 5 squared, or 5²), you use two asterisks **.
# 5 to the power of 2 (5 * 5)
squared = 5 ** 2
print(squared)
# Output: 25
# 2 to the power of 3 (2 * 2 * 2)
cubed = 2 ** 3
print(cubed)
# Output: 83.6 The Modulo Operator (%)
The percent sign % is called the Modulo operator (or mod for short). It divides two numbers, but instead of giving you the answer, it gives you the remainder.
The easiest way to understand this is to look at some examples in the IDLE shell.
>>> 10 % 3
1
>>> 8 % 5
3
>>> 20 % 4
0
>>> 5 % 5
0Why is this useful? As a programmer, you’ll find that the modulo operator is a powerful tool for solving many different problems. For example, if you want to know if a number is even or odd, you just use % 2. If the answer is 0, the number is perfectly even. If the answer is 1, it must be odd.
3.7 Updating Number Variables
In software, numbers change constantly. Scores go up, bank balances go down, and days pass. If you wanted to increase a number, you have to add a number to it and assign it back to itself:
score = 10
score = score + 5Because programmers do this thousands of times a day, Python has a shortcut called Augmented Assignment Operators. You can type += or -= to instantly update a variable’s value.
score = 10
# Add 5 to the score
score += 5
print(score)
# Output: 15
# Subtract 2 from the score
score -= 2
print(score)
# Output: 133.8 Type Casting: Changing Shapes
We learned that computers treat the integer 5 and the string "5" completely differently. If you try to add them together, the computer crashes with a TypeError.
Type Casting is the act of forcing data to change its type. Python gives us three built-in functions to do this: int(), str(), and float().
Casting Strings to Integers
When we use input(), the computer always hands us a String. If we want to do math with the player’s answer, we must wrap it in int().
# The user types 10. Python sees it as the word "10".
age_text = input("How old are you? ")
# We cast it into an integer
actual_age = int(age_text)
# Now we can safely do math!
future_age = actual_age + 5Casting Integers to Strings
If we want to glue an integer into a sentence using the + operator, we must do the reverse. We use str() to turn the number back into a word.
total_coins = 500
# We cannot do: "You have " + 500. It will crash!
# We must cast the integer to a string first:
print("You have " + str(total_coins) + " coins!")3.9 The Project: The Epic Loot Splitter
We are going to build a calculator that solves a very common problem: splitting things fairly.
Whether you are splitting gold coins among a party of adventurers, or splitting slices of pizza among your friends, the math is the same. We will use Floor Division to see how much everyone gets, and the Modulo Operator to see what is leftover.
Open a new file, save it as loot_splitter.py, and type the following code:
print("=============================")
print(" THE EPIC LOOT SPLITTER")
print("=============================")
# 1. Ask the user for numbers and cast them to integers
loot_text = input("\nHow many gold coins did you find? ")
total_coins = int(loot_text)
friends_text = input("How many friends are splitting the loot? ")
party_size = int(friends_text)
# 2. Do the Math!
# Use Floor Division (//) to give out whole coins fairly
coins_per_person = total_coins // party_size
# Use Modulo (%) to find the remainder
leftovers = total_coins % party_size
# 3. Print the results (Don't forget to cast the integers back to strings!)
print("\nCalculating shares...")
print("Each person receives " + str(coins_per_person) + " gold coins.")
print("There are " + str(leftovers) + " leftover coins for the leader!")Run your code and try typing in 100 coins and 3 friends. The computer will instantly tell you that everyone gets 33 coins, with exactly 1 coin left over!