LearnWave
Learn it. Master it.

Brief Overview of Python

Data types

Pick the right data type for a value.

Every value in Python has a data type, which decides what it can hold and which operations work on it. The built-in function type() tells you the type: type(10) gives <class 'int'>; type(-1921.9) gives <class 'float'>.

Numbers:

  • int: whole numbers: -12, -3, 0, 123.
  • float: numbers with a decimal point: -2.04, 4.0, 14.23.
  • complex: numbers with a real and an imaginary part. The book writes 3 + 4i, but in Python code the imaginary part uses j: 3 + 4j.
  • bool (Boolean) is a subtype of int, with two values, True (non-zero) and False (zero).

Simple types hold one value. To hold many values (months of the year, students in a class, a phone book), Python has sequences and mappings.

Sequences are ordered collections whose items are indexed by integers:

  • String: a group of characters (letters, digits, symbols, spaces) inside single or double quotes: 'Hello' or "Hello". You cannot do arithmetic on a string, even one holding digits such as "452".
  • List: items separated by commas inside square brackets, which may be of different types: [5, 3.4, "New Delhi", "20C", 45]. Lists can be changed.
  • Tuple: items inside round brackets: (10, 20, "Apple", 3.4, 'a'). Once created, a tuple cannot be changed.

Mapping: the standard mapping type is the dictionary: key-value pairs inside curly brackets, each key separated from its value by a colon. Values are found by key, which is fast. For example, dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}, and dict1['Price(kg)'] gives 120.

Example (new): a train's details could be stored as number = 12951 (int), fare = 1450.50 (float), stations = ['Mumbai', 'Vadodara', 'Kota', 'Delhi'] (a list, since stops may be added), and coach = {'type':'3A', 'berths':64} (a dictionary).

Lists change, tuples don't, dictionaries look up by 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.