Translate

Friday 16 February 2024

Built-in Functions in Python

 Built-in Functions in Python

Core Data Types

  • Numeric:

  • abs(x): Returns the absolute value of a number.

  • int(x): Converts a number or string to an integer.

  • float(x): Converts a number or string to a floating-point number.

  • complex(real, imag): Creates a complex number.

  • divmod(x, y): Returns the quotient and remainder of the division.

  • pow(x, y): Returns x to the power of y.

  • round(x, n): Returns x rounded to n decimal places.

  • Boolean:

  • bool(x): Converts a value to a Boolean (True or False).

  • Strings:

  • chr(x): Returns the character corresponding to Unicode code point x.

  • ord(x): Returns the Unicode code point of a character.

  • len(s): Returns the length of a string.

  • format(format_string, *args): Formats a string using values provided.

  • str(x): Converts an object to a string representation.

  • Iterables (Sequences, Sets, Mappings):

  • all(iterable): Returns True if all elements of an iterable are true.

  • any(iterable): Returns True if any element of an iterable is true.

  • enumerate(iterable, start=0): Returns an enumerate object of (index, value) pairs.

  • len(s): Returns the length (number of items) in an object.

  • list(iterable): Converts an iterable to a list.

  • max(iterable): Returns the largest item in an iterable.

  • min(iterable): Returns the smallest item in an iterable.

  • range(start, stop, step): Generates a sequence of numbers.

  • reversed(seq): Returns a reverse iterator over a sequence.

  • set(iterable): Creates a set.

  • sorted(iterable): Returns a sorted list from an iterable.

  • dict(iterable): Creates a dictionary

Input/Output

  • print(*objects, sep=' ', end='\n', file=sys.stdout): Prints objects to the console.

  • input(prompt=None): Reads a line of input from the user.

Type Inspection and Conversion

  • type(x): Returns the type of an object.

  • isinstance(object, classinfo): Checks if an object is an instance of a class (or of a subclass).

  • issubclass(class, classinfo): Checks if a class is a subclass of another class.

Object Manipulation

  • id(x): Returns the unique identifier of an object.

  • dir(object): Returns a list of attributes and methods of an object.

  • hasattr(object, name): Checks if an object has an attribute.

  • getattr(object, name, default): Returns the value of an object's attribute.

  • setattr(object, name, value): Sets the value of an object's attribute.

  • delattr(object, name): Deletes an attribute from an object.

Math

  • min(x, y, ...): Returns smallest among arguments.

  • max(x, y, ...): Returns largest among arguments.

  • sum(iterable): Returns sum of items in an iterable.

  • And many more from the math module: Import the math module to use functions like sin, cos, sqrt, factorial, etc.

Other Important Functions

  • open(file, mode='r'): Opens a file and returns a file object.

  • help(object): Accesses the built-in help system.

  • globals(): Returns a dictionary representing the current global namespace.

  • locals(): Returns a dictionary representing the current local namespace.

Important Notes

  • Python has many more built-in functions! Use help() in your Python interpreter to explore further.

  • Several useful functions reside in standard library modules. Import those modules (e.g., import math, import random) to access them.


---------------------------------------------------------

.

1. abs(x): Absolute Value

  • Purpose: Calculates the distance of a number from zero, always giving a positive result.

  • Example:
    Python
    print(abs(-10))   # Output: 10
    print(abs(5.7))   # Output: 5.7

2. int(x): Integer Conversion

  • Purpose: Transforms a compatible number (float or string representing a number) into a whole number (integer).

  • Example:
    Python
    print(int(3.14))    # Output: 3
    print(int("-45"))   # Output: -45

  • Important: If x cannot be converted cleanly, a ValueError will be raised.

3. float(x): Floating-Point Conversion

  • Purpose: Transforms a number or a compatible string into a floating-point number (a number with decimals).

  • Example:
    Python
    print(float(5))     # Output: 5.0
    print(float("3.14159"))  # Output: 3.14159

4. complex(real, imag): Complex Number Creation

  • Purpose: Constructs a complex number where 'real' is the real part and 'imag' is the imaginary part.

  • Example:
    Python
    c = complex(2, -3)   # Represents the complex number 2 - 3j
    print(c)             # Output: (2-3j)

5. divmod(x, y): Division and Remainder

  • Purpose: Performs division and returns a tuple containing the quotient and remainder.

  • Example:
    Python
    result = divmod(17, 3)
    print(result)        # Output: (5, 2)  # 17 divided by 3 is 5 with a remainder of 2

