Advertisement
Oct 10, 2023 7 mins

Understanding Python Built-in Functions Part 1

Python Built-in Functions Part 1 Python Built-in Functions Part 1

Python built-in functions are sort of tools for making computer programs better. It has many buit-in functions. Each function does some thing special. We're going to look at some of those function, beginning from A to E. I'll show you what they do with examples.

Imagine you’re a chef in a kitchen. Python’s functions are your ingredients. You’ll discover ways to blend them to prepare dinner something specail.

We’re going to make it fun and smooth to understand. You’ll see how each function allows in making your computer do cool tricks. Let’s dive in and play with them, discovering how they help us resolve puzzles in programming.

This is part 1 of the Python built-in function tutorial series and will cover the following built-in functions. Checkout the these links for other python built-in function.

abs function

The abs() function finds the absolute value of a given number. Whether the input is a positive or negative integer, or even a floating-point number, the abs() function returns the non-negative, or absolute, value.

For example, when calculating differences between values or distances, the abs() function ensures that the result is consistently positive.

abs_value = abs(-5)
print(abs_value)  # Output: 5

all() function

The all() function returns True if all elements in an iterable are evaluated as True, and False otherwise. Essentially, the all() function checks whether every element in the given iterable meets a specified condition.

For instance, when dealing with a list of boolean values or conditions, the all() function quickly assess whether every element satisfies the required criteria. .

all_true = all([True, True, True])
print(all_true)  # Output: True

any() function

The any() function returns True if at least one element in the iterable evaluates as True, and False if all elements are evaluated as False. For example, when dealing with a list of boolean values or conditions, the any()function efficiently assesses whether there is at least one True value.

any_true = any([False, True, False])
print(any_true)  # Output: True

bin() function

The bin() function used for converting integer values into their binary representation. When applied to an integer, the bin() function returns a string prefixed with ‘0b’, indicating that the subsequent characters represent the binary form of the given number.

This function is particularly useful in situations where binary representation is needed, such as in bitwise operations or when dealing with low-level data manipulation.

binary_str = bin(10)
print(binary_str)  # Output: '0b1010'

bool() function

The bool() function converts a value to its boolean representation. When applied, the bool() function evaluates the truthiness of the given value, returning either True or False.

For instance, when dealing with conditional statements or logical operations, the bool() function can help clarify the boolean value of a particular condition.

bool_value = bool(1)
print(bool_value)  # Output: True

ascii() function

ascii() function is used to create a string representation of an object. When applied to an object, the ascii() function returns a string containing a printable version of the object.

This function is particularly useful when you want to obtain a string representation of an object that includes escape sequences for non-printable or special characters.

ascii_str = ascii("hello, world!")
print(ascii_str)  # Output: 'hello, world!'

bytearray() function

The bytearray() function takes various types of input, such as integers, strings, or other iterable objects, and convert them into a bytearray object. The resulting bytearray can be modified, unlike immutable bytes objects.

This function is useful in situations where a mutable representation of binary data is required, allowing for in-place modifications.

byte_array = bytearray([65, 66, 67])
print(byte_array)  # Output: bytearray(b'ABC')

bytes() function

The bytes() function creates an immutable sequence of bytes. It takes an iterable of integers as its argument, converting each integer to a byte and then constructing a bytes object from those bytes.

This function is commonly used to represent binary data in a way that cannot be modified after creation. It is particularly useful in scenarios where a fixed and unalterable sequence of bytes is required, such as when dealing with binary file formats or network protocols.

bytes_obj = bytes([65, 66, 67])
print(bytes_obj)  # Output: b'ABC'

callable() function

The callable() function allows you to check whether an object is callable, i.e., whether it can be called as a function. When applied to an object, callable() returns True if the object appears callable (can be invoked with parentheses), and False otherwise.

This function is useful for dynamically determining if a given object, such as a function or a class instance, can be invoked like a function. It helps in making runtime decisions in your code, ensuring that you are working with callable entities before attempting to call them.

is_callable = callable(print)
print(is_callable)  # Output: True

chr() function

The chr() function takes an integer representing a Unicode code point and returns the corresponding character. Essentially, it converts a numeric Unicode code point into its corresponding Unicode character.

For example, chr(65) would yield the character ‘A’, as 65 is the Unicode code point for the uppercase letter ‘A’.

char = chr(65)
print(char)  # Output: 'A'

