Python自学入门(一):环境安装
Python自学入门(二):数据类型和运算符
Python自学入门(三):数据类型详解
Python自学入门(四):流程控制
四、函数和模块
4.1 函数
函数是可重复利用的一段代码块。
#没有返回值的函数
def printHello():
print("hello python")
#调用函数
printHello()
#有返回值的函数
def getSchool():
return "PKU"
#调用函数
name=getSchool()
print(name)
#带参数的函数
def getMax(a,b):
print('接收的参数:a=',a,';b=',b)
if a>b:
return a
else:
return b
#调用函数,按顺序传入参数
getMax(10,40)
#关键字参数
getMax(b=10,a=5)
#会报错,因为参数个数不对
getMax(10)
#默认参数,要在必须参数之后
def info(age,name='无名氏'):
print(name,age)
#调用函数
info(13,'tom')
info(10)
info(age=10,name='jack')
#不定长参数用*修饰,相当于一个元组,调用函数时不能再使用关键字参数
def test1(name,*vars):
print(name,vars)
#调用函数
test1('a',1,2,3)
#相当于字典
def test2(**vars):
print(vars)
#调用函数
test2(a=1,b=2,c=3)
参数的类型有可变类型和不可变类型,Python3 的六个标准数据类型中:
- **不可变数据:**Number(数字)、String(字符串)、Tuple(元组)
- **可变数据:**List(列表)、Set(集合)、Dictionary(字典)
不可变类型,在函数中的改变不会影响到原来的形参。而可变类型,在函数中的改变会影响原来的形参,形参指向的是同一对象。
def test3(num,ls):
num=1;
#ls=[] #新的地址
ls.append(0)
#调用函数
num=2 #不可变
ls=[1,2,3] #可变
test3(num,ls)
print(num) #不变
print(ls) #改变
4.2 模块
模块是封装好的一些py文件,文件中定义了函数和变量。使用import可以引入模块。
#创建一个my_test.py文件,输入如下内容
def test_print1():
print('hello python 1')
def test_print2():
print('hello python 2')
#在另一个文件中导入模块
import my_test
my_test.test_print1()
#可以把函数赋值给一个本地变量,注意末尾没括号
mt=my_test.test_print1
mt()
my_test.test_print2()
#引入模块中的部分函数,多个函数用逗号隔开
from my_test import test_print1
test_print1()
#test_print2() #报错
from my_test import test_print2 as tp2 #定义别名
tp2() #使用别名,原名称不能使用