Types

Up until now, all the data that we have been working with in Python has been numerical: we have been dealing with numbers, so what about letters, or other more exotic things like complex numbers?

We refer to the variety of different basic quantities as types.

Numeric types

Python provides an built-in function type for determining the type of some data. For example

type(2)
int

The number \(2\) is an integer - in Python we represent this as 2 without a decimal point. We say that these have the type of int.

What about if we have a decimal point?

type(2.5)
float

Numbers with a decimal point are floats and have the type of float.

There is also a third basic numeric type for complex numbers

type(3 + 2j)
complex

which is, unimaginatively, called complex. The j in the code above represents the imaginary unit \(i\) - we’d write the above as \(3 + 2i\) on pen and paper. We won’t use complex numbers in this course, but it’s worth noting that Python is perfectly capable of using them.

We can combine numeric types and let Python do the conversion automatically - to see this add a float to an int.

a_float = 2.2
an_integer = 5

sum_of_them = an_integer + a_float
print(sum_of_them)

type(sum_of_them)
7.2
float

We see that the result is a float. This makes sense if you think about it this way - python will try and stay as precise as possible. If it converted 2.2 to an integer we’d lose the .2 and the number would become 2 - this wouldn’t be very precise! Instead, it converts 5 to 5. without any loss of precision.

Note

In python (and some other languages) we call the conversion between types type casting. Here the int has been cast to a float.

Strings

You might be wondering how we use letters or words in python - can we store these in variables?

Words, or more generally, collections of individual letters/characters are referred to as strings in Python (and in many other programming languages).

String syntax in Python is relatively simple, we just need to enclose whichever letters we want in quotes

saying_hello = 'Hello world!'
print(saying_hello)
hello world

Strings are clearly very different from the numeric data discussed above; this is reflected by the type function which tells us they have a type of str

type('a really nice string')
str

In the above we’ve used single quotes to give a string, but we can also use double quotes

saying_hello = "Hello world!"
print(saying_hello)
hello world

What we cannot do is open a string with one type of quotation mark and end it with another - python gives us an error in this case.

a_syntactically_invalid_string = 'This string is not valid syntax!"
print(a_syntactically_invalid_string)
  Cell In[1], line 1
    a_syntactically_invalid_string = 'This string is not valid syntax!"
                                     ^
SyntaxError: unterminated string literal (detected at line 1)
WarningError

There are many different kinds of errors in Python. The example above is a SyntaxError, meaning the code we’re trying to run isn’t valid Python. In other words, the code does not make sense to the Python interpreter, like trying to speak to someone in a language that they do not understand.

Notice that the error message tells us which line is causing the problem. Here we are informed that line 1 is causing the SyntaxError, and we’re told the syntax problem is an unterminated string literal - we haven’t closed the string with the correct quotation mark.

You should always read and try to understand error messages - python is trying to tell you what is wrong!

It’s worth emphasising that you can use double quotation marks within a string that starts and ends with a single quotation mark (and vice versa)

valid = 'This is "valid"...'
also_valid = "and so is 'this'"
print(valid, also_valid)
This is "valid"... and so is 'this'.

What if we want to include quotation marks in a string that starts and ends with those same quotation marks? This can be accomplished with a backslack \ which is used to “escape” the desired character:

an_invalid_string = 'This string will raise a 'SyntaxError'!'
print(an_invalid_string)
  Cell In[6], line 1
    another_silly_string = 'This string will raise a 'SyntaxError'!'
                                                      ^
SyntaxError: invalid syntax
another_valid_string = 'This string will raise a \'SyntaxError\'!'
print(another_valid_string)
This string will not raise a 'SyntaxError'!

Exercise

Using your knowledge of python strings, try out the following operations in Python:

  • Adding two strings together using the + operator.
  • Multiplying a string by an integer (a number without a decimal point) using the * operator.
  • Multiplying a string by a float (a number with a decimal point) using the * operator.
  • Multiplying two strings together using the * operator.
  • Subtracting one string from another using the - operator.
  • Adding a string to a number using the + operator.
Note

Some of these operations will cause errors - this is expected and entirely intentional. Read the errors and try to understand why your code does not run: does the operation you are asking Python to do make sense?

String operations

From the exercise above you’ll have seen that, when applied to str, some operations result in an error.

As an example, look what happens when we add a str to an int.

an_integer = 7
a_string = 'Strings are not numbers!'

an_integer + a_string
TypeError                                 Traceback (most recent call last)
Cell In[9], line 4
      1 an_integer = 7
      2 a_string = 'Strings are not numbers!'
----> 4 an_integer + a_string

TypeError: unsupported operand type(s) for +: 'int' and 'str'
TipError

This code yields a TypeError, which means that we are trying to operate on different data types in a way that doesn’t make any sense. This happens because Python doesn’t have a defined way of adding a str to an int.

Of course, there are situations in which we might want to add an integer to a string. Consider the following:

'This is an integer: ' + 10

This code will raise an error much like the previous example, but as human beings we can see how it might make some sense. To add the int to the str, we have to cast it to a str

an_integer = 10
a_string = 'This is an integer: '

a_string + str(an_integer)
'This is an integer: 10'

Here we have used the in-built str function to cast the int to a str.

This method becomes tedious when you have lots of things to print, and in fact is considered bad form. Instead, python provides a better way to print a mixture of types using a formatted string or f-string - we’ll cover these at the end of this session.

Booleans

The final basic data type we have yet to cover is the Boolean. This type of data represents two possible logical values: True or False

type(True)
bool
type(False)
bool

We have yet to see how this type of data can be useful, but we will use them a lot in later Sessions. However, True and False are the first reserved keywords that we have come across - we cannot create variables with these names!

True = 5
Cell In[16], line 1
    True = 5
    ^
SyntaxError: cannot assign to True
False = 'here comes the error!'
Cell In[17], line 1
    False = 'here comes the error!'
    ^
SyntaxError: cannot assign to False