Python Built-In Functions

Python Built-In Functions

In this Blog, i will be covering few of Python Built-In Functions that will be useful for developers.

Python Built-in Functions

The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The python interpreter has several functions that are always present for use. These functions are known as Built-in Functions. There are several built-in functions in Python , Lets discuss few of them which is useful for developers in day to day development.

Python all() Function

The python all() function accepts an iterable object (such as list,dictionary etc.).

1. It returns True if all items in passed iterable are true, otherwise it returns False.

2. If the iterable object is empty, the all() function returns True.

Let's take an example of all() functions and see how it works

Example1

# all values true  
number = [1, 3, 4, 5]  
print(all(number))  - returns True

Example 2

# all values false  
number = [0, False]  
print(all(number))  - returns False

Example 3

# one false value  
number = [1, 3, 4, 0]  
print(all(number))  - returns False

Example 4

# one true value  
number = [0, False, 5]  
print(all(number))  - returns False

Example 5

# empty iterable  
number = []  
print(all(number))   - returns True

Python bool() Function

The python bool() method converts value to boolean (True or False) using the standard truth testing procedure.

1. It is not mandatory to pass value to bool().

2. If you do not pass the value, bool() returns False.

3. In general, bool() takes a single parameter value.

Let's take few example and try to understand how it works

Example 1

test = []  
print(bool(test))  - returns False

Example 2

test = [0]  
print(bool(test))  - returns True

Example 3

test = 0.0  
print(bool(test))  - returns False

Example 4

test = None  
print(bool(test)) – returns False

Example 5

test = True  
print(bool(test))  - returns True

Example 6

test = 'Easy string'  
print(test,'is',bool(test))  - returns True

Python callable() Function

A python callable() function in Python is something that can be called. This built-in function checks and returns True if the object passed appears to be callable, otherwise False.

Parameters

object - The object that you want to test and check, it is callable or not.

Return

Returns True if the object is callable, otherwise False.

Lets take an example and try to understand its working

Example 1

Check if a function is callable:
def x():  
 a = 5  

print(callable(x))   - returns True

Example 2

Check if a function is not callable (such as normal variable).
x = 5  
print(callable(x))  - returns False

Python exec() Function

The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a single expression.

Signature

exec(object, globals, locals)

Parameters

object - It should be either string or code object.

globals (optional) - It is used to specify global functions.C++ vs Java

locals (optional) - It is used to specify local functions.

Lets take few examples of working of exec function

Example 1

x = 5  
exec('print(x==5)')  - returns True
exec('print(x+4)')  - returns 9

Example 2 - This example shows exec() dynamic code execution

from math import *  
for l in range(1, 3):  
    func = input("Enter Code Snippet to execute:\n")  
    try:  
        exec(func)  
      except Exception as ex:  
        print(ex)  
        break  
print('Done')

Output

Enter Code Snippet to execute:
print(sqrt(16))
4.0
Enter Code Snippet to execute:
print(min(2,1))
1
Done

Python eval() Function

The python eval() function parses the expression passed to it and runs python expression(code) within the program.

Signature

eval(expression, globals, locals)

Parameters

expression - The string is parsed and evaluated as a Python expression. globals (optional) - A dictionary that specifies the available global methods and variables. locals (optional) - It is an another dictionary which is commonly used for mapping type in Python.

Return

It returns the result evaluated from the expression.

Lets take an example of eval function

x = 5  
print(eval('x + 1'))   - returns 6

Note :-

In this example, we take an integer variable named x, and eval() function parses the expression and returns result evaluated from the expression.

Python frozenset() Function

The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.

Signature

frozenset(iterable)

Parameters

iterable: An iterable object such as list, tuple etc.

Return

It returns an immutable frozenset object initialized with elements from the given iterable.

Lets take an example and try to understand how it works

# tuple of letters  
letters = ('m', 'r', 'o', 't', 's')  

fSet = frozenset(letters)  
print('Frozen set is:', fSet)  
print('Empty frozen set is:', frozenset())

Output:

Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()

Explanation:

In the above example, we take a variable that consists tuple of letters and returns an immutable frozenset object.

Python hasattr() Function

The python hasattr() function returns true if an object has given named attribute. Otherwise, it returns false.

Signature

hasattr(object, attribute)

Parameters

object: It is an object whose named attribute is to be checked. attribute: It is the name of the attribute that you want to search.

Return

It returns true if an object has given named attribute. Otherwise, it returns false.

Lets take an example and try to understand its working

class Employee:  
    age = 38
    name = 'Dhiraj Kumar'  

employee = Employee()  

print('Employee has age?:', hasattr(employee, 'age'))  
print('Employee has salary?:', hasattr(employee, 'salary'))

Output:

Employee has age?: True
Employee has salary?: False

Explanation:

In this example, we have created a class named as Employee, then we create the object of the Employee class, i.e., employee. The hasattr(employee, 'age') returns the true value as the employee object contains the age named attribute, while hasattr(employee, 'salary')) returns false value as the employee object does not contain the salary named attribute.

That's all for this Blog developers and with that, it's a wrap! I hope you found the article useful.

I create content about Programming, and Productivity, If this is something that interests you, please share the article with your friends and connections.

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

I would strongly recommend you to Check out my YouTube Channel youtube.com/c/codeasitis where i post programming video and don't forget to subscribe to my Channel. I would love to connect with you at Twitter ( twitter.com/codeasitis1 ) | Instagram ( instagram.com/codeasitis )

See you in my next Blog article, Take care!!