payment by upi: sinhamit@icici or payment by bank account name: amit kumar sinha, account number: 2646728782 IFSC code: KKBK0005660 SWIFT: KKBKINBB

Please support if you like my work by payment through upi: sinhamit@icici or payment by bank

account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB


builtins module   in Category: Python   by amit

🕙 Posted on 2023-06-26 at 12:19:38     Read in Hindi ...


Built-in Functions

    Unlike PHP and JavaScript, there are many modules (libraries) in Python, and even you can contribute or create your own custom modules. One of those modules is builtins which defines all built-in functions in the python programming language. To exploit all features of a module, you have to import it in your file with .py extension, and run/execute the same in the Command Line Console or VSCode Editor Terminal.

import builtins
print( dir( builtins ) ) # Outputs following built-in functions as items of a list

PS C:\xampp\htdocs> cd .\python2023\
PS C:\xampp\htdocs\python2023> py new.py
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

import builtins
print( help( builtins ) )
# You can run/execute this statement after saving it in your file, however, the help( builtins ) outputs very large help data, and therefore, you should extract separate help for each of these built-in functions mentioned above.

    Each of these built-in functions have their own methods, some of those methods have same name for different built-in functions. You can see names of methods of respective built-in function, by executing the statement, for example, print( dir( list ) ) or print( dir( str ) ). You can also know more about these built-in function by executing the statement, for example, print( help( list ) ) or print( help( str ) ). You have seen help document­ation about list in previous page.

print( dir( str ) ) # This statement will show all methods of str() built-in function. (You should delete all old codes in new.py file before executing this statement!)

PS C:\xampp\htdocs> cd .\python2023\
PS C:\xampp\htdocs\python2023> py new.py
['__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', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

print( help( str.capitalize ) ) # You can see all available methods of str() built-in function as shown above, and you can get help document­ation of specific method by executing this statement.

PS C:\xampp\htdocs\python2023> py new.py
Help on method_descriptor:

capitalize(self, /)
    Return a capitalized version of the string.

    More specifically, make the first character have upper case and the rest lower
    case.

None

print( help( ''.upper ) ) # You can either use keyword (e.g., str) for which you want to get document­ation, or use literal values of respective data-type. upper() method makes all letters CAPITAL (uppercase) in a string

C:\xampp\htdocs\python2023> py new.py
Help on built-in function upper:

upper() method of builtins.str instance
    Return a copy of the string converted to uppercase.

None

    You can get individual document­ation help for each method of a specific built-in function, as you can see in above description that capitalize() and upper() are methods (or properties), which are applied specifically to string data-type.

print( help( ''.count ) ) # count() method is different from len() built-in function. If you have already learned PHP, then you can distinguish these methods in Python with same name in PHP functions.

C:\xampp\htdocs\python2023> py new.py
Help on built-in function count:

count(...) method of builtins.str instance
    S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end]. Optional arguments start and end are
    interpreted as in slice notation.

None

    print( 'HelloHello'.count('l') ) # outputs 4 (integer value of occurrence of l character in string 'HelloHello'). Many methods takes one or more arguments within parentheses.

    print( len( 'HelloHello' ) ) # outputs 10 (integer value of total number characters in string 'HelloHello'). A built-in function always takes at least one argument inside the parentheses.

    bool(), str(), int(), float(), complex(), list(), range(), tuple(), dict(), set(), frozenset(), bytes(), bytearray(), and memoryview() built-in functions are used to create or type-cast (convert) the value assigned to a variable name in respective data-type. You have already seen in previous page some of above built-in functions, such as print() (used to display data on the CLI or Console), exit() and quit() (used to quit the Python CLI), dir() (used to show names of all methods and functions for a class/function, etc. in a list), range() and list() (used to create an array), type() (used to output the data-type of variable or literal).

    However, there are some reserved keywords, for example, and, as, assert, break, case, class, continue, del, def, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, match, None, nonlocal, not, or, pass, raise, return, while, True, try, etc. and different kind of operators which are frequently used in python programming language. You will learn about them in next lessons.


Leave a Comment: