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

Free lesson

2.2 (2 of 3): Changing one data type to another

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

40 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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.

Watch: text joins, numbers add

Press Play on the short film below. Watch the quote marks: each function gives back a new value of a new type.

Film: changing one data type to another

Changing one data type to another

Every scene, as text

  1. input() always gives text. The strings "5" + "5" join to make "55". Text joins. It does not add.
  2. To add, change the text into numbers first. int("5") gives 5, so int("5") + int("5") gives 10. This is type conversion.
  3. Four functions change the type. int("7") gives 7. float("2.5") gives 2.5. str(12) gives "12". bool(0) gives False.
  4. To join a number to text, change it with str() first. "Score: " + str(7) gives "Score: 7".
  5. int(4.9) gives 4, not 5. int() cuts off the decimal part. It does not round.
  6. bool() gives True or False. bool(0) and bool("") give False. bool(5) and bool("hello") give True.
  7. int() can only change text that is a whole number. int("hello") and int("2.5") stop the program with a ValueError. float("2.5") works.

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.

Make a free account to save your work and track your progress.

Four conversion functions

Python gives you four functions to change type. Each one takes a value and gives back a new value of that type, made from the one you gave it.

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.

Match the code to its result

Have a go

Loading…

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

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.

Make a free account to save your work and track your progress.

Not every conversion works

Warning

Many people think int() can turn any text into a number. 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

Three reasons to convert

There are three common reasons.

One: input comes as text, but you want to calculate.

Two: you want to join a number to a sentence, so the number must be text.

Three: a function needs one type and you have another.

Extra: Another name, and a function that rounds

Note

Some books and websites say casting. Casting means the same as type conversion.

int(4.9) gives 4, because it cuts off the decimal part. round(4.9) gives 5, because it rounds to the nearest whole number. round() is not a conversion. Use it when you want the nearest whole number.

Your turn: convert the values

Use int(), float(), str() and bool() to finish four functions. total_price gets a price and a quantity as text and gives back a float. next_age gets the age as text and gives back the age next year as an integer. score_label gives text like Score: 7. has_name gives True if the name is not empty. Press Run Tests.

Code: python
def total_price(price_text, quantity_text):
    # Both arrive as text, for example "2.50" and "3".
    # Give back the price times the quantity, as a float.
    return None


def next_age(age_text):
    # Give back the age next year, as a whole number. "15" gives 16.
    return None


def score_label(score):
    # score is a whole number. Give back text like: Score: 7
    return None


def has_name(name):
    # Give back True if name is not empty, and False if it is "".
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

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

Exit quiz

Have a go

Exit quiz

6 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

Remember

Important

int(), float(), str() and bool() change the type of a value. Text from a user must be changed before you calculate with it. int() cuts off decimals and does not round.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.