Python for Everybody: Learn Python from Scratch
About Lesson

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:

  1. abs(x): Returns the absolute value of a number. It works for integers, floats, and complex numbers.

    Python
    num = -5
    print(f"Absolute value of {num} is {abs(num)}")
    # Output: Absolute value of -5 is 5
    
  2. bin(x): Converts an integer to a binary string (prefixed with “0b”).

    Python
    decimal_num = 14
    binary_representation = bin(decimal_num)
    print(f"Binary representation of {decimal_num} is {binary_representation}")
    # Output: Binary representation of 14 is 0b1110
    
  3. bool(x): Converts a value to a Boolean (True or False).

    Python
    value = 0
    is_true = bool(value)
    print(f"Is {value} True? {is_true}")
    # Output: Is 0 True? False
    
  4. len(iterable): Returns the number of items in an iterable (e.g., list, string, tuple).

    Python
    my_list = [10, 20, 30, 40]
    length = len(my_list)
    print(f"Length of the list: {length}")
    # Output: Length of the list: 4
    
  5. max(iterable) and min(iterable): Return the maximum and minimum values from an iterable.

    Python
    numbers = [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
    
  6. sum(iterable): Calculates the sum of all elements in an iterable (works for numbers).

    Python
    scores = [85, 90, 78, 92]
    total_score = sum(scores)
    print(f"Total score: {total_score}")
    # Output: Total score: 345
    
  7. round(number, ndigits): Rounds a floating-point number to the specified number of decimal places.

    Python
    pi = 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!

Join the conversation