Understanding Python Functions: Built‑in and Custom Functions
This article explains the concept of functions in Python, covering built‑in functions, how to create custom functions, and demonstrates examples of parameter‑less, parameterized, and return‑value functions with clear code snippets.
Functions are a fundamental programming concept that enable modular design, and mastering them is essential for any programmer, especially in Python where functional programming is prominently featured.
Built‑in Functions are provided by Python’s standard library and can be called directly without any import; they are often referred to as APIs. For example, print() outputs text to the console and is a classic built‑in function.
Custom Functions are user‑defined blocks of code designed to perform specific tasks, offering encapsulation and reusability. They allow you to package functionality into a “box” that can be invoked whenever needed.
1. Function without parameters
<code># Function definition
def function():
print("hello world")
function()
</code>This defines a simple function that prints "hello world" and demonstrates a parameter‑less function call.
2. Function with parameters
<code># This is a function with parameters
def give(username, number):
print("{}给主播送了{}个西瓜".format(username, number))
give("Tom", 100)
</code>The function give accepts two arguments, username and number , and prints a formatted message. When called with "Tom" and 100, it outputs the corresponding text.
<code>D:\My_Python\Scripts\python.exe D:/My_Python/021.py
hello world
Tom给主播送了100个西瓜
Process finished with exit code 0
</code>3. Function with a return value
<code># This is a function that returns a value
def sum(n1, n2):
result = n1 + n2
return result
sum(1, 2)
</code>The sum function adds two numbers and returns the result, illustrating how a function can provide output back to the caller.
Understanding how to define and invoke functions, whether built‑in or custom, is a prerequisite for mastering object‑oriented programming and more advanced Python techniques.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.