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:



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:

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"}

Get the code for the classic Retro Alien Blitz Game using Python Turtle Graphics when you join our mailing list