FUNCTIONS IN PYTHON


In general, functions are blocks of statements that are executed to perform certain tasks. In python, we can group a set of statements together to execute a certain task. Python has a rich set of libraries or modules that provides an extensive set of standard functions for various tasks. Some of the most frequently used python built-in functions are as follows:

print(): Outputs text or variables to the console.

print("Hello, world!")

input(): Takes user input from the console.

name = input("Enter your name: ")
print("Hello,", name)

len(): Returns the length of a sequence (such as a string, list, tuple, or dictionary).

my_string = "Hello"
print(len(my_string))  # Output: 5

type(): Returns the type of an object.

x = 5
print(type(x))  # Output: <class 'int'>

range(): Generates a sequence of numbers.

for i in range(5):
    print(i)

max(): Returns the maximum value in a sequence.

numbers = [1, 3, 5, 7, 9]
print(max(numbers))  # Output: 9

min(): Returns the minimum value in a sequence.

numbers = [1, 3, 5, 7, 9]
print(min(numbers))  # Output: 1

sum(): Returns the sum of all elements in a sequence.

numbers = [1, 2, 3, 4, 5]
print(sum(numbers))  # Output: 15

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

x = -5
print(abs(x))  # Output: 5

round(): Rounds a number to a specified precision.

x = 3.14159
print(round(x, 2))  # Output: 3.14

We can use built-in help() method, to get documentation about other functions and objects. Example:

help(str)

output:

Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.