This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Basic built-in data types

Firstly, open a terminal and launch the interactive Python interpreter on your terminal (type python3 or whichever alias you are using). Do not forget - we are working with Python version 3, so make sure it is the correct version.

This will give you an interactive prompt, which you can now use to write Python code interactively. When you want to stop writing Python code, you can type exit() into the prompt.

Please follow along and try out the code while studying these materials. Trying things out yourself is the best way to learn!

Now, type these into the Python prompt:

>>> 1+1
2
>>> 'I am a genius'
'I am a genius'

Yes, you are indeed a genius! 😃

This was just actually get you warmed up. We can now start the lesson for real.

We will first discuss the basic elements or ‘atoms’ in Python.

Python is made up of different basic types of values. For example,

  • Numbers
  • Booleans
  • Strings

You can use type() to check the type of a value.

A literal is a succint and ‘direct’ way to write a value, e.g. 558, 2.6, "hello", True.

Numbers

Numbers can be

  • int (integers)
  • float (floating points),
  • complex (complex numbers)

Try typing these into an interactive Python interpreter and see what you get:

>>> type(42)
>>> type(3.412)
>>> type(1+2j)

You can also express floating-point values like \(3.2 \times 10^{-12}\) as 3.2e-12

>>> 3.2e-12
>>> type(3.2e-12)

Number system

Numbers can also be written in a non-decimal base form.

  • Binary (base 2): prefix with 0b or 0B
  • Octal (base 8): prefix with 0o or 0O
  • Hexadecimal (base 16): prefix with 0x or 0X
>>> print(26)
>>> print(0b11010)
>>> print(0o32)
>>> print(0x1A)

Booleans

Booleans (bool) can be either True or False.

>>> type(True)
>>> type(False)

Strings

Strings (str) are a sequence of characters.

In Python, you surround string literals with either ‘single quotes’, “double quotes”, or ‘'’triple quotes’’’.

Try these:

>>> 'Is Python that easy?'
>>> "Is Python that easy?"
>>> '''Is Python that easy?'''

All three are equivalent. So ‘my string’ is identical to “my string”.

NOTE: Many programming languages (C, C++, Java) have a special character (char) type, usually enclosed with single quotes (e.g. 'a', '6', '%'). In these languages, char are different from strings, which are usually enclosed with double quotes (e.g. “a string”). Therefore, 'a' is different from "a" in these languages.

In Python, there is no char data type. Instead, a character is a string of length 1.

You can also write multiline strings with ‘'’triple quotes’’’.

>>> ''' This is a string
...     spanning multiple
...     lines
... '''

If you see the character \n in your output, it is a character representing a newline.