Built-in Functions
Let’s explore some of Python’s powerful built-in functions. These functions are always available and provide essential tools for various tasks. I’ll cover a few of them along with examples:
-
abs(x): Returns the absolute value of a number. It works for integers, floats, and complex numbers.Pythonnum = -5 print(f"Absolute value of {num} is {abs(num)}") # Output: Absolute value of -5 is 5 -
bin(x): Converts an integer to a binary string (prefixed with “0b”).Pythondecimal_num = 14 binary_representation = bin(decimal_num) print(f"Binary representation of {decimal_num} is {binary_representation}") # Output: Binary representation of 14 is 0b1110 -
bool(x): Converts a value to a Boolean (True or False).Pythonvalue = 0 is_true = bool(value) print(f"Is {value} True? {is_true}") # Output: Is 0 True? False -
len(iterable): Returns the number of items in an iterable (e.g., list, string, tuple).Pythonmy_list = [10, 20, 30, 40] length = len(my_list) print(f"Length of the list: {length}") # Output: Length of the list: 4 -
max(iterable)andmin(iterable): Return the maximum and minimum values from an iterable.Pythonnumbers = [5, 12, 8, 3, 20] max_value = max(numbers) min_value = min(numbers) print(f"Max value: {max_value}, Min value: {min_value}") # Output: Max value: 20, Min value: 3 -
sum(iterable): Calculates the sum of all elements in an iterable (works for numbers).Pythonscores = [85, 90, 78, 92] total_score = sum(scores) print(f"Total score: {total_score}") # Output: Total score: 345 -
round(number, ndigits): Rounds a floating-point number to the specified number of decimal places.Pythonpi = 3.14159 rounded_pi = round(pi, 2) print(f"Rounded pi: {rounded_pi}") # Output: Rounded pi: 3.14
These built-in functions are your trusty companions in Python programming. Explore more of them and leverage their power!