6. pow(x, y): Exponentiation

  • Purpose: Calculates x raised to the power of y (x**y).

  • Example:
    Python
    print(pow(2, 3))    # Output: 8 (2 cubed)
    print(pow(5, 0))    # Output: 1 (any non-zero number to the power of 0 is 1)

7. round(x, n): Rounding

  • Purpose: Rounds a number (x) to a specified number of decimal places (n).

  • Example:
    Python
    print(round(3.14159, 2))  # Output: 3.14
    print(round(42, -1))      # Output: 40 (rounds to the nearest ten)



Boolean

  • bool(x): The Truthiness of Values

  • Purpose: Converts a value to its Boolean equivalent (True or False). This becomes incredibly useful when you need to work with conditional statements.

  • Key Concepts:

  • "Truthy" values: Values that evaluate to True when passed through bool(). Examples include non-zero numbers, non-empty strings, lists, dictionaries, etc.

  • "Falsy" values: Values that evaluate to False when passed through bool(). Examples include zero (0, 0.0), empty strings (""), empty lists ([]), empty dictionaries ({}), and the special value None.

  • Examples:
    Python
    print(bool(5))        # Output: True
    print(bool(""))       # Output: False
    print(bool([1, 2]))   # Output: True 
    print(bool(None))     # Output: False

Strings

  • chr(x): Unicode to Character

  • Purpose: Takes a Unicode code point (an integer) and returns the corresponding character.

  • Example:
    Python
    print(chr(65))   # Output: 'A' (Unicode code point for capital A)
    print(chr(9728)) # Output: '☂' (Unicode code point for an umbrella)

  • ord(x): Character to Unicode

  • Purpose: Does the opposite of chr(). Takes a single character and returns its Unicode code point.

  • Example:
    Python
    print(ord('B'))   # Output: 66
    print(ord('Ï€'))  # Output: 960

  • len(s): String Length

  • Purpose: Returns the number of characters in a string.

  • Example:
    Python
    message = "Hello, world!"
    length = len(message)
    print(length)   # Output: 13

  • format(format_string, *args): String Formatting

  • Purpose: Provides a powerful way to insert values into strings and control their presentation.

  • Example:
    Python
    name = "Alice"
    age = 30
    output = "My name is {} and I am {} years old.".format(name, age)
    print(output)  # Output: My name is Alice and I am 30 years old.

  • str(x): Object to String

  • Purpose: Converts a value or object into its string representation.

  • Example:
    Python
    num = 42
    num_str = str(num)
    print(type(num_str))  # Output: <class 'str'>




Iterables: Understanding the Concept

  • Iterables are objects in Python that contain multiple elements you can "iterate" over. This means you can process them one element at a time using loops or other techniques.

  • Common types of iterables include lists, tuples, strings, sets, and dictionaries.

Functions for Iterables

  1. all(iterable)

  • Purpose: Returns True if every element in the iterable is "truthy" (See explanation of truthiness under the bool() function). Returns False otherwise.

  • Example:
    Python
    numbers = [1, 5, 0, -2]
    all_positive = all(num > 0 for num in numbers)  # all_positive will be False

  1. any(iterable)

  • Purpose: Returns True if at least one element in the iterable is "truthy". Returns False if all elements are "falsy".

  • Example:
    Python
    letters = ['a', '', 'x']
    has_letters = any(letter for letter in letters)  # has_letters will be True

  1. enumerate(iterable, start=0)

  • Purpose: Returns an "enumerate object" that yields pairs of (index, value) for each item in the iterable. The optional start argument controls the starting index value.

  • Example:
    Python
    fruits = ['apple', 'banana', 'mango']
    for index, fruit in enumerate(fruits, start=1):
        print(f"{index}. {fruit}")

  1. len(s)

  • Purpose: Returns the number of elements (length) in any iterable object.

  • Example: See previous examples

  1. list(iterable)

  • Purpose: Converts any iterable (tuples, strings, sets, etc.) into a list.

  • Example: See previous examples.

  1. max(iterable) & min(iterable)

  • Purpose: Finds the largest or smallest element in an iterable. Works best with numbers or objects that can be compared.

  • Example:
    Python
    temps = [25, 18, 30, 21]
    highest = max(temps)
    lowest = min(temps)

  1. range(start, stop, step)

  • Purpose: Generates a sequence of numbers. start (inclusive), stop (exclusive), and step (difference between numbers) are the arguments.

  • Example: See previous examples

  1. reversed(seq)

  • Purpose: Returns an iterator that provides the elements of a sequence in reverse order.

  • Example:
    Python
    colors = ["red", "green", "blue"]
    for color in reversed(colors):
        print(color)

  1. set(iterable)

  • Purpose: Creates an unordered set (a collection of unique elements) from an iterable.

  • Example: See previous examples

  1. sorted(iterable)

  • Purpose: Returns a new sorted list from the elements of an iterable.

  • Example:
    Python
    numbers = [6, 3, 1, 8]
    sorted_numbers = sorted(numbers)
    print(sorted_numbers)  # Output: [1, 3, 6, 8]


