Python Type Annoatations

Most exam boards offering Computer Science GCSE and A Level courses allow students a choice of which programming language to use. This usually includes Python along with other options like Java, C# or Visual Basic.

In some ways Python is less strict than the others, and this can cause problems for students. For example in Python, there is no need to specify the type of variables, including function arguments. There is also no need to specify the return type from a function. However these details are expected by examiners. Compare the following code snippets:


def fib(n):
    a = 0
    b = 1

    for i in range(n):
        temp = a + b
        b = a
        a = temp
    return a


public static int Fibonacci(int n)
    int a = 0;
    int b = 1;

    for (int i = 0; i < n; i++)
        int temp = a + b;
        b = a;
        a = temp;
    return a;

You can see that the Python version has a lot less information about data types. One solution to giving the examiner what they want when writing program code solutions to questions in Python is to use comments to explicitly name the type of a variable. However, with Python 3’s type annotations there is a better way. Take a look a this code:

def fib(n: int) -> int:
    a: int = 0
    b: int = 1

    i: int
    for i in range(n):
        temp: int = a + b
        b = a
        a = temp
    return a

Can you see how the type hints are now built into the code like in other languages? There is one detail that you may have noticed – since you can’t use : on a loop variable, I’ve declared the type of i before use. These type annotations are pretty cool eh? Try using them in your own code and develop a habit which will keep you examiner happy!

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.