7.2 Distinguish between built in functions and user defined functions
Distinguishing between Python built-in functions and user-defined functions can be done by understanding their characteristics and origins. Here's a detailed explanation of each:
7.2a Python Built-in Functions
- Predefined - Built-in functions are pre-installed with Python and are available out-of-the-box.
- Part of Python Standard Library - They are part of Python's standard library and are universally available in any Python environment.
- Consistent Behavior - They have consistent behavior and are well-documented.
- No Need for Definition - They do not require any user-defined code to be written; they can be used directly.
Examples:
print()
- Outputs text or other data to the console.len()
- Returns the length of an object.sum()
- Sums the items of an iterable.type()
- Returns the type of an object.
Example 7.2.1 - with built-in functions.
# Using built-in functions
print("Hello, world!") # Output: Hello, world!
length = len([1, 2, 3, 4]) # length is 4
total = sum([1, 2, 3, 4]) # total is 10
data_type = type(42) # data_type is <class 'int'>
7.2b User-defined functions characteristics
- Custom Definitions - User-defined functions are created by the programmer to perform specific tasks.
- Defined Using def Keyword - They are defined using the def keyword followed by a function name and parentheses containing parameters.
- Scope Limited to the Script/Module - They are available only within the script or module where they are defined unless explicitly imported elsewhere.
- Flexible - They can be tailored to fit the specific needs of a program.
Examples of user-defined function are any function you define to perform a particular task. More examples are available in section 7.3 where we will learn how to create user-defined functions.
7.2c Summary of differences
Feature | Built-in Functions | User-defined Functions |
---|---|---|
Availability | Predefined, always available | Defined by the user |
Location | Part of the Python standard library | Located in user scripts or modules |
Customization | Cannot be changed | Fully customizable |
Definition | No need for user definition | Defined using the def keyword |
Examples | print(), len(), sum(), type() | Any function created by the user |
7.2d Identifying Functions
To determine if a function is built-in or user-defined:
- Check Documentation - Built-in functions are documented in the Python Standard Library documentation.
- Source Code- User-defined functions are present in your script or module, and their definitions start with the def keyword.
- Use the builtins Module: You can inspect the builtins module to see all built-in functions available in Python.
By understanding these characteristics and using these methods, you can easily distinguish between built-in and user-defined functions in Python.