Getting Started with Python
Data types
Pick the right data type for a value.
Every value in Python has a data type, which decides what can be done with it. The function type() tells you the type: type(22) gives <class 'int'>.
Numbers:
- int: whole numbers, such as -7, 0, 22.
- float: numbers with a decimal point, such as 2.5 or 4.0.
- complex: numbers with a real and an imaginary part, such as 5 + 8j.
- bool: True or False. It is a kind of int (True behaves like 1, False like 0).
Sequences are ordered collections, whose items are numbered by index (starting from 0):
- A string: characters in quotes, 'India' or "India".
- A list: items in square brackets, which can be of different types and can be changed: ['onion', 'potato', 2.5].
- A tuple: items in round brackets, which cannot be changed once made: (7, 14, 'Mango').
A set is an unordered collection in curly brackets, with no duplicates: {4, 5, 4} is stored as {4, 5}. None is a special value meaning no value at all; its type is NoneType.
A dictionary holds key : value pairs in curly brackets: {'Subject':'Maths', 'Marks':92}. You look up a value by its key: if d is that dictionary, d['Marks'] gives 92.
Types are either mutable or immutable:
- Mutable types can be changed in place: lists, dictionaries and sets.
- Immutable types cannot: numbers, strings and tuples. If you 'change' an immutable value, Python actually makes a new object, and the variable now refers to it.
Choosing a type: use a list for a collection that will change, a tuple for fixed data, a set when items must be unique, and a dictionary to look things up by a key.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.