Topic 3: Python Built-in Functions

1. Introduction

Python comes with a library of built-in functions, readily available for use without the need for any imports. These functions are universal, versatile, and form the foundational building blocks for various tasks in Python programming.

2. Basic Utility Functions

a. print() – Displays the specified message or value.
python
print("Hello, World!") # Outputs: Hello, World!
b. input() – Reads a line from input and returns it as a string.
python
name = input("Enter your name: ")
c. len() – Returns the length of an object.
python
print(len("Python")) # Outputs: 6

3. Numeric and Mathematical Functions

a. abs() – Returns the absolute value of a number.
python
print(abs(-5)) # Outputs: 5
b. max() and min() – Returns the largest or smallest of input values.
python
print(max(3, 5, 2)) # Outputs: 5 print(min(3, 5, 2)) # Outputs: 2
c. sum() – Returns the sum of a list or tuple.
python
print(sum([1, 2, 3, 4])) # Outputs: 10
d. round() – Rounds a number to the nearest integer or to the specified number of decimals.
python
print(round(5.6)) # Outputs: 6 print(round(5.678, 2)) # Outputs: 5.68

4. Type Conversion Functions

a. int(), float(), str() – Converts a value to an integer, floating-point number, or string, respectively.
python
print(int("5")) # Outputs: 5 print(float("5.6")) # Outputs: 5.6 print(str(100)) # Outputs: "100"
b. list(), tuple(), set(), dict() – Converts to respective data types.
python
print(list("python")) # Outputs: ['p', 'y', 't', 'h', 'o', 'n']

5. Iteration and Sequence Functions

a. range() – Produces a sequence of numbers.
python
for i in range(3): print(i) # Outputs: 0, 1, 2
b. enumerate() – Returns an enumerate object.
python
for index, value in enumerate(["a", "b", "c"]): print(index, value) # Outputs: 0 a, 1 b, 2 c
c. zip() – Merges two or more lists into a list of tuples.
python
names = ["Alice", "Bob"] ages = [25, 30] print(list(zip(names, ages))) # Outputs: [('Alice', 25), ('Bob', 30)]

6. Information and Testing

a. type() – Returns the type of an object.
python
print(type(5)) # Outputs: <class 'int'>
b. isinstance() – Checks if an object is an instance of a specified type or class tuple.
python
print(isinstance(5, int)) # Outputs: True print(isinstance(5, (str, int))) # Outputs: True

7. Conclusion

Python’s built-in functions are powerful tools that provide core functionality right out of the box. Leveraging these functions can significantly reduce the time and effort required to implement common tasks and checks. As you delve deeper into Python, you’ll find yourself turning to these built-ins frequently, making them an integral part of your coding arsenal.