python data types, interactive help, and built-in functions

In our last post, we looked at the print function, string concatenation, and escape character in python3. In this part of the tutorial, will look at a few of the basics of python3 – data types, python interactive help, and built-in functions. Let’s get started.

In one of our article titled, Introduction to programming using python3, we got a brief introduction of what the python programming language is, where it can be used, installing python on your machine and writing your first python program and running it in your machine. We will look at some other basic characteristics for python in this section:

Data Types

There are different types of python data types. Some built-in data types are:

  • Numeric: Python numeric data type is used to hold numeric values like;
    • int: Used to store signed integer values.
    • float: Used to store floating point values.
    • complex: Used to store complex number values.
  • String (str): Used to store a collection of characters. String literals are surrounded by either single quotation or double quotation marks.
  • List (list): A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Lists are very powerful and flexible.
  • Tuple (tuple): A tuple is a data structure in Python that is similar to lists but are immutable.
  • Dictionary (dict): A dictionary in python is a collection of key-value pairs. Each key-value pair maps the key to its associated value.

We will look at each of these data types in detail in another article. 

Unline C or C++, the python programming language does not have any type declarations. For eg: >>> name = “student” >>> roll_no = 1 >>> grade = 3.87 >>> type(name) <class ‘str’> >>> type(roll_no) <class ‘int’> >>> type(grade) <class ‘float’>


Python interactive help

There might be times when you might not be able to search for classes, modules, function on the internet. In such case you can use the Python’s interactive help feature. In particular, we will look at dir() and help() functions. Let’s look back at our data types. As you can see, the variables (name, roll_no, and grade) are all objects of respective classes (str, int and float). It is possible to view the various methods available to the object using the dir() function. Eg: >>> dir(name)

[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]

To view the functionality of a specific method, you can use the help command. For eg: help(name.replace) will display:

Help on built-in function replace:

replace(…) method of builtins.str instance
S.replace(old, new[, count]) -> str

Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is

given, only the first count occurrences are replaced.

The lines show how to use the function. The name of the function is ‘replace’. To use it, call S.replace() where S is a variable of type String. The function accepts three parameters. ‘old’, ‘new’, and, ‘count’. The parameter count is inside square bracket which means it is optional. The description below that is the detailed description of the help function. To quit the help view, you can press ‘q‘ anytime. For a custom function, we will need to provide the description ourselves. We will learn more about this when we discuss functions.

Built-in functions 

The dir() function can also be called without passing any parameter. For eg: the command dir()in a new python interpreter gives the following output on python3: >>> dir()

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]

You can see the module __builtins__ in the list. This module contains a collection of common objects which are always available to you. To see the list of built-in objects, view the directory for the built-ins module. To do this, we can just call the dir() function and pass the __builtins__ name. Eg:

>>> dir(__builtins__)
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’, ‘BufferError’, ‘BytesWarning’, ‘DeprecationWarning’, ‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’, ‘FloatingPointError’, ‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’, ‘IndentationError’, ‘IndexError’, ‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’, ‘NameError’, ‘None’, ‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’, ‘PendingDeprecationWarning’, ‘ReferenceError’, ‘RuntimeError’, ‘RuntimeWarning’, ‘StandardError’, ‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’, ‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’, ‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’, ‘ValueError’, ‘Warning’, ‘ZeroDivisionError’, ‘_’, ‘__debug__’, ‘__doc__’, ‘__import__’, ‘__name__’, ‘__package__’, ‘abs’, ‘all’, ‘any’, ‘apply’, ‘basestring’, ‘bin’, ‘bool’, ‘buffer’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘cmp’, ‘coerce’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘execfile’, ‘exit’, ‘file’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘intern’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘long’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’, ‘raw_input’, ‘reduce’, ‘reload’, ‘repr’, ‘reversed’, ’round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘unichr’, ‘unicode’, ‘vars’, ‘xrange’, ‘zip’]

This list contains many functions and types ready to use. To learn about one of these objects, you call the help function with the name of the object. For eg: help(pow) will display:

Help on built-in function pow in module __builtin__:

pow(x, y[, z]) -> number

With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

You can explore all the builtin objects in a similar way. You can also see the detailed descriptions of the datatypes mentioned earlier in a similar way.