search
HomeBackend DevelopmentPython TutorialWhat are the examples of python custom functions?

What are the examples of python custom functions?

Jun 22, 2020 am 11:02 AM
pythonCustom function

What are the examples of python custom functions?

Recommended tutorial: "python video tutorial"

What are the examples of python custom functions?

Examples of python custom functions include:

1. What is a function?

A function is an organized, reusable code segment used to implement a single or related function. Functions can improve application modularity and code reuse.

2. Function definition method:

def test(x):
    '函数定义方法'
    x+=1
    return x

Explanation:

def: Define function keywords

test: Function name

(): Definable formal parameters

'': Document description

x =1: Code block or program processing logic

return:End and return value

Why should a function have a return value? ?

Receive the execution result of the function through the return value, and subsequent logic needs to use this result to perform its corresponding operation.

(1), Example: Write log information to a file

import time
# 定义函数
def test1():
    '函数练习:添加日志记录'
    log_time = time.strftime('%Y-%m-%d %X')
    with open('file_a','a') as f:
        f.write(log_time+':log msg\n')
# 调用函数
test1()

(2), Function return value description:

return Number of return values ​​= 0: Return one None value (none)

Return value = 1: Object (Object)

rebate Value & GT; :

#函数返回类型
def test_None():
    print('返回一个空值')
x=test_None()
print(x)
def test_object():
    print('返回一个对象')
    return 0
y=test_object()
print(y)
def test_tuples():
    print('返回一个元组')
    return 1,'hello world',['qwe','asd'],{'001':'simple'}
z=test_tuples()
print(z)

(3), formal parameters: the defined parameters are called formal parameters (x, y)

Actual parameters: the actual parameters passed in are called actual parameters (1,2)

Without specifying parameters: one-to-one correspondence between actual and formal parameter positions

Example:

Note: When positional parameters are shared and keyword parameters are shared, keyword parameters cannot be written. Before positional parameters

def test_sum(x,y):
    '两数之和'
    z = x + y
    return z
t_sum=test_sum(1,2) #实参与形参位置一一对应
print(t_sum)
t_sum2=test_sum(x=1,y=2) #与形参位置无关
print(t_sum2)
t_sum3=test_sum(1,y=2) # 错误方式:test_sum(x=1,2) 位置传参与关键字传参共用时,关键参数不能写在位置参数之前
print(t_sum3)

(4), default value parameter:

# 默认值参数
def test_default(x,y=2):
    '默认值参数'
    z = x + y
    return z
print(test_default(2)) #print(tesst_default(2,2))

(5), parameter group (indefinite length parameter):

# 参数组,接受位置参数,将多个实参存入一个元组中
# 定义格式:*变量名(一般规范为 *args)
def test_group(*args):
    '参数组'
    print(args)
test_group(1,2,3,4,5,6)
def test_group2(x,*args):
    '参数组与位置参数混用'
    print(x)
    print(args)
test_group2(1,2,3,4,5,6)
# 接受关键字参数组,转换成字典
def test_group3(**kwargs):
    '参数组键值对形式'
    print(kwargs['name'])
test_group3(name='simple',age=25,sex='m')
def test_group4(name,**kwargs):
    '参数、参数组键值对混用'
    print(name)
    print(kwargs)
test_group4('simple',age=25,sex='m')
#注:参数组必须放在位置参数、默认参数之后
def test_group5(name,age=25,**kwargs):
    '参数、默认参数、参数组键值对混用'
    print(name)
    print(age)
    print(kwargs)
test_group5('simple',age=3,sex='m',game='lol')
def test_group6(name,age=25,*args,**kwargs):
    '参数、默认参数、参数组、参数组键值对混用'
    print(name)
    print(age)
    print(*args)
    print(kwargs)
test_group5('simple',age=3,sex='m',game='lol')

Recommended related articles: "

python tutorial

"

The above is the detailed content of What are the examples of python custom functions?. 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
Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use