Table of Contents
Create function
Calling a function
are similar to
Default parameters are parameters that declare
案例:计算任意两个数字的和
模块基础
定义模块
基本概念
导入模块 (import)
模块加载 (load)
模块特性及案例
模块特性
Home Backend Development Python Tutorial How to create and call functions in Python

How to create and call functions in Python

May 20, 2023 pm 12:13 PM
python

Create function

Function is created with def statement, the syntax is as follows:

def 函数名(参数列表):  # 具体情况具体对待,参数可有可无
	"""函数说明文档字符串"""
    函数封装的代码
    ……
Copy after login

The title line is composed of def key word, the name of the function, and the set of arguments (if any) to form the

def The remainder of the clause includes an optional but highly recommended documentation word String , and required function body

The naming of the function name should comply with the naming rules of identifiers

  • can consist of letters, underscores and numbers

  • cannot start with a number

  • cannot Same name as a keyword

def washing_machine():  # 洗衣机可以帮我们完成
    print("打水")
    print("洗衣服")
    print("甩干")
Copy after login
Calling a function

Use a pair of parentheses () to call a function. If there are no parentheses, it is just a reference to the function

Any entered parameters must be placed in brackets

Legend:

How to create and call functions in Python

Case: Add washing powder

def washing_machine():  # 洗衣机可以帮我们完成
    print("打水")
    print("加洗衣粉!!!")
    print("洗衣服")
    print("甩干")
# 早上洗衣服
washing_machine()
# 中午洗衣服
washing_machine()
# 晚上洗衣服
washing_machine()
Copy after login

How to create and call functions in Python

Summary

  • ##After defining a function, it only means that this function encapsulates a piece of code That’s all

  • If you don’t actively call the function, the function will not actively execute

Thinking

  • Can I put the

    function call above the function definition?

    • cannot!

    • Because before

      using the function name to call the function, you must ensure that Python already knows the existence of the function

    • Otherwise the console will prompt

      NameError: name 'menu' is not defined (Name error: the name menu is not defined)

Parameters of function

Formal parameters and actual parameters
  • ##Formal parameters

    :When defining the function , the parameters in parentheses are used to receive parameters. is used as a variable inside the function

  • actual parameters

    :When calling a function, the parameters in parentheses are used to pass data to the inside of the function

Question

When we want to wash other things, we need to manually change the code inside the method:

def washing_machine():  # 洗衣机可以帮我们完成
    print("打水")
    print("加洗衣粉!!!")
    print("洗床单")  # 洗被套
    print("甩干")
Copy after login

There are certain changing values ​​inside the function:

def washing_machine():  # 洗衣机可以帮我们完成
    print("打水")
    print("加洗衣粉!!!")
    print("洗衣服")
    print("甩干")
washing_machine()
def washing_machine():  # 洗衣机可以帮我们完成
    print("打水")
    print("加洗衣粉!!!")
    print("洗床单")
    print("甩干")
washing_machine()
......
Copy after login

Thinking What are the problems?

The function can only process fixed data

How to solve it?

It would be great if the data that needs to be processed can be passed to the inside of the function when calling the function!

Pass parameters

    Fill in the parentheses after the function name
  • Parameters

  • More Use
  • ,

    to separate the parameters

  • When calling a function, the number of actual parameters needs to be consistent with the number of formal parameters, and the actual parameters will be passed to the formal parameters in turn. Parameter
  • def washing_machine(something):  # 洗衣机可以帮我们完成
        print("打水")
        print("加洗衣粉!!!")
        print("洗" + something)
        print("甩干")
    # 洗衣服
    washing_machine("衣服")
    # 洗床单
    washing_machine("床单")
    Copy after login
Legend

def washing_machine(xidiji,something):  # 洗衣机可以帮我们完成
    print("打水")
    print("加" + xidiji)
    print("洗衣服" + something)
    print("甩干")
#早上洗衣服
#按照参数位置顺序传递参数的方式叫做位置传参
#使用洗衣机,执行洗衣机内部的逻辑
washing_machine("洗衣液","衣服")#something = 衣服
#中午洗被罩
washing_machine("洗衣粉","被罩")# something = 被罩
#晚上洗床单
washing_machine("五粮液","床单")# something = 床单
Copy after login
How to create and call functions in Python

