The Theory:

Convert and use different types of data
Python Data types: Convert and use different types of data

We’ve already learnt how you can use variables to store data so that your code can process and display it, but so far we’ve only looked at text data.

The next step is to look at how to deal with numbers as well as text.

Before, we said that variables are like boxes used to store stuff. We said that variables have a name (like the box’s label) and a value (like what’s inside the box).

Variables also have a type which is like the shape of the box. There are three simple data types you should be aware of:

Integer or int: a whole number like 1, 2 or 3 but not 1.2 or 3.6

Real or Float: a number that has a decimal point like 1.123 or 3.14

String: text which can contain characters, punctuation or numbers like "hello" or "45 degrees" or even "45" but not 45

It’s important to note that python thinks the string "45" is different from the int 45

For example, when you add integers together, you add the number values.

45 + 45 is 90

However, when you add strings together, you join them one after the other:

"45" + "45" is "4545"

Joining strings together is called concatenation.

Sometimes it’s useful to convert from one type to another.

For example, input("How old are you") will ask the user a question for which you’d expect them to type a number (e.g. 15). However, the value that you get back from input is a string (e.g. "15"). If you want to do any calculations using that value, you’ll need to convert it to an integer first.

Converting to integers: int("2") and int(2.1) both return the integer value 2

Converting to strings: str(2) and str(1 + 1) both return the string value "2"  

Converting to real numbers: float(2) or float("2") both return the real number 2.0

Converting from one data type to another is called casting.

You can use any combination of variables, constants and values inside the brackets of these functions.

Key point:  use int(...)str(...) and float(...) functions to cast data to integers (whole numbers), strings (text) and reals (floating point decimal numbers).

On the next page you’ll get some code examples that you can try out for yourself.

Page 1: Intro

Page 2: The theory: learn what you need to know as fast as possible.

Page 3: Try it: try out and adapt some working python code snippets.

Page 4: Debug it: Learn how to find and fix common mistakes.

Page 5: Extend it: Choose a project idea to use your newfound python skills.