Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Changing one data type to another

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

40 minutes

Why 5 + 5 can be 55

A user types 5 and 5 into your calculator. Your program shows 55. It should show 10.

The reason is the data type. A data type is the kind of value. What a user types with input() is always text. Text joins together. It does not add. To add, you must change the text into numbers.

Key words

WordWhat it meansExample
Type conversionChanging a value from one data type to another.text "5" to number 5
Data typeThe kind of value.integer, string
IntegerA whole number.5
FloatA number with a decimal point.2.5
StringText inside quote marks."5"
BooleanTrue or False.True
FunctionA named piece of code that does one job.int()
ConcatenationJoining strings together with +."5" + "5" is "55"

The cells students fill in are left blank in this preview.

Try it: text or numbers?

Code: python
print("5" + "5")
print(5 + 5)
print(int("5") + int("5"))

# The first joins text. The second adds numbers.
# The third changes text to numbers first.

Four conversion functions

Python gives you four functions to change type. Each one takes a value and gives back the same value in a new type.

int() makes a whole number. float() makes a number with a decimal point. str() makes text. bool() makes True or False.

Worked example: what each one gives

CodeResultType of result
int("7")7Integer
int(4.9)4 (it cuts off the decimal part, it does not round)Integer
float(3)3.0Float
float("2.5")2.5Float
str(12)"12"String
bool(0)FalseBoolean
bool(5)True (any number except 0 is True)Boolean
bool("hello")TrueBoolean
bool("")False (empty text)Boolean

The cells students fill in are left blank in this preview.

Try it: use all four

Code: python
age_text = "15"
age = int(age_text)
print(age + 1)

price = float("2.50")
print(price * 3)

score = 7
print("Score: " + str(score))

print(bool(0))
print(bool(5))

# Try int("hello") and see the error.

Not every conversion works

data-callouts.warning.label

int("hello") stops the program with a ValueError. Python cannot turn the word hello into a number. int("2.5") also fails, because 2.5 has a decimal point. Data from a user can be wrong, so check it first.

Which conversion fits?

Have a go

Which conversion fits?

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

The lesson goes on

6 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.