Function is created with def
statement, the syntax is as follows:
def 函数名(参数列表): # 具体情况具体对待,参数可有可无 """函数说明文档字符串""" 函数封装的代码 ……
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("甩干")
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:
Case: Add washing powder
def washing_machine(): # 洗衣机可以帮我们完成 print("打水") print("加洗衣粉!!!") print("洗衣服") print("甩干") # 早上洗衣服 washing_machine() # 中午洗衣服 washing_machine() # 晚上洗衣服 washing_machine()
Summary
Thinking
function call above the function definition?
using the function name to call the function, you must ensure that Python already knows the existence of the function
NameError: name 'menu' is not defined (
Name error: the name menu is not defined)
:When defining the function , the parameters in parentheses are used to receive parameters. is used as a variable inside the function
:When calling a function, the parameters in parentheses are used to pass data to the inside of the function
When we want to wash other things, we need to manually change the code inside the method:
def washing_machine(): # 洗衣机可以帮我们完成 print("打水") print("加洗衣粉!!!") print("洗床单") # 洗被套 print("甩干")
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() ......
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
to separate the parameters
def washing_machine(something): # 洗衣机可以帮我们完成 print("打水") print("加洗衣粉!!!") print("洗" + something) print("甩干") # 洗衣服 washing_machine("衣服") # 洗床单 washing_machine("床单")
def washing_machine(xidiji,something): # 洗衣机可以帮我们完成 print("打水") print("加" + xidiji) print("洗衣服" + something) print("甩干") #早上洗衣服 #按照参数位置顺序传递参数的方式叫做位置传参 #使用洗衣机,执行洗衣机内部的逻辑 washing_machine("洗衣液","衣服")#something = 衣服 #中午洗被罩 washing_machine("洗衣粉","被罩")# something = 被罩 #晚上洗床单 washing_machine("五粮液","床单")# something = 床单
The
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
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
Default parameters
. 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
so that the caller can perform subsequent processing on the specific result
is the function that completes the work After , finally gives the caller's a result
keyword can be used in the function Return results</li><li><p>调用函数一方,可以 <strong>使用变量</strong> 来 <strong>接收</strong> 函数的返回结果</p></li></ul><h5>案例:计算任意两个数字的和</h5><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:py;"># 函数的返回值: 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("return表示函数的终止,return后的代码都不会执行")
# 将函数return后的结果赋值给变量dc: dc = sum -> dc = 30
dc = get_sum(10, 20) # x = 10, y = 20
print("dc:", dc) # 30
dc1 = get_sum(10) # x = 10, y = 100
print("dc1:", dc1) # 110
# if dc % 2 == 0:
# print("偶数")
# else:
# print("奇数")</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:py;">#默认参数
#注意:具有默认值的参数后面不能跟没有默认值的参数
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("dc:",dc) # 6
dc1 = get_sum(1,2) # a=1 b=2 c=10
print("dc1:",dc1) # 13
dc2 = get_sum(1) # a=1 b=5 c=10
print("dc2:",dc2) # 16
dc3 = get_sum()
print("dc3:",dc3) # 35</pre><div class="contentsignin">Copy after login</div></div><p><img src="https://img.php.cn/upload/article/000/887/227/168455598911182.jpg" 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:py;">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("dc:",dc)
print("dc1:",dc1)</pre><div class="contentsignin">Copy after login</div></div><p><img src="https://img.php.cn/upload/article/000/887/227/168455598947497.jpg" 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:py;">#练习:生成随机密码
#创建 randpass.py 脚本,要求如下:
#编写一个能生成8位随机密码的程序
#使用 random 的 choice 函数随机取出字符
#由用户决定密码长度
import random
def new_password():
n = int(input("密码长度:"))
password = ""
all = "0123456789zxcvbnmlkjhgfdsaqwertyuiopPOIUYTREWQASDFGHJKLMNBVCXZ" # 0-9 a-z A-Z
random.choice(all)
for i in range(n):
dc = random.choice(all)
password += dc
# print("passwd:",password)
return password
# 调用函数,才能执行函数内部逻辑
dc = new_password()
print("dc:",dc)</pre><div class="contentsignin">Copy after login</div></div><p><img src="https://img.php.cn/upload/article/000/887/227/168455598971596.jpg" alt="How to create and call functions in Python" /></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:py;">#练习:生成随机密码
#创建 randpass.py 脚本,要求如下:
#编写一个能生成8位随机密码的程序
#使用 random 的 choice 函数随机取出字符
#由用户决定密码长度
import random,string
def new_password():
n = int(input("密码长度:"))
password = ""
all = string.ascii_letters + string.digits
random.choice(all)
for i in range(n):
dc = random.choice(all)
password += dc
# print("passwd:",password)
return password
# 调用函数,才能执行函数内部逻辑
dc = new_password()
print("dc:",dc)</pre><div class="contentsignin">Copy after login</div></div><p><img src="https://img.php.cn/upload/article/000/887/227/168455598921688.jpg" alt="How to create and call functions in Python" /></p><h4>模块基础</h4><h5>定义模块</h5><h6>基本概念</h6><ul class=" list-paddingleft-2"><li><p>模块是从逻辑上组织python代码的形式</p></li><li><p>当代码量变得相当大的时候,最好把代码分成一些有组织的代码段,前提是保证它们的 <strong>彼此交互</strong></p></li><li><p>这些代码片段相互间有一定的联系,可能是一个包含数据成员和方法的类,也可能是一组相关但彼此独立的操作函数</p></li></ul><h5>导入模块 (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="https://img.php.cn/upload/article/000/887/227/168455598942924.jpg" 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:py;"># test.py,将 file_copy.py 放在同级目录下
# 需求:要将/etc/passwd复制到/tmp/passwd
src_path = "/etc/passwd"
dst_path = "/tmp/passwd"
# 如何复制?
# 调用已有模块中的方法
# - 很推荐,简单粗暴不动脑
# - 直接使用 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
一个模块只被 加载一次,无论它被导入多少次
只加载一次可以 阻止多重导入时,代码被多次执行
如果两个文件相互导入,防止了无限的相互加载
模块加载时,顶层代码会自动执行,所以只将函数放入模块的顶层是最好的编程习惯
模块在被导入时,会先完整的执行一次模块中的 所有程序
案例
# foo.py print(__name__) # bar.py import foo # 导入foo.py,会将 foo.py 中的代码完成的执行一次,所以会执行 foo 中的 print(__name__)
结果:
# foo.py -> __main__ 当模块文件直接执行时,__name__的值为‘__main__’
# bar.py -> foo 当模块被另一个文件导入时,__name__的值就是该模块的名字
所以我们以后在 Python 模块中执行代码的标准格式:
def test(): ...... if __name__ == "__main__": test()
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!