Function

The

    function organizes code blocks with independent functions into a small module and calls the parameters of the
  • function when needed to increase the versatility of the function and target the same The data processing logic can adapt to more data
  • 1. Inside the function, use the parameters as variables to perform the required data processing

2. Function call When, according to the parameter order defined by the function, pass the data you want to process inside the function through the parameters

Positional parameters

are similar to
shell

scripts, programs The name and parameters are passed to the python program in the form of positional parameters, using the sys module's argv list to receive the

legend

How to create and call functions in PythonDefault parameters

Default parameters are parameters that declare
default value

. Because the parameters are given default values, they are used when calling functions. It is also allowed not to pass a value to the parameter The return value of the function

    In program development, sometimes, you will want
  • a function to execute After the end, tell the caller a result

    so that the caller can perform subsequent processing on the specific result

  • The return value

    is the function that completes the work After , finally gives the caller's a result

  • The
  • return

    keyword can be used in the function Return results</li><li><p>调用函数一方,可以 <strong>使用变量</strong> 来 <strong>接收</strong> 函数的返回结果</p></li></ul><h5 id="案例-计算任意两个数字的和">案例:计算任意两个数字的和</h5><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'># 函数的返回值: return, 用于对后续逻辑的处理 # 理解: 把结果揣兜里,后续想干啥干啥,想打印打印,想求和就求和 # 注意: # a. 函数中如果没有return,那么解释器会自动加一个return None # b. return表示函数的终止,return后的代码都不会执行 # 1 定义一个函数,计算两个数的和 # 2 计算这两个数的和是不是偶数 def get_sum(x, y=100): # 默认参数 he = x + y # sum = 10 + 20 return he # return 30 print(&quot;return表示函数的终止,return后的代码都不会执行&quot;) # 将函数return后的结果赋值给变量dc: dc = sum -&gt; dc = 30 dc = get_sum(10, 20) # x = 10, y = 20 print(&quot;dc:&quot;, dc) # 30 dc1 = get_sum(10) # x = 10, y = 100 print(&quot;dc1:&quot;, dc1) # 110 # if dc % 2 == 0: # print(&quot;偶数&quot;) # else: # print(&quot;奇数&quot;)</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>#默认参数 #注意:具有默认值的参数后面不能跟没有默认值的参数 def get_sum(a=20,b=5,c=10): he = a + b+ c return he dc = get_sum(1,2,3) #a=1 b=2 c=3 print(&quot;dc:&quot;,dc) # 6 dc1 = get_sum(1,2) # a=1 b=2 c=10 print(&quot;dc1:&quot;,dc1) # 13 dc2 = get_sum(1) # a=1 b=5 c=10 print(&quot;dc2:&quot;,dc2) # 16 dc3 = get_sum() print(&quot;dc3:&quot;,dc3) # 35</pre><div class="contentsignin">Copy after login</div></div><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168455598911182.jpg" class="lazy" alt="How to create and call functions in Python" /></p><p>修改菲波那切数列</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>def new_fib(n=8): list01 = [0,1] #定义列表,指定初始值 for dc in range(n-2): list01.append(list01[-1]+list01[-2]) return list01 dc = new_fib() #不加参数默认是8 dc1 = new_fib(10) print(&quot;dc:&quot;,dc) print(&quot;dc1:&quot;,dc1)</pre><div class="contentsignin">Copy after login</div></div><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168455598947497.jpg" class="lazy" alt="How to create and call functions in Python" /></p><p><strong>生成随机密码:</strong></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>#练习:生成随机密码 #创建 randpass.py 脚本,要求如下: #编写一个能生成8位随机密码的程序 #使用 random 的 choice 函数随机取出字符 #由用户决定密码长度 import random def new_password(): n = int(input(&quot;密码长度:&quot;)) password = &quot;&quot; all = &quot;0123456789zxcvbnmlkjhgfdsaqwertyuiopPOIUYTREWQASDFGHJKLMNBVCXZ&quot; # 0-9 a-z A-Z random.choice(all) for i in range(n): dc = random.choice(all) password += dc # print(&quot;passwd:&quot;,password) return password # 调用函数,才能执行函数内部逻辑 dc = new_password() print(&quot;dc:&quot;,dc)</pre><div class="contentsignin">Copy after login</div></div><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168455598971596.jpg" class="lazy" alt="How to create and call functions in Python" /></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>#练习:生成随机密码 #创建 randpass.py 脚本,要求如下: #编写一个能生成8位随机密码的程序 #使用 random 的 choice 函数随机取出字符 #由用户决定密码长度 import random,string def new_password(): n = int(input(&quot;密码长度:&quot;)) password = &quot;&quot; all = string.ascii_letters + string.digits random.choice(all) for i in range(n): dc = random.choice(all) password += dc # print(&quot;passwd:&quot;,password) return password # 调用函数,才能执行函数内部逻辑 dc = new_password() print(&quot;dc:&quot;,dc)</pre><div class="contentsignin">Copy after login</div></div><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168455598921688.jpg" class="lazy" alt="How to create and call functions in Python" /></p><h4 id="模块基础">模块基础</h4><h5 id="定义模块">定义模块</h5><h6 id="基本概念">基本概念</h6><ul class=" list-paddingleft-2"><li><p>模块是从逻辑上组织python代码的形式</p></li><li><p>当代码量变得相当大的时候,最好把代码分成一些有组织的代码段,前提是保证它们的 <strong>彼此交互</strong></p></li><li><p>这些代码片段相互间有一定的联系,可能是一个包含数据成员和方法的类,也可能是一组相关但彼此独立的操作函数</p></li></ul><h5 id="导入模块-import">导入模块 (import)</h5><ul class=" list-paddingleft-2"><li><p>使用 <strong>import</strong> 导入模块</p></li><li><p>模块属性通过 <strong>“模块名.属性”</strong> 的方法调用</p></li><li><p>如果仅需要模块中的某些属性,也可以单独导入</p></li></ul><p><strong>为什么需要导入模块?</strong></p><p>可以提升开发效率,简化代码</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168455598942924.jpg" class="lazy" alt="How to create and call functions in Python" /></p><p><strong>正确使用</strong></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'># test.py,将 file_copy.py 放在同级目录下 # 需求:要将/etc/passwd复制到/tmp/passwd src_path = &quot;/etc/passwd&quot; dst_path = &quot;/tmp/passwd&quot; # 如何复制? # 调用已有模块中的方法 # - 很推荐,简单粗暴不动脑 # - 直接使用 file_copy.py的方法即可 # 导入方法一:直接导入模块 import file_copy # 要注意路径问题 file_copy.copy(src_path, dst_path) # 导入方法二:只导入 file_copy 模块的 copy 方法 from file_copy import copy # 如果相同时导入多个模块 from file_copy import * copy(src_path, dst_path) # 导入方法四:导入模块起别名 as import file_copy as fc fc.copy(src_path, dst_path)</pre><div class="contentsignin">Copy after login</div></div><p><strong>常用的导入模块的方法 </strong></p><ul class=" list-paddingleft-2"><li><p>一行指导入一个模块,可以导入多行, 例如:<code>import random

  • 只导入模块中的某些方法,例如:from random import choice, randint

模块加载 (load)
  • 一个模块只被 加载一次,无论它被导入多少次

  • 只加载一次可以 阻止多重导入时,代码被多次执行

  • 如果两个文件相互导入,防止了无限的相互加载

  • 模块加载时,顶层代码会自动执行,所以只将函数放入模块的顶层是最好的编程习惯

模块特性及案例
模块特性

模块在被导入时,会先完整的执行一次模块中的 所有程序

案例

# foo.py
print(__name__)
 
# bar.py
import foo  # 导入foo.py,会将 foo.py 中的代码完成的执行一次,所以会执行 foo 中的 print(__name__)
Copy after login

结果:

# foo.py -> __main__ 当模块文件直接执行时,__name__的值为‘__main__’
# bar.py -> foo 当模块被另一个文件导入时,__name__的值就是该模块的名字

How to create and call functions in Python

所以我们以后在 Python 模块中执行代码的标准格式:

def test():
    ......
if __name__ == "__main__":
    test()
Copy after login

The above is the detailed content of How to create and call functions in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles