Unit5 函数
1、函数的参数
1.1、位置参数的使用
def happy_birthday(name,age):
print("祝" + name + str(age) + "岁生日快乐")
#调用
happy_birthday("小明", 18)
1.2、关键字传参
def happy_birthday(name,age):
print("祝" + name + str(age) + "岁生日快乐")
#调用
happy_birthday(name = "小明", age = 18)
#happy_birthday(name = "小明", age1 = 18) 错误
happy_birthday("小虎", age = 20)
#传参需要位置传参在前,关键字传参在后
#happy_birthday( name = "小虎", 20)SyntaxError: positional argument follows keyword argument
1.3、默认值参数
def happy_birthday(name = "personname",age = 18):
print("祝" + name + str(age) + "岁生日快乐")
#调用
happy_birthday("小明", 18)
#TypeError: happy_birthday() missing 2 required positional arguments: 'name' and 'age'
happy_birthday()#默认值
happy_birthday("小明")#位置传参
happy_birthday(age=20)#关键字传参
'''
Traceback (most recent call last):
File "E:\pythonProject\Learning\Base\Chapter5\_3默认值参数的使用.py", line 11, in <module>
happy_birthday(19)#报错
^^^^^^^^^^^^^^^^^^
File "E:\pythonProject\Learning\Base\Chapter5\_3默认值参数的使用.py", line 2, in happy_birthday
print("祝" + name + str(age) + "岁生日快乐")
~~~~~~^~~~
TypeError: can only concatenate str (not "int") to str
'''
#happy_birthday(19)#报错
'''
位置参数在前,关键字参数在后
'''
def fun(a,b = 20):
pass
# def fun(a = 20 ,b):
# pass
2、可变参数
#个数可变的位置参数
def fun(*para):
print(type(para))
for item in para:
print(item)
#调用
fun(10,20,30,40)
fun(10)
fun(20,30)
fun([10,20,30,40])#一个参数
#调用时,参数加一颗星,会将列表进行解包
fun(*[10,20,30,40])
#个数可变的关键字参数
def fun2(**kwpara):
print(type(kwpara))
for key,value in kwpara.items():
print(key,"---",value)
#调用
fun2(name = "小明",age = 18, height = 180)
#字典传参需要解包,否则报错
d = {"name":"小明","age":18,"height":180}
#TypeError: fun2() takes 0 positional arguments but 1 was given
#fun2(d)
fun2(**d)
3、返回值
def sum(*para):
print(type(para))
sum = 0
for item in para:
sum += item
return sum
print(sum(1, 2, 3, 4, 5))
#列表
s = [1,2,3,4,5]
print(sum(*s))
4、变量的作用域
a = 100 #全局变量
def calc(x,y):
return a + x + y
print(a)
print(calc(10,20))
print("-"*30)
def calc2(x,y):
a = 200 #局部遍历
#局部优先级高
return a + x + y
print(a)
print(calc2(10,20))
print("-"*30)
def calc3(x,y):
global s #global全局变量
s = 300
return s + x + y
print(calc3(10,20))
print(s)
5、匿名的作用域
def calc(a,b):
return a + b
print(calc(10,20))
#匿名函数
s = lambda a,b : a + b
print(type(s))#<class 'function'>
#调用
print(s(10,20))
print("*"*30)
lst = [10,20,30,40]
for i in range(len(lst)):
print(lst[i])
print("*"*30)
for i in range(len(lst)):
result = lambda x:x[i] #根据索引取值,result类型卫function,x是形式参数
print(result(lst))
#
student_scores = [
{"name":"小a","score":90},
{"name":"小s","score":40},
{"name":"小d","score":50},
{"name":"小f","score":60}
]
#对列表排序
student_scores.sort(key=lambda x:x.get("score"),reverse=True)
print(student_scores)
6、递归
#求阶乘
def fac(n):
if n == 1:
return 1
else:
return n * fac(n - 1)
print(fac(5))
7、斐波那契数列
def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
print("*"*20)
for i in range(1,10):
print(fibonacci(i), end="\t")
8、常用内置函数
#bool()
print("非空字符串的布尔值",bool("he"))
print("空字符串的布尔值",bool(""))
print("空列表的布尔值",bool([]))
print("空列表的布尔值",bool(list()))
print("空元组的布尔值",bool(()))
print("空元组的布尔值",bool(tuple()))
print("空集合的布尔值",bool(set()))
print("空字典的布尔值",bool({}))
print("空字典的布尔值",bool(dict()))
print("*"*30)
print("非0数值型的布尔值:", bool(123))
print("整数0的布尔值:", bool(0))
print("浮点数0的布尔值:", bool(0.0))
#将其他类型转成数字类型
lst = [10,20,30]
print(type(lst), lst)
s= str(lst)
print(type(s),s)
#float str -> int
print("*"*30)
print(int(98.5) + int("99"))
#tip
#print(int("98.1"))#ValueError: invalid literal for int() with base 10: '98.1'
print(int("a"))#ValueError: invalid literal for
int() with base 10: 'a'
'''
结果:
1 0 10
(3, 1) (3, 1)
2
o
324
324
[12, 324, 45, 312, 12.2]
15
8
3
4
3.12
0.0
'''
print(abs(-1),abs(0),abs(10))
print(divmod(13,4),divmod(10,3))
print(max(1,2))
print(max("hello"))
print(max([12,324,45,312,12]))
print(max([12,324,45,312,12.1]))
print(max([12,324,45,312,12.1],[12,324,45,312,12.2]))
#min反之
print(sum([1,2,3,4,5]))
#print(sum(1,2,3,4,5))#TypeError: sum() takes at most 2 arguments (5 given)
#print(sum([1,2,3,4,5],[1,2,3,4,5]))TypeError: can only concatenate list (not "int") to list
print(pow(2,3))
print(round(3.12334234))
print(round(3.82334234))
print(round(3.12334234,2))
print(round(3.12334234,-1))
9、迭代器
9、迭代器
lst = [1,234,45,345,546,5467,567,56,7567,56687]
#sort
asc_lst = sorted(lst)
desc_lst = sorted(lst,reverse=True)
print("源列表",lst)
print("升序",asc_lst)
print("逆序",desc_lst)
#reversed 反转
reversed_lst = reversed(lst)
print(type(reversed_lst))
print(list(reversed_lst))
#zip
x = ['a','b','c','d','e']
y = [1,2,3,4]
zipobj = zip(x,y)
#会忽略最后一个没对齐的
print(type(zipobj))
#strict属性是严格对齐
#zipobj = zip(x,y,strict=True)
#print(type(zipobj))
print((zipobj))
#enumerate
enum = enumerate(y , start = 1)
print(type(enum))
print(tuple(enum))
#all
'''
all(iterable)
如果 iterable 的所有元素均为真值(或可迭代对象为空)则返回 True 。 等价于:
def all(iterable):
for element in iterable:
if not element:
return False
return True
'''
lst2 = [12,"",32]
print(all(lst2))
print(all(lst))
#any
'''
any(iterable)
如果 iterable 的任一元素为真值则返回 True。 如果可迭代对象为空,返回 False。 等价于:
def any(iterable):
for element in iterable:
if element:
return True
return False
'''
print(any(lst2))
#next
'''
next(iterator, default)
通过调用 iterator 的 __next__() 方法获取下一个元素。如果迭代器耗尽,则返回给定的 default,如果没有默认值则触发 StopIteration。
'''
print(next(zipobj))
print(next(zipobj))
print(next(zipobj))
'''
filter(function, iterable)
使用 iterable 中 function 返回真值的元素构造一个迭代器。 iterable 可以是一个序列,一个支持迭代的容器或者一个迭代器。 如果 function 为 None,则会使用标识号函数,也就是说,iterable 中所有具有假值的元素都将被移除。
'''
def fun(num):
return num % 2 == 1
obj = filter(fun,range(10))
print(list(obj))
#map
def upper(x):
return x.upper()
map_lst = ["hello","world","python"]
obj1 = map[upper, map_lst]
print(list(obj1))
10、练习
'''
编写函数实现计算列表中元素最大值
'''
import random
lst = [random.randint(1,101) for i in range(10)]
# for i in range(10):
# lst.append(random.randint(1,101))
print(lst)
def get_max(lst):
maxV = lst[0]
#遍历
for i in range(1, len(lst)):
if lst[i] > maxV:
maxV = lst[i]
return maxV
print(get_max(lst))
'''
编写函数实现提取指定字符串中的数字并求和
'''
def get_digit(x):
lst = []
for item in x:
if item.isdigit():
lst.append(int(item))
return lst,sum(lst)
s = input("请输入一个字符串:")
lst,x = get_digit(s)
print("提取的数字为:", lst)
print("累加和为:", x)
'''
实现in的功能
'''
def get_find(s,lst):
for item in lst:
for i in item:
if s == i:
return True
return False
lst = ["hello","world","python"]
s = "h"
result = get_find(s, lst)
#if..else 的简写
print("存在" if result else "不存在")