General Built-in Functions
Explore how to utilize Python's built-in functions such as divmod for quotient and remainder, reversed for accessing elements backwards, round for approximations, and functions like hex, bin, and sorted for conversions and sorting. Understand their practical applications through example programs to enhance your coding skills.
We'll cover the following...
Built-in functions
Python provides built-in utility functions that make it easier for programmers to perform routine tasks. The best-known built-in functions are len(), range(), input(), and print().
Let’s explore some commonly used built-in functions.
Quotient and remainder together
The divmod() function computes the remainder after the division of two numbers. It differs from the modulus operator % in that it returns two resulting values, the quotient and the remainder.
Remember: A function in Python might return two or more values.
Let’s use an example program to explore the difference between the divmod() function and the % operator.
In the program above:
-
We use
%to calculate the remainder. -
We use built-in
divmod()function, which accepts two parameters:- The dividend
- The divisor
-
The function then returns two values:
- The quotient
- The remainder
Reverse order
The reversed() function is used to access the elements of a list or string in reverse order. The result of this function can be accessed with the help of a loop. The following code will demonstrate how this function works:
In the program above:
- A list passes to the
reversed()function in theforloop statement. - Each element of the list displays in reverse order in the body of the loop.
- A string passes to the