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
Real or Float: a number that has a decimal point like
String: text which can contain characters, punctuation or numbers like
"45 degrees"or even
It’s important to note that python thinks the string
"45" is different from the int
For example, when you add integers together, add the number values.
"45" + "45"is
However, when you add strings together, you join them one after the other:
45 + 45is
Joining strings together is called concatenation.
Sometimes it’s useful to convert from one type to another.
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.1)both return the integer value
Converting to strings:
str(1 + 1)both return the string value
Converting to real numbers:
float("2")both return the real number
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
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.