Python Useful Built-in Functions With Examples | How to create a new function

Types of function in Python

There are 3 types of functions in Python:

  1. Built-in functions
  2. User-Defined Functions (UDFs)
  3. Anonymous functions

1. Built-in functions

Built-in functions can be defined as the functions whose functionality is pre-defined in Python. All build-in functions and exceptions can be found in ‘builtins‘ module.
Question: What is a built-in function in Python? Tell me the name of 10 build-in functions.

List of all build-in functions (Python 3.7)

‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’, ‘bool’, ‘breakpoint’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘debugfile’, ‘delattr’, ‘dict’, ‘dir’, ‘display’, ‘divmod’, ‘enumerate’, ‘eval’, ‘exec’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘get_ipython’, ‘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’, ‘range’, ‘repr’, ‘reversed’, ’round’, ‘runfile’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’

Question: How do I print a built-in function in Python?
Answer: By importing builtins module print all build-in items by using the below line of code
print(dir(builtins))

Below are the details of first 10 functions (alphabetically)

  1. abs() : Use to get the absolute value of a number.
  2. all() : this return True if all elements of the iterable are true.
  3. any() : this return True if any elements of the iterable are true.
  4. ascii() : this returns a string containing a printable representation of an object
  5. bin() : this function is used to convert an integer number to a binary string.
  6. bool() : this function give a Boolean value (True/False) based on standard truth testing procedure.
  7. breakpoint() : the function is used to start the python debugger.
  8. bytearray() : this function returns the array of bytes.
  9. bytes() : this function is used to get the byte object, the byte object is an immutable sequence of integers.
  10. callable() : this function return True if the object argument is callable else it will return False.

For details of binary types please click on this http://mycloudplace.com/python-data-types-with-examples/#BinaryType

EXAMPLE: Using above build-in functions in our program.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 22:00:35 2021
website : http://mycloudplace.com
@author: mycloudplace
"""
def main():
    #Example: Using the following build-in function in our program
    str_seprator = "---------------------------------------------------------"
    print("1. 'abs' example")
    abs_int = -4
    abs_float = -123.5432
    abs_comprex = (4 + 5j)
    print("Absolute value  of " + str(abs_int)  +  " :", abs(abs_int))
    print("Absolute value  of " + str(abs_float)  +  " :", abs(abs_float))
    print("Absolute value  of " + str(abs_comprex)  +  " :", abs(abs_comprex))
    
    print(str_seprator)
    print("2. 'all' example")
    var_dict = {2: 'two', 3: 'three'} 
    print("is all elements of the 'var_dict' are true :", all(var_dict))
    var_dict2 = {0: 'zero', 3: 'three'}
    print("is all elements of the 'var_dict2' are true :", all(var_dict2))
    
    print(str_seprator)
    print("3. 'any' example")
    print("is any elements of the 'var_dict' are true :", any(var_dict))
    print("is any elements of the 'var_dict2' are true :", any(var_dict2))
    var_dict3 = {0: 'hello', 0: 'world'}
    print("is any elements of the 'var_dict3' are true :", any(var_dict3))
    
    print(str_seprator)
    print("4. 'ascii' example") 
    var_non_ascii = "♥prëm"
    print(ascii(var_non_ascii))
        
    print(str_seprator)
    print("5. 'bin' example") 
    int_sample = 12
    print("Binary Code of", int_sample, "is :", str(bin(int_sample)))
    
    print(str_seprator)
    print("6. 'bool' example") 
    print("bool of", int_sample, "is :", str(bool(int_sample)))
    
    print(str_seprator)
    print("7. 'breakpoint' example") 
    breakpoint() # it will start the python debugger
    
    print(str_seprator)
    print("8. 'bytearray' example")  
    str_hello = "This is sample sentence."
    byte_array = bytearray(str_hello, 'utf-8')
    print("Type of byte_array is " + str(type(byte_array)))
    print(byte_array)

    print(str_seprator)
    print("9. 'bytes' example") 
    byte_str2 = bytes(str_hello, 'utf8')
    print("Type of byte_str2 is " + str(type(byte_str2)))
    print(byte_str2)
    
    print(str_seprator)
    print("10. 'callable' example") 
    def xyz():
        print("hello xyz")
    print("is variable 'int_sample' is callable : ", callable(int_sample)) 
    print("is function 'xyz' is callable : ", callable(xyz))
    
if __name__ == "__main__":
    main() 

OUTPUT:

1. 'abs' example
Absolute value  of -4 : 4
Absolute value  of -123.5432 : 123.5432
Absolute value  of (4+5j) : 6.4031242374328485
---------------------------------------------------------
2. 'all' example
is all elements of the 'var_dict' are true : True
is all elements of the 'var_dict2' are true : False
---------------------------------------------------------
3. 'any' example
is any elements of the 'var_dict' are true : True
is any elements of the 'var_dict2' are true : True
is any elements of the 'var_dict3' are true : False
---------------------------------------------------------
4. 'ascii' example
'\u2665pr\xebm'
---------------------------------------------------------
5. 'bin' example
Binary Code of 12 is : 0b1100
---------------------------------------------------------
6. 'bool' example
bool of 12 is : True
---------------------------------------------------------
7. 'breakpoint' example
> /home/hadoop/functions.py(53)main()
     51     breakpoint() # it will start the python debugger
     52 
---> 53     print(str_seprator)
     54     print("8. 'bytearray' example")
     55     str_hello = "This is sample sentence."
ipdb> --KeyboardInterrupt--
KeyboardInterrupt: Interrupted by user
---------------------------------------------------------
8. 'bytearray' example
Type of byte_array is <class 'bytearray'>
bytearray(b'This is sample sentence.')
---------------------------------------------------------
9. 'bytes' example
Type of byte_str2 is <class 'bytes'>
b'This is sample sentence.'
---------------------------------------------------------
10. 'callable' example
is variable 'int_sample' is callable :  False
is function 'xyz' is callable :  True

Go To Top (Types of function in Python)


2. Python User-defined Functions (UDFs)

The user-defined functions can be defined as the function which is defined by user to perform a specific task like function to add two number, function to perform specific computation, etc.
A user-defined function begins with def keyword followed by function name. The user-defined functions may take the input arguments.

EXAMPLE: Find the factorial of a number using Recursive function.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed June 02 22:00:35 2021
website : http://mycloudplace.com
@author: mycloudplace
"""
def factorial(num):
    if (num == 1 or num == 0):
        return 1
    else:
        return (num * factorial(num - 1))
