Python is a powerful and versatile programming language that has a wide variety of built-in functions. These are functions that are already available to use as soon as Python is installed, without the need for any additional imports. In this chapter, we'll explore some of Python's most useful built-in functions and how they can be used in systems programming with Python and Django.
Abs()
The abs() function returns the absolute value of a number. The absolute value of a number is its distance from zero on the real number line, without regard to direction. For example, abs(-5) and abs(5) both return 5.
>>> abs(-5) 5 >>> abs(5) 5
Bin()
The bin() function converts an integer to a binary string. For example, bin(10) returns '0b1010', which is the binary representation of 10.
>>> bin(10) '0b1010'
Bool()
The bool() function converts a value into a boolean value. If the value is true, it returns True. If the value is false, it returns False. For example, bool(0) returns False, while bool(1) returns True.
>>> bool(0) False >>> bool(1) true
Chr()
The chr() function returns a string representing a character whose Unicode code is the specified integer. For example, chr(97) returns 'a'.
>>> chr(97) 'The'
Dict()
The dict() function creates a new dictionary. A dictionary is a collection of key-value pairs. For example, dict(a=1, b=2) returns {'a': 1, 'b': 2}.
>>> dict(a=1, b=2) {'a': 1, 'b': 2}
Enumerate()
The enumerate() function takes a collection (eg a list) and returns an enumerated object. This enumerated object can be used in for loops to iterate over the collection, along with an index. For example:
>>> for i, v in enumerate(['a', 'b', 'c']): ... print(i, v) ... 0 to 1 b 2c
Filter()
The filter() function constructs a list of elements for which a function returns true. The filter() function needs a function as its first argument. The function needs to return a boolean value (true or false). This function will be applied to each element of the list. Only if the function returns True will the list element be included in the result.
>>> def is_positive(n): ... return n > 0 ... >>> list(filter(is_positive, [0, 1, -1, 2, -2])) [1, 2]
These are just a few of the many built-in functions available in Python. By becoming familiar with these functions, you can write more efficient and concise Python code. In the next chapter, we'll explore more built-in functions and how they can be used in systems programming with Python and Django.