search

Python Tutorial - unction

Jan 06, 2025 pm 01:52 PM

Introduction

The function is a callable unit containing instructions, aimed at reducing code duplication and organizing complex tasks. There are two types: void functions (no return value) and those that return a value.

This is the basic structure of function in Python.

def function_name(args):
    function body

This is an example of a void function (no return value) in Python.

# create a function
def hello():
    print("hello!")

# call the function
hello()

Output

hello!

Based on the code above, the function called hello() is created. The function is called by specifying the function name followed by parentheses ().

This is an example of fa unction with the return value.

# create a function with return value
def add(a,b):
    return a + b

result = add(2,4)

print(result)

Output

6

Based on the code above, the function called add() is created to sum two numbers. The return value of the add() function is stored inside the result variable.

When working with the return value function, ensure the returned value is being used.

Arguments and Keyword Arguments

The function in Python can take multiple arguments dynamically. There are two approaches to implementing multiple arguments in a function:

  • Arguments: the multiple arguments are implemented in a function without specifying the keywords. the arguments can be implemented using *args.

  • Keyword arguments: the multiple arguments are implemented in a function with the specified keywords. the keyword arguments can be implemented using **kwargs.

Both arguments and keyword arguments must be located in the last position of the argument definition in a function.

This is an example of multiple arguments implementation using the arguments approach to calculate the sum of the numbers dynamically.

def sum(*args):
    result = 0
    for arg in args:
        result += arg
    return result

print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,4,3,2))

Output

3
6
24

Based on the code above, the sum() function can be called with a different number of parameters.

This is an example of multiple arguments implementation using the keyword arguments approach.

def display_info(name,**kwargs):
    print("========")
    print(f"name: {name}")
    print("other informations")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("========")

display_info("john",job="programmer",company="acme inc")
display_info("doe",job="programmer",company="acme inc",skills="go,java,php")

Output

========
name: john
other informations
job: programmer
company: acme inc
========
========
name: doe
other informations
job: programmer
company: acme inc
skills: go,java,php
========

Based on the code above, the display_info() function can be called with a different number of parameters. By using **kwargs, the parameters can be defined with the keywords.

Both arguments and keyword arguments can be used together. This is an example.

def display(*args,**kwargs):
    print("===========")
    print("items")
    for arg in args:
        print(arg)
    print("other information")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("===========")

display("apple","coffee","milk",payment="cash")
display("TV","Camera",payment="cash",delivery="express")

Output

===========
items
apple
coffee
milk
other information
payment: cash
===========
===========
items
TV
Camera
other information
payment: cash
delivery: express
===========

Recursive Function

The recursive function is a function that calls itself when accomplishing its task. The recursive function can solve many problems including factorial numbers, the Fibonacci sequence, and others.

There are two main components in a recursive function:

  • Base case: the base case defines when the function is stopped.
  • Recurrence relation: the recurrence relation defines the recursive process of the function.

In this example, the factorial calculation is implemented using a recursive function.

def function_name(args):
    function body

Output

# create a function
def hello():
    print("hello!")

# call the function
hello()

Let's take a closer look to the factorial() function. There are two components involved in this function:

  • base case: the function execution terminates if the value of n equals to 0 or 1.

  • recurrence relation: the function executes if the value of n greater than 1.

hello!

The factorial() function is illustrated in this picture below.

Python Tutorial - unction

Lambda

The lambda is an anonymous function. The lambda can contain many arguments just like function in general. The lambda function is suitable for creating a small function that returns the value directly.

This is an example of the sum() function.

# create a function with return value
def add(a,b):
    return a + b

result = add(2,4)

print(result)

This is the example of a lambda function to sum two numbers. The lambda function is stored inside a variable called sum_func.

6

To use the lambda function, call the function by its variable name.

def sum(*args):
    result = 0
    for arg in args:
        result += arg
    return result

print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,4,3,2))

Map and Filter

Map Function

The map() function executes a provided callback function for each item inside a list.

This is the example of the map() function to multiply each number by 3.

3
6
24

Output

def display_info(name,**kwargs):
    print("========")
    print(f"name: {name}")
    print("other informations")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("========")

display_info("john",job="programmer",company="acme inc")
display_info("doe",job="programmer",company="acme inc",skills="go,java,php")

Based on the code above, the triple() function acts as a callback for the map() function which means the triple() function is called for each item in the numbers list. Then, the result of the map() function is converted into the list and then stored inside the variable called result.

The example above can be simplified using the lambda function.

========
name: john
other informations
job: programmer
company: acme inc
========
========
name: doe
other informations
job: programmer
company: acme inc
skills: go,java,php
========

Output

def display(*args,**kwargs):
    print("===========")
    print("items")
    for arg in args:
        print(arg)
    print("other information")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("===========")

display("apple","coffee","milk",payment="cash")
display("TV","Camera",payment="cash",delivery="express")

Filter Function

The filter() function selects the item inside a list based on the given callback function. The filter() function is suitable for filtering the items inside a list by using the provided callback function. The filter() function requires a callback function that returns a boolean value.

This is the example of the filter() function to select only even numbers in a list.

===========
items
apple
coffee
milk
other information
payment: cash
===========
===========
items
TV
Camera
other information
payment: cash
delivery: express
===========

Output

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

# call the function
result = factorial(5)

print(result)

Based on the code above, the filter() function uses is_even() as a callback function to select the even numbers from the list.

This example can be simplified using the lambda function.

120

Output

def function_name(args):
    function body

Example - Remove Duplicate Codes

The function can be used to remove duplicate codes. For example, there are two functions called register() and login(). Both functions is using the validation process.

# create a function
def hello():
    print("hello!")

# call the function
hello()

There is a duplicate code for the validation process. To remove these duplicates, the validation process can be wrapped in a separate function.

hello!

The validate() function can be used inside the register() and login() functions.

# create a function with return value
def add(a,b):
    return a + b

result = add(2,4)

print(result)

Based on the code above, the code is cleaner and easier to modify because if the additional validation rules are updated, the validation rules can be updated in one place (inside the validate() function).

Tips

These are the key tips when working with a function in Python.

  • The function must complete a single task. If multiple tasks are required, create a separate function for other tasks.

  • The maximum number of function arguments is 3. If the arguments seem more than 3, consider using a dedicated data object for the function argument.

The maximum number of function arguments seems debatable.

This is the example of the create_account() function using arguments.

6

The create_account() function can be modified to use data object for cleaner code.

def sum(*args):
    result = 0
    for arg in args:
        result += arg
    return result

print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,4,3,2))
  • Use documentation to explain the function description. The documentation can be added using """ syntax.

This is an example of using documentation inside a function.

3
6
24

Sources

  • Arguments and keyword arguments in function
  • Recursive function illustrations

I hope this article helps you learn Python. If you have any feedback, please let me know in the comment section.

The above is the detailed content of Python Tutorial - unction. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.