def main():
    print("Factorial example using recursive function :")
    input_number = 10
    fact_number = factorial(input_number)
    print("Factorial of", input_number , "is :",fact_number)
    
if __name__ == "__main__":
    main() 

OUTPUT:

Factorial example using recursive function :
Factorial of 10 is : 3628800

Go To Top (Types of function in Python)

3. Anonymous functions

  • Question: What is lambda function in python explain with an example?
  • Question: How do you write a lambda function in Python?
  • Question: How do you declare an anonymous function in Python?
  • Question: Are lambda functions faster than standard user-defined functions in python?
  • Question: Can python lambda return multiple variables?

For details please click on Anonymous functions..

Our previous articles

Next Article

http://mycloudplace.com/python-lambda-function-with-examples-how-to-create-a-new-anonymous-function

Python official link

https://docs.python.org/3.8/library/

13 thoughts on “Python Useful Built-in Functions With Examples | How to create a new function”

  1. Pingback: Modules in python tactics that can boost your python programming skills - Mycloudplace

  2. Pingback: A to Z of Python exception handling | Python try catch with example - Mycloudplace

  3. Pingback: Datapane python reporting library for interactive reports and beautiful charts - Mycloudplace

  4. You need to be a part of a contest for one of the highest quality sites on the net. I am going to recommend this website!

  5. דירות דיסקרטיות בתל אביב

    Everything is very open with a really clear clarification of the issues. It was truly informative. Your site is very helpful. Many thanks for sharing!

  6. שירותים בתל אביב

    Greetings! Very helpful advice within this post! It is the little changes that will make the most significant changes. Thanks for sharing!

  7. Pingback: Python obfuscation | Great technique to hide python code | Perfect use of pyarmor - Mycloudplace

Leave a Comment

Your email address will not be published. Required fields are marked *