day5 函数

 
1.求全部元素的和 [1,2,1,2,3,3,3,3] 遍历
a = [1,2,1,2,3,3,3,3]
sum = 0
n = len(a)-1
while n>=0:
sum += a[n]
n -= 1
2.求偶数元素的和 [1,2,1,2,3,3,3,3]
a = [1,2,1,2,3,3,3,3]
b = []
for i in a:
if i//2 == 0:
b.append(i)
sum = 0
n = len(b)-1
while n>=0:
sum+=b[n]
n-=1
 
3.统计所有数字出现的个数 [1,2,1,2,3,3,3,3] 字典
a = [1,2,1,2,3,3,3,3]
d = {}
for i in a:
d[i]=0
len(d)
4.生成随机的10位小写字母:
import random
[chr(ord('a')+random.randint(1,25)) for i in range(10)]
5.生成随机的10位小写字母:
[chr(ord('A')+random.randint(1,25)) for i in range(10)]
6.生成随机不限定固定大小写个数的10个字母:
lower_num = random.randint(0,10)
uper_num = 10-lower_num
q = []
for i in range(lower_num):
... q.append(chr(ord('a')+random.randint(1,25)))
for m in range(uper_num):
... q.extend(chr(ord('A')+random.randint(1,25)))
...
>>> q
['z', 'g', 'o', 'h', 'c', 'x', 'p', 'u', 'p', 'N']
 
函数
判断小写字母的个数
def count_letter(s):
result = 0
for i in s:
if i >='a' and i <= 'z':
result += 1
return result
判断字符串里面数字的个数
>>> def count_num(s):
... result = 0
... for i in s:
... if i.isdigit():
... result += 1
... return result
def count_letter(s):
result = 0
for i in s:
if i >='0' and i <= '9':
result += 1
return result
 
字符串判断方法:s.isdigit() 判断字符串是否为数字,如果是,返回true
s.isalpha() 判断字符串是否为字母,如果是,返回true
s.isalnum() 判断是否数字和字母的组合,如果是,返回true
 
def add(a,b):
if isinstance(a,(int,float,complex)) and isinstance(b,(int,float,complex)):
return a+b
return None
print(add(1.1,3))
n = 1
def func():
n = 2
return n
print(func())
print(n)
局部变量在函数里面有效,出了函数就没用,函数外面的是全局变量
当函数被定义的时候,删除无效,需要从写函数
内置函数覆盖后,可以删除,无需重写
 
def add(a,b):
return a+b
print(add(1))
Traceback (most recent call last):
File "test.py", line 4, in <module>
print(add(1))
TypeError: add() missing 1 required positional argument: 'b'
参数必须一一对应
def add(a,b=1):
return a+b
print(add(1))
默认值参数,关于参数格式:函数在赋值参数的时候,应该按照顺序给定参数,如果不按顺序,应该给出变量名然后参数;默认参数应该在最后面,后面不能有非默认值
return 可以返回多个值,tuple类型
当函数里有变量没定义时,会找函数外面的变量
n = 1
def func():
return n+1
 
n = 1
def func(n):
n+=1
return n+1
print(func(n))
 
n = []
def func(a):
a.append(1)
return a
print(func(n))
如果函数传入可变类型(list,set,dict)参数,函数内部的操作都会影响传入类型的结果
如果函数传入不可变类型(str,int,float),函数内部操作不会影响传入参数的外部结果
 
可变参数:
def add(a,b,*c):
print(type(c))
print(c)
add(1,2,3,4,5,6,78)
*c 不限制传入参数数量,以tuple形式传入
练习:求总和并返回
def add(a,b,*c):
print(type(c))
print(c)
add(1,2,3,4,5,6,78)
def add(a,b,*c):
sum = 0
for i in c:
sum+=i
return sum+a+b
print(add(1,2,3,4,5,6,78))
 
def add(a,b,**c):
return a,b,c
print(add(1,2,f=3,q=4,w=5,e=6,r=78))
def add(a,b,**c):
result = a+b
for v in c.values():
result+=v
return result
print(add(1,2,f=3,q=4,w=5,e=6,r=78))
def add(a,b,*c,**d):
result = a+b
for i in c:
result += i
for v in d.values():
result+=v
return result
print(add(1,2,2,4,5,f=3,q=4,w=5,e=6,r=78))
关于*和**:* 一般用于存放tuple,**存放字典格式的,*要放在**前面

posted @ 2019-12-23 08:13  绝世老中医  阅读(225)  评论(0编辑  收藏  举报