vlrtraining

Input/Output

  • print(*objects, sep=' ', end='\n', file=sys.stdout)

  • Purpose: The workhorse of output in Python. Sends formatted text and objects to the console (or another output stream).

  • Key Arguments:

  • *objects: The things you want to print. Can be strings, numbers, variables, and more.

  • sep: Specifies the separator between objects (defaults to a space ' ').

  • end: Specifies what to print at the end of the line (defaults to a newline '\n').

  • file: Where to send the output (defaults to sys.stdout, which is the standard console output).

  • Examples:
    Python
    print("Hello,", "world!"# Output: Hello, world!
    print(1, 2, 3, sep='-')    # Output: 1-2-3
    print("The answer is", 42, end='!\n')   # Output: The answer is 42!

  • input(prompt=None)

  • Purpose: Pauses execution and waits for the user to type in a line of text and press Enter.

  • Argument:

  • prompt: An optional string message displayed to the user before they enter input.

  • Example:
    Python
    name = input("What's your name? ")
    print("Hello,", name)

Type Inspection and Conversion

  • type(x)

  • Purpose: Reveals the data type of an object.

  • Example:
    Python
    a = 5
    b = "Hello"
    c = 3.14
    print(type(a))  # Output: <class 'int'>
    print(type(b))  # Output: <class 'str'>
    print(type(c))  # Output: <class 'float'>

  • isinstance(object, classinfo)

  • Purpose: Checks if an object is an instance of a particular class or one of its subclasses. Returns True or False.

  • Example:
    Python
    class Animal:
        pass

    dog = Animal()
    print(isinstance(dog, Animal))   # Output: True
    print(isinstance(5, int))         # Output: True
    print(isinstance("hello", int))  # Output: False

  • issubclass(class, classinfo)

  • Purpose: Checks if one class is a subclass (derived class) of another class. Returns True or False.

  • Example:
    Python
    class Pet:
        pass

    class Dog(Pet):
        pass

    print(issubclass(Dog, Pet))   # Output: True
    print(issubclass(int, object)) # Output: True (all classes inherit from 'object')



Understanding Objects

In Python, almost everything is an object. Objects store data (attributes) and have associated behaviors (methods). These built-in functions allow you to introspect and modify objects during your program's execution.

Functions for Object Manipulation

  1. id(x)

  • Purpose: Returns a unique integer identifier for any object. This identifier is typically related to the object's location in memory.

  • Example:
    Python
    num = 42
    text = "hello"
    print(id(num)) 
    print(id(text))

  1. dir(object)

  • Purpose: Returns a list of the valid attributes (data and methods) associated with an object. This is incredibly useful when exploring what you can do with a particular object.

  • Example:
    Python
    numbers = [1, 2, 3]
    print(dir(numbers))  # You'll see methods like append, sort, etc.

  1. hasattr(object, name)

  • Purpose: Checks if an object has a specific attribute. Returns True if the attribute exists, False otherwise.

  • Example:
    Python
    class Person:
        name = "Alice"

    person = Person()
    print(hasattr(person, "name"))  # Output: True
    print(hasattr(person, "age"))  # Output: False

  1. getattr(object, name, default)

  • Purpose: Retrieves the value of an object's attribute.

  • Arguments

  • object: The object you're working with.

  • name: The name of the attribute as a string.

  • default (optional): A value to return if the attribute doesn't exist.

  • Example:
    Python
    class Employee:
        emp_id = 101

    emp = Employee()
    print(getattr(emp, "emp_id"))  # Output: 101

  1. setattr(object, name, value)

  • Purpose: Sets the value of an attribute on an object. If the attribute doesn't exist, it's created.

  • Example:
    Python
    class Student:
        pass  # Empty class initially

    student = Student()
    setattr(student, "name", "Bob")
    setattr(student, "grade", 10)

  1. delattr(object, name)

  • Purpose: Deletes an attribute from an object. Be careful – once deleted, it's gone!

  • Example:
    Python
    class Car:
        color = "red"

    my_car = Car()
    delattr(my_car, "color")

Important Notes

  • Manipulating an object's attributes directly can sometimes lead to unexpected behavior if the object has internal mechanisms tied to them. When possible, it's often better to use an object's methods designed for modification.

  • Some objects (like basic numbers and strings) are immutable, meaning their attributes cannot be changed after creation.



Built-in Math Functions

  • min(x, y, ...) & max(x, y, ...)

  • Purpose: These functions find the smallest or largest value from a series of arguments. They work with numbers or any objects that can be compared.

  • Example:
    Python
    print(min(3, 7, 1, 9))           # Output: 1
    print(max("apple", "banana", "kiwi"))  # Output: kiwi (alphabetical order)

  • sum(iterable)

  • Purpose: Calculates the total sum of numbers within an iterable object (like lists or tuples).

  • Example:
    Python
    sales = [200, 150, 320, 80]
    total_sales = sum(sales)
    print(total_sales)    # Output: 750

The math Module

The math module extends Python's mathematical toolkit. Here's how to use it and a few key functions:

  1. Import:
    Python
    import math

  2. Example Functions:

  • math.sqrt(x): Calculates the square root of a number.
    Python
    root = math.sqrt(25)
    print(root)   # Output: 5.0

  • math.sin(x), math.cos(x), math.tan(x): Calculates sine, cosine, and tangent of an angle (provided in radians).
    Python
    angle_in_radians = math.pi / 4 
    sine_value = math.sin(angle_in_radians)
    print(sine_value)

  • math.factorial(x): Calculates the factorial of a non-negative integer.
    Python
    fact = math.factorial(5
    print(fact)       # Output: 120 (5! = 5 * 4 * 3 * 2 * 1)

  • math.ceil(x): Rounds up to the smallest integer greater than or equal to x

  • math.floor(x): Rounds down to the largest integer less than or equal to x

  • math.pi: Provides the mathematical constant pi.

  • And many more!

Important Notes

  • The math module offers numerous other functions related to trigonometry, logarithms, exponents, and more.

  • Check out the official documentation for a comprehensive list of all math module functions: https://docs.python.org/3/library/math.html



File Interaction

  • open(file, mode='r')

  • Purpose: This function is your gateway to working with files in Python. It opens a specified file and returns a file object that lets you interact with it.

  • Arguments:

  • file: The path to the file you want to open.

  • mode: Specifies how you intend to use the file. Common modes include:

  • 'r': Read mode (the default).

  • 'w': Write mode (overwrites existing files or creates a new one)

  • 'a': Append mode (adds to the end of an existing file)

  • 'x': Create mode (fails if the file already exists)

  • 'b': Binary mode (for non-text files)

  • '+': Open for both reading and writing

  • Example:
    Python
    with open("my_text_file.txt", 'r') as file:
        contents = file.read()
        print(contents)

  • Important: It's recommended to use the with statement when working with files, as it ensures the file is automatically closed even if errors occur.

Getting Help

  • help(object)

  • Purpose: Python's incredibly useful built-in documentation system. When you pass an object (function, module, class, etc.) to help(), it displays information about it.

  • Example:
    Python
    help(print# Displays information and usage of the print function
    import math
    help(math)   # Shows details about the math module

  • Tip: Use help() liberally while learning Python or when working with unfamiliar elements!

Understanding Namespaces

  • globals()

  • Purpose: Returns a dictionary representing the global namespace (i.e., the currently available variables, functions, etc. at the top level of your program).

  • Example: (Assume this code is in your main script)
    Python
    x = 10
    def my_function():
        pass

    print(globals())
    # Output might look like: {'__name__': '__main__', 'x': 10, 'my_function': <function my_function at 0x7f67a2f67940>, ...}

  • locals()

  • Purpose: Returns a dictionary representing the current local namespace (variables, functions, etc. within the current scope, such as inside a function).

  • Example:
    Python
    def outer_function():
        x = 5
        def inner_function():
            y = 10
            print(locals())  # Output: {'y': 10}
        inner_function()

    outer_function()

Note: Modifying globals() and locals() can have side effects, so use them primarily for inspection and debugging if needed.