函数是组织好、可重复使用,用来实现单一或相关联功能的代码段。
函数能够提高应用的模块化和代码的重复利用率。Python提供了许多内建函数,如print()、int()、float()等等。
用户也可以自己创建函数,这样的函数称为用户自定义函数。
######
例子一:
#coding=utf-8
def func1(): #自定义函数
print('Welcome to zhuohua.') #函数的操作
if __name__ == '__main__':
func1() #执行一次函数func1()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
Welcome to zhuohua.
######
例子二:
#coding=utf-8
def func1(Key_1): #自定义函数,加上了一个变量Key_1
print('Welcome to',Key_1)
if __name__ == '__main__':
func1("zhuohua.") #按参数顺序传入参数后,执行一次func1()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
Welcome to zhuohua.
######
例子三:
#coding=utf-8
def func1(Name_1,Age_1): #自定义函数,加上了两个变量Name_1、Age_1
print("姓名:",Name_1)
print("年龄:",Age_1)
if __name__ == '__main__':
func1('zhuohua',18) #按参数顺序传入参数后,执行一次func1()
Name_1 = 'Mary'
Age_1 = 25
func1(Name_1,Age_1) #按参数顺序传入参数后,执行一次func1()
Name_1 = "Lily"
Age_1 = 42
func1(Name_1,Age_1) #按参数顺序传入参数后,执行一次func1()
print("-" * 10)
func1(Name_1='Python',Age_1=28) #指定参数名传入参数后,执行一次func1()
func1(Age_1=38,Name_1='Tom') #指定参数名传入参数后,执行一次func1()
脚本运行的结果:(函数func1()一共被执行了五次)
C:\Users\jacky\Desktop>python xx.py
姓名: zhuohua
年龄: 18
姓名: Mary
年龄: 25
姓名: Lily
年龄: 42
----------
姓名: Python
年龄: 28
姓名: Tom
年龄: 38
######
例子四:
#coding=utf-8
def func1():
Key_1 = 1
return Key_1 #这种方法不用return的话,返回结果为None
def func2():
#局部变量Key_2使用了func1()return出来的一个变量Key_1的值
Key_2 = func1()
print(Key_2)
if __name__ == '__main__':
#这种方法需要依次执行func1()、func2()
func1()
func2()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
1
######
例子五:
#coding=utf-8
def func1():
Key_1 = 1
Key_2 = 2
return Key_1,Key_2
def func2():
#局部变量a_1、a_2分别使用了func1()return出来的两个变量Key_1、Key_2的值
a_1 = func1()[0]
a_2 = func1()[1]
print(a_1)
print(a_2)
if __name__ == '__main__':
#这种方法需要依次执行func1()、func2()
func1()
func2()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
1
2
######
例子六:
#coding=utf-8
def func1():
Key_1 = "zhuohua"
Key_2 = 'Python'
Key_3 = 168
return Key_1,Key_2,Key_3
if __name__ == '__main__':
Key_1,Key_2,Key_3 = func1()
print(Key_2)
print(Key_1,Key_3)
print(f"今年{Key_1}{Key_3}。")
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
Python
zhuohua 168
今年zhuohua168。
######
例子七:
#coding=utf-8
Key_1 = input("请输入一个1到3之间的整数:")
def func1():
a='Welcome to zhuohua.'
print(a)
def func2():
Path_1 = "./test2.txt" #在脚本所在目录里创建一个名为test2.txt的文件
f_name = open(Path_1,'w')
f_name.close()
print('创建文件test2.txt')
def func3():
Path_1 = "../test3.txt" #在脚本所在目录的上一级目录里创建一个名为test3.txt的文件
f_name = open(Path_1,'w')
f_name.close()
print('创建文件test3.txt')
if __name__ == '__main__':
if int(Key_1)==1:
func1()
elif int(Key_1) == 2:
func2()
elif int(Key_1) == 3:
func3()
多次运行脚本的结果:
C:\Users\jacky\Desktop>python xx.py
请输入一个1到3之间的整数:1
Welcome to zhuohua.
C:\Users\jacky\Desktop>python xx.py
请输入一个1到3之间的整数:2
创建文件test2.txt
C:\Users\jacky\Desktop>python xx.py
请输入一个1到3之间的整数:3
创建文件test3.txt
笺注:
只有输入了整数'2'再按回车键,func2()才会创建一个名为test2.txt的文件
只有输入了整数'3'再按回车键,func3()才会创建一个名为test3.txt的文件
假如脚本xx.py是在桌面,那么文件test2.txt就生成到目录C:\Users\jacky\Desktop
假如脚本xx.py是在桌面,那么文件test3.txt就生成到目录C:\Users\jacky
######
例子八:
#coding=utf-8
def func1():
Path_1 = "D:/Python3/share/a.txt" #在目录D:\Python3\share里创建一个名为a.txt的文件
f_name = open(Path_1,'w')
f_name.close()
print('创建文件a.txt')
def func2():
Path_1 = "./b.txt"
f_name = open(Path_1,'w')
f_name.close()
print('创建文件b.txt')
def func3():
Path_1 = "../c.txt"
f_name = open(Path_1,'w')
f_name.close()
print('创建文件b.txt')
if __name__ == '__main__':
func1()
func2()
func3()
脚本运行的结果:(脚本运行后,依次创建文件a.txt、文件b.txt、文件c.txt)
C:\Users\jacky\Desktop>python xx.py
创建文件a.txt
创建文件b.txt
创建文件b.txt
######使用函数进行科学计算(一)
#coding=utf-8
def func1():
Key_1 = 22
Key_2 = 66
Result_0 = Key_1 + Key_2
return Result_0 #这种方法不用return的话,返回结果为None
if __name__ == '__main__':
Result_1 = func1() #全局变量Result_1使用了func1()return出来的一个变量Result_0的值
print(Result_1)
print(type(Result_1))
print(f"计算结果为 {Result_1}")
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
88
<class 'int'>
计算结果为 88
######使用函数进行科学计算(二)
#coding=utf-8
def func1(Key_1,Key_2):
Result_0 = Key_1 + Key_2
return Result_0
if __name__ == '__main__':
#多次按参数顺序传入参数后,多次执行func1()
Result_1 = func1(1,2)
print(Result_1)
Result_1 = func1(3,4)
print(Result_1)
Result_1 = func1(5,6)
print(Result_1)
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
3
7
11
######使用函数进行科学计算(三)
#coding=utf-8
def func1():
i_1 = 2
i_2 = 16
j_1 = 5
j_2 = 45
Key_1 = i_1 + i_2
Key_2 = j_1 + j_2
return Key_1,Key_2
def func2():
a_1 = func1()[0]
a_2 = func1()[1]
Result_1 = a_1 - a_2
print(Result_1)
print(type(Result_1))
print(f"计算结果为 {Result_1}")
if __name__ == '__main__':
func1()
func2()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
-32
<class 'int'>
计算结果为 -32
######使用函数进行科学计算(四)
#coding=utf-8
def func1():
Key_1 = 1
#func2()调用了func1()的一个变量Key_1,并且func2()会自动执行
func2(Key_1)
def func2(Key_1):
Key_2 = Key_1 + 2
print(Key_2)
if __name__ == '__main__':
func1()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
3
######使用函数进行科学计算(五)
#coding=utf-8
def func1():
Key_1 = 1
Key_2 = 2
Key_3 = Key_1 + Key_2
#func2()调用了func1()的两个变量Key_1、Key_3,并且func2()会自动执行
func2(Key_1,Key_3)
def func2(Key_1,Key_3):
Result_1 = Key_1 + Key_3 + 4
print(Key_1)
print(Key_3)
print(Result_1)
if __name__ == '__main__':
func1()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
1
3
8
######使用函数进行科学计算(六)
#coding=utf-8
Key_1 = int(input("请输入变量Key_1的值:"))
Key_2 = int(input("请输入变量Key_2的值:"))
Key_3 = int(input("请输入变量Key_3的值:"))
Key_4 = int(input("请输入变量Key_4的值:"))
def func1():
Result_1 = Key_1 / ((Key_2 + Key_3) * Key_4)
print("-" * 10)
print(f"计算结果: {Result_1}")
print(f"计算结果的数据类型:{type(Result_1)}")
print("-" * 10)
Result_2 = "%.3f" % Result_1 #保留三位小数
print("计算结果保留三位小数:",Result_2)
print("计算结果保留三位小数后的数据类型:",type(Result_2))
print("-" * 10)
Result_3 = float(Result_2) #字符串转换为浮点数
print("计算结果从字符串转换为浮点数:",Result_3)
print("计算结果从字符串转换为浮点数后的数据类型:",type(Result_3))
print("-" * 10)
Result_4 = int(Result_3) #浮点数转换为整数;直接截取整数部分,不是四舍五入
print("计算结果从浮点数转换为整数:",Result_4)
print("计算结果从浮点数转换为整数后的数据类型:",type(Result_4))
if __name__ == '__main__':
func1()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
请输入变量Key_1的值:80
请输入变量Key_2的值:1
请输入变量Key_3的值:2
请输入变量Key_4的值:-3
----------
计算结果: -8.88888888888889
计算结果的数据类型:<class 'float'>
----------
计算结果保留三位小数: -8.889
计算结果保留三位小数后的数据类型: <class 'str'>
----------
计算结果从字符串转换为浮点数: -8.889
计算结果从字符串转换为浮点数后的数据类型: <class 'float'>
----------
计算结果从浮点数转换为整数: -8
计算结果从浮点数转换为整数后的数据类型: <class 'int'>
######使用函数进行科学计算(七)
#coding=utf-8
def func1(Key_1,Key_2,Key_3,Key_4):
Result_0 = Key_1 / ((Key_2 + Key_3) * Key_4)
return Result_0
def func2():
print("-" * 10)
print(Result_1)
print(type(Result_1))
print("-" * 10)
Result_2 = "%.2f" % Result_1 #保留两位小数
print(Result_2)
print(type(Result_2))
print("-" * 10)
Result_3 = int(float(Result_2)) #不可以直接将有小数点的字符串取整数部分,要先转换为浮点数
print(Result_3)
print(type(Result_3))
if __name__ == '__main__':
Key_1 = int(input("请输入变量Key_1的值:"))
Key_2 = int(input("请输入变量Key_2的值:"))
Key_3 = int(input("请输入变量Key_3的值:"))
Key_4 = int(input("请输入变量Key_4的值:"))
Result_1 = func1(Key_1,Key_2,Key_3,Key_4) #Result_1为全局变量
func2() #func2()可以直接使用全局变量Result_1
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
请输入变量Key_1的值:80
请输入变量Key_2的值:1
请输入变量Key_3的值:2
请输入变量Key_4的值:-3
----------
-8.88888888888889
<class 'float'>
----------
-8.89
<class 'str'>
----------
-8
<class 'int'>
######使用函数进行科学计算(八)
#coding=utf-8
def func1(Key_1,Key_2,Key_3,Key_4):
global Result_0 #使用关键字global,把Result_0从局部变量变为全局变量
Result_0 = Key_1 / ((Key_2 + Key_3) * Key_4)
def func2():
print("-" * 10)
print(Result_0)
print(type(Result_0))
print("-" * 10)
Result_1 = "%.1f" % Result_0 #保留一位小数
print(Result_1)
print(type(Result_1))
print("-" * 10)
Result_2 = int(float(Result_1))
print(Result_2)
print(type(Result_2))
if __name__ == '__main__':
Key_1 = int(input("请输入变量Key_1的值:"))
Key_2 = int(input("请输入变量Key_2的值:"))
Key_3 = int(input("请输入变量Key_3的值:"))
Key_4 = int(input("请输入变量Key_4的值:"))
func1(Key_1,Key_2,Key_3,Key_4)
func2() #func2()可以直接使用全局变量Result_0
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
请输入变量Key_1的值:80
请输入变量Key_2的值:1
请输入变量Key_3的值:2
请输入变量Key_4的值:-3
----------
-8.88888888888889
<class 'float'>
----------
-8.9
<class 'str'>
----------
-8
<class 'int'>
######循环使用函数(一)
#coding=utf-8
def func1(): #自定义函数
global Key_1
print("##### Welcome to zhuohua. #####")
print("1: Install Apache")
print("2: Install MySQL")
print("3: Install PHP")
print("###")
Key_1 = int(input("Enter your choice (1, 2, 3, 4): "))
if __name__ == '__main__':
func1() #先执行一次函数func1()
if Key_1 == 1:
print("Installing Apache...")
print("Install Apache completed,enjoy it!")
print("")
func1() #再执行一次函数func1()
if Key_1 == 2:
print("Installing MySQL...")
print("Install MySQL completed,enjoy it!")
print("")
print("")
func1() #再执行一次函数func1()
if Key_1 == 3:
print("Installing PHP...")
print("Install PHP completed,enjoy it!")
print("")
print("")
func1() #再执行一次函数func1()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
##### Welcome to zhuohua. #####
1: Install Apache
2: Install MySQL
3: Install PHP
###
Enter your choice (1, 2, 3, 4): 1
Installing Apache...
Install Apache completed,enjoy it!
##### Welcome to zhuohua. #####
1: Install Apache
2: Install MySQL
3: Install PHP
###
Enter your choice (1, 2, 3, 4): 2
Installing MySQL...
Install MySQL completed,enjoy it!
##### Welcome to zhuohua. #####
1: Install Apache
2: Install MySQL
3: Install PHP
###
Enter your choice (1, 2, 3, 4): 3
Installing PHP...
Install PHP completed,enjoy it!
##### Welcome to zhuohua. #####
1: Install Apache
2: Install MySQL
3: Install PHP
###
Enter your choice (1, 2, 3, 4): 4
C:\Users\jacky\Desktop>
######循环使用函数(二)
#coding=utf-8
import sys
def func1(): #自定义函数
global Key_1
print("##### Install Apache #####")
print("1: Install Apache2.2")
print("2: Install Apache2.4")
print("q: Exit current script")
print("###")
Key_1 = input("Enter your choice (1, 2, q): ")
if Key_1 == "1":
print("You will install Apache2.2")
elif Key_1 == "2":
print("You will install Apache2.4")
elif Key_1 == "q":
sys.exit() #终止脚本的运行
func2() #执行一次函数func2()
def func2(): #自定义函数
global Key_2
print("##### Install MySQL #####")
print("1: Install MySQL5.5")
print("2: Install MySQL5.6")
print("3: Install MySQL5.7")
print("q: Exit current script")
print("###")
Key_2 = input("Enter your choice (1, 2, 3, q): ")
if Key_2 == "q":
sys.exit() #终止脚本的运行
func3() #执行一次函数func3()
def func3(): #自定义函数
global Key_3
print("##### Install PHP #####")
print("1: Install PHP5.6")
print("2: Install PHP7.0")
print("3: Install PHP7.1")
print("4: Install PHP7.2")
print("q: Exit current script")
print("###")
Key_3 = input("Enter your choice (1, 2, 3, 4, q): ")
if Key_3 == "q":
sys.exit() #终止脚本的运行
def func4(): #自定义函数
print("")
print("Installing Apache2.4...")
print("Install Apache2.4 completed,enjoy it!")
print("Installing MySQL5.6...")
print("Install MySQL5.6 completed,enjoy it!")
print("Installing PHP7.2...")
print("Install PHP7.2 completed,enjoy it!")
print("")
if __name__ == '__main__':
func1() #先执行一次函数func1()
if Key_1 == "1" and Key_2 == "1" and Key_3 == "1":
print("")
print("Installing Apache2.2...")
print("Install Apache2.2 completed,enjoy it!")
print("Installing MySQL5.5...")
print("Install MySQL5.5 completed,enjoy it!")
print("Installing PHP5.6...")
print("Install PHP5.6 completed,enjoy it!")
print("")
elif Key_1 == "2" and Key_2 == "1" and Key_3 == "1":
print("")
print("Installing Apache2.4...")
print("Install Apache2.4 completed,enjoy it!")
print("Installing MySQL5.5...")
print("Install MySQL5.5 completed,enjoy it!")
print("Installing PHP5.6...")
print("Install PHP5.6 completed,enjoy it!")
print("")
elif Key_1 == "2" and Key_2 == "2" and Key_3 == "4":
func4() #执行一次函数func4()
脚本运行的结果:
C:\Users\jacky\Desktop>python xx.py
##### Install Apache #####
1: Install Apache2.2
2: Install Apache2.4
q: Exit current script
###
Enter your choice (1, 2, q): 1
You will install Apache2.2
##### Install MySQL #####
1: Install MySQL5.5
2: Install MySQL5.6
3: Install MySQL5.7
q: Exit current script
###
Enter your choice (1, 2, 3, q): 1
##### Install PHP #####
1: Install PHP5.6
2: Install PHP7.0
3: Install PHP7.1
4: Install PHP7.2
q: Exit current script
###
Enter your choice (1, 2, 3, 4, q): 1
Installing Apache2.2...
Install Apache2.2 completed,enjoy it!
Installing MySQL5.5...
Install MySQL5.5 completed,enjoy it!
Installing PHP5.6...
Install PHP5.6 completed,enjoy it!
C:\Users\jacky\Desktop>
###
C:\Users\jacky\Desktop>python xx.py
##### Install Apache #####
1: Install Apache2.2
2: Install Apache2.4
q: Exit current script
###
Enter your choice (1, 2, q): 2
You will install Apache2.4
##### Install MySQL #####
1: Install MySQL5.5
2: Install MySQL5.6
3: Install MySQL5.7
q: Exit current script
###
Enter your choice (1, 2, 3, q): 1
##### Install PHP #####
1: Install PHP5.6
2: Install PHP7.0
3: Install PHP7.1
4: Install PHP7.2
q: Exit current script
###
Enter your choice (1, 2, 3, 4, q): 1
Installing Apache2.4...
Install Apache2.4 completed,enjoy it!
Installing MySQL5.5...
Install MySQL5.5 completed,enjoy it!
Installing PHP5.6...
Install PHP5.6 completed,enjoy it!
C:\Users\jacky\Desktop>
相关文章:
全局变量和局部变量
自定义类
datetime模块
replace()函数
Python3命令集
Python3调用另外一个脚本的函数/类
Python3检测文件内容中是否包含关键字
文件操作(创建、读取、写入、追加)
try语句
字典
匿名函数
Pandas的进阶(一)
Pandas的进阶(三)
CentOS6使用Socket(检测TCP端口)
CentOS8使用Socket(检测TCP端口)
Windows使用tcping+任务计划
Python3使用多线程/线程锁
Python3制作音乐播放器
Python3脚本管理Linux下的MySQL
Linux使用内置模块ftplib
网络爬虫_爬(blog.zhuohua.store)
网络爬虫_爬(电影天堂)
Shell脚本中的函数 |