Search⌘ K

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.

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.

Python 3.10.4
print(13 % 3)
print (divmod(13 , 4))
# we can store the two results as below
q , r = divmod(13 , 4)
print('Quotient:',q)
print('Remainder:',r)

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:

Python 3.10.4
for a in reversed([1,2,3]):
print(a)
for b in reversed("nib"):
print(b)

In the program above:

  • A list passes to the reversed() function in the for loop statement.
  • Each element of the list displays in reverse order in the body of the loop.
  • A string passes to the
...