Python built-in functions

Arthur 178 Published: 10/03/2024

Python built-in functions

I'll respond in English for this one.

Python has a plethora of built-in functions that can simplify your coding experience and make your life easier. Here are some essential ones you should know:

print(): This is the most basic function in Python, used to print output to the console.
print("Hello, world!")

type(): Returns the type of an object or variable.
x = 5

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

len(): Returns the length (number of elements) of a list, tuple, dictionary, or string.
fruits = ['apple', 'banana', 'cherry']

print(len(fruits)) # Output: 3

abs(): Returns the absolute value of a number.
x = -5

print(abs(x)) # Output: 5

round(): Rounds a number to the nearest integer or specified decimal place.
x = 3.14159

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

min() and max(): Return the smallest or largest item in an iterable (like a list or tuple).
numbers = [1, 2, 3, 4, 5]

print(min(numbers)) # Output: 1

print(max(numbers)) # Output: 5

sorted(): Sorts an iterable and returns a new sorted list.
fruits = ['banana', 'apple', 'cherry']

print(sorted(fruits)) # Output: ['apple', 'banana', 'cherry']

sum(): Sums up the elements of an iterable (like a list or tuple).
numbers = [1, 2, 3, 4, 5]

print(sum(numbers)) # Output: 15

input() and int(input()): Allow user input and convert it to an integer.
x = int(input("Enter a number: "))

print(x) # User enters 42; prints 42

eval(): Evaluates a string as Python code and returns the result.
result = eval('5 * 2')  # Output: 10

chr() and ord(): Convert between characters and their ASCII codes.
char = 'A'

print(ord(char)) # Output: 65

code = 65

print(chr(code)) # Output: A

These are just a few of the many built-in functions available in Python. Mastering these can greatly simplify your coding experience and improve your overall productivity.

That's it!

What is documentation string in Python?

I'll respond in English for this question.

In Python, a documentation string (also known as docstring) is a string literal that occurs as the first statement in a function, class, or method definition. Its primary purpose is to provide documentation about what the code does, what parameters it takes, what it returns, and any other relevant details.

Docstrings are useful for several reasons:

Code readability: A well-written docstring helps readers understand what your code does, making it easier to use, maintain, or even modify. Automatic documentation generation: Many IDEs (Integrated Development Environments) and documentation tools can automatically generate documentation based on the docstrings you've written.

Python uses the triple quotes (""") to denote a block of text that is intended as documentation. The most common way to use docstrings is with function definitions, where it describes what the function does, its parameters, return value, and any other relevant details. Here's an example:

def greet(name: str) -> None:

"""

Prints a personalized greeting message.

Args:

name (str): The person's name to include in the greeting.

Returns:

None: No explicit return value.

"""

print(f"Hello, {name}!")

In this example, the docstring explains what the greet function does, its single argument (name) and its return type (None).

How do I use docstrings in Python?

Define a docstring: Place your docstring at the top of your function, class, or method definition. Use triple quotes: Start your docstring with triple quotes (""") and end it with another set of triple quotes. Format for readability: Use blank lines to separate paragraphs within your docstring, and indent blocks using four spaces (or any other consistent amount) to make them readable. Be concise and clear: Aim for a length that's long enough to provide useful information but not so long that it becomes tedious to read. Use the correct structure: Your docstring should follow the structure: [summary], [optional additional info].

Tools and libraries that use Python docstrings

Several tools and libraries can automatically generate documentation from Python docstrings:

Sphinx: A popular tool for generating HTML, PDF, or LaTeX documentation. Doxygen: Another tool for generating HTML documentation. Pydoc: The built-in Python documentation generator that uses docstrings to create HTML files. AutoDoc: A library that helps generate documentation with minimal effort.

Best practices

Write concise and clear docstrings: Aim for a length that provides useful information without being overwhelming. Use proper capitalization: Follow the standard Python coding style guide, which recommends using underscores (_) to separate words in identifiers (e.g., my_function_name), but not in docstrings (e.g., "My Function Name"). Document your code thoroughly: Write detailed docstrings for critical functions or classes, and shorter ones for less complex code.

By following these best practices, you'll be creating valuable documentation that helps others understand and use your Python code effectively.