compile() function

The compile() function transforms a source code string into a code object, which can then be executed or evaluated by the Python interpreter. The resulting code object can be executed using the exec() function or evaluated with eval() function.

The compile() function is beneficial in situations where dynamic generation or manipulation of Python code is required at runtime. It is commonly used in scenarios such as code generation, interpreter development, and dynamic execution of Python code within a program.

compiled_code = compile("print('Hello, World!')", "", "exec")
exec(compiled_code)  # Output: Hello, World!

complex() function

The complex() function is used to create a complex number from either real and imaginary parts or from a single numerical value. Complex numbers are essential in mathematical and scientific computations, especially in fields like engineering and physics.

The complex() function facilitates the creation and manipulation of complex numbers in a straightforward manner.

complex_num = complex(1, 2)
print(complex_num)  # Output: (1+2j)

delattr() function

The delattr() function is used to delete an attribute from an object. This function provides a dynamic way to manage an object’s attributes during runtime.

It is particularly useful when you need to modify or clean up an object’s structure by removing certain attributes dynamically.

class Example:
    x = 10

obj = Example()
delattr(obj, '`x')
# Now obj.x will raise an AttributeError

dict() function

The dict() function is used to create a new dictionary or convert an iterable of key-value pairs into a dictionary. When no arguments are provided, it returns an empty dictionary.

The dict() function provides a convenient and concise way to work with data organization and manipulation in Python programs.

new_dict = dict(a=1, b=2, c=3)
print(new_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

dir() function

The dir() function returns a sorted list of names in the current local scope or the attributes of a specified object. When invoked without arguments, it provides a list of names in the current scope, including variables, functions, and modules. If an object is passed as an argument, dir() returns a list of attributes and methods associated with that object.

This function is valuable for exploring the contents of a module, class, or any Python object. It is often used during development and debugging to examine the structure and capabilities of objects.

dir_list = dir()
print(dir_list)

divmod() function

The divmod() function takes two arguments and returns a tuple containing the quotient and the remainder of the division operation. The first argument represents the dividend, and the second argument is the divisor.

The result is a tuple (a, b), where a is the quotient obtained by performing the floor division of the two numbers, and b is the remainder.

This function is particularly useful in scenarios where both the result of the division and the remainder are needed simultaneously.

divmod_result = divmod(10, 3)
print(divmod_result)  # Output: (3, 1)

enumerate() function

The enumerate() function is commonly used when iterating over sequences like lists, tuples, or strings. It takes an iterable as its argument and returns an iterator that produces tuples containing the index and corresponding element of the iterable.

This function is particularly useful in scenarios where both the index and the value of elements in a sequence are needed during iteration.

fruits = ['apple', 'banana', 'cherry']
enumerated_fruits = list(enumerate(fruits, start=1))
print(enumerated_fruits)
# Output: [(1, 'apple'), (2, 'banana'), (3, 'cherry')]

eval() function

The eval() function allows the dynamic execution of Python expressions or statements represented as strings. It takes a string as its argument and evaluates it as a Python expression, returning the result.

This function is particularly useful in situations where code needs to be generated or executed dynamically during runtime. However, it should be used with caution as it poses security risks, especially if the input string is obtained from untrusted sources, as it can execute arbitrary code.

x = 5
y = 10
result = eval('x + y')
print(result)
# Output: 15

exec() function

The exec() function dynamically executes Python code represented as a string. It takes either a string containing a block of code or a code object as its argument and runs the code within the current Python environment. Similar to the eval() function, exec() allows for the dynamic generation and execution of code during runtime. However, exec() is designed for executing multiple statements or larger code blocks, whereas eval() is generally used for evaluating single expressions.

While exec() provides flexibility for certain advanced programming scenarios, it should be used judiciously due to potential security risks, especially when handling code from untrusted sources.

code = '''
for i in range(5):
    print(i)
'''
exec(code)
# Output:
# 0
# 1
# 2
# 3
# 4

Conclusion

Python’s built-in functions offer a wide array of capabilities, simplifying common programming tasks. Understanding these functions enhances your proficiency as a Python developer, allowing you to write more efficient and concise code. In this comprehensive guide, we’ve explored essential Python functions across different categories. Incorporating these functions into your Python code will undoubtedly enhance your programming experience.


Comments


There are no comments yet.

Write a comment

You can use the Markdown syntax to format your comment.