Python中的函数

Python内置数据结构总结
数值类型:
bool
str
list tuple set dict

可变数据类型 不可变数据类型
可变数据类型:list set dict(是否可以增删改查)

有序数据类型和无序数据类型
有序:str list tuple
无序:数值 bool set
python2:dict无序 python3中:dict有序

一般情况下:有序数据类型可以索引,切片,连接,重复 但是字典除外

可以for循环数据结构
函数的理解和定义
范例:
def print(self, *args, sep=’ ‘, end=’\n’, file=None):
def min(*args, key=None):

def 函数名():
函数体
定义一个函数,在没有调用函数的情况下,函数是不会被执行的
def hello():
print(‘hello’)
print(‘hello’)

调用函数
hello()

函数里面嵌套函数
def fentiao():
print(‘is fentiao…’)
def westos():
print(‘westos’)
westos()

fentiao()

def func1(a):
name = ‘westos’#定义函数时的变量称为形式参数,变量名可以任意起
print(‘hello %s’ %(a))

调用函数时的参数称为实参,该参数必须是实际存在的
func1(12)
func1(‘linux’)
func1(‘python’)

函数动态添加成员
def fun():
print(fun.x)
fun()

动态添加
fun.x = 3
fun()

动态删除
del fun.x
fun()

函数的返回值
函数调用时一般有返回值,没有定义返回值的时候,python中默认返回None
def hello():
print(‘hello’)

res = hello()
print(res)

def hello():
return 返回的表达式或者变量
return ‘hello’

res = hello()
print(res)

多个返回值

def fun(a):
#
接收一个列表,求这个列表的最大值,平均值,最小值
max_num = max(a)
min_num = min(a)
avg_num = sum(a)/len(a)
python函数中,只能返回一个值
如果非要返回多个值,会把返回的值封装为一个元组数据类型
return max_num,min_num,avg_num

variables = fun([34,1,2,3,4,5,6,7,421])
print(variables,type(variables))

函数形参之四大参数类型
参数:形参 实参
形参的分类:位置参数 默认参数 可变参数 关键字参数

位置参数:形参和实参必须保持一致
def getInfo(name, age): # 按照位置传递参数
print(name, age)
getInfo(age=18, name=‘name’)

默认参数:形参和实参可以不一致
def mypow(x,y=2):
“”"
求x的y次方
:param x:
:param y:
:return:
“”"
print(x**y)
mypow(4)
mypow(4,3)

函数的作用域
作用域
局部作用域
全局作用域

全局作用域:作用于整个程序
num = 10
print(‘out fun: id=’,id(num))

def fun():
局部作用域,在函数运行时生效,函数运行结束则释放
num =2
print(‘in fun:id=’,id(num))
print(‘in fun:num = %s’ %(num))

fun()
print(‘out fun: num=%s’ %(num))

num = 10

def fun():
通过global关键字声明局部变量为全局变量
函数执行完毕,变量依然生效
global num
num = 2
fun()

print(num)

参数检测
列表生成式
需求1:
1.接收变量k,a,b
s = ‘51 5000 10000’
li = []
for item in s.split():
li.append(int(item))
k,a,b = li
print(k,a,b)
li=[int(item) for item in s.split()]
print(li)
print(k,a,b)

需求2:生成一个列表,列表元素分别为[11,22,33,44…n*n]
li = []
for i in range(1,8):
li.append(i**i)
print(li)

li = [i**i for i in range(1,8)]
print(li)
列表生成式变形之for循环嵌套
需求:讲3x3的矩阵转换成一堆数组
[
[1,2,3],
[4,5,6],
[7,8,9]
]
[1,2,3,4,5,6,7,8,9]
“”"
li = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
resLi = []
for item1 in li: # [1,2,3] [4,5,6] [7,8,9]
for item2 in item1:
if item2 % 2 == 0:
resLi.append(item2)
print(resLi)

print([item2 for item1 in li for item2 in item1])

from itertools import chain
print(list(chain(*li)))
字典生成式
需求1:假设有20个学生,学生分数在60~100之间,筛选出成绩在90分以上的学生
import random

stuInfo={}
for i in range(20):
name = ‘westos’ + str(i)
score = random.randint(60,100)
stuInfo[name] = score
print(stuInfo)
stuInfo = {‘westos’+ str(i):random.randint(60,100) for
i in range(20)}

highscore = {}
for name,score in stuInfo.items():
if score > 90:
highscore[name] = score
print(highscore)

print({name:score for name,score in stuInfo.items() if score > 90})

需求2:将所有的key值变为大写
d = dict(a=1,b=2)
new_d = {}
for i in d:
new_d[i.upper()] = d[i]
print(‘key转化为大写的字典:’,new_d)

print({k.upper():v for k,v in d.items()})

需求3:大小写key值合并,统一以小写输出
d = dict(a=2, b=1, c=2, B=9, A=10)
print({k.lower(): d.get(k.lower(), 0) + d.get(k.upper(), 0) for k in d})
for k, v in d.items():
low_k = k.lower()
if low_k not in new_d: new_d[low_k] = v
else:
new_d[low_k] += v

print(new_d)

集合生成式
print({i ** 2 for i in {1, 2, 3}})
print({i ** 2 for i in {1, 2, 3, 9, 12} if i % 3 == 0})
生成器

使用send唤醒程序
使用send()函数来唤醒程序执行,使用send()函数的好处是
可以在唤醒的同时向断点中传入一个附加的数据

def create_num(all_num):
a,b = 0,1
current_num = 0
while current_num < all_num:
ret = yield a
print(’>>>>>>>>ret>>>>>>>’,ret)
a,b = b,a+b
current_num += 1

obj = create_num(100)
red = next(obj)
print(red)
red = obj.send(None)
print(red)

next和send得到的都是yield后面的值
不同的是send传递值而next不传递值

注意:
不能把send放在第一个,因为第一次执行程序是从开始执行
并没有值来接收send
如果你非要把send放在第一个,那么传递的值应该是None

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值