#函数
#常用内置函数
#abs
a = -10
print(abs(a))
#max min
l1 = [1,2,3,4,5,6]
print(max(l1),min(l1))
#sum
print(sum(l1))
#sorted
l2 = [6,5,4,3,2,1]
print(sorted(l2))
#len
print(len(l2))
#divmod 获取商和余数
a = 10
b = 2
print(divmod(a,b))
#pow 获取乘方数
print(pow(a,b))
#round 指定小数位数
a = 3.1415926
print(round(a,3))
#range
print(range(2,10))
10
6 1
21
[1, 2, 3, 4, 5, 6]
6
(5, 0)
100
3.142
range(2, 10)
In [44]:
#自定义函数 m是参数,m=2是缺省值 return返回返回值
def fun(m = 2):
print(m)
return m*m
res = fun(10)
#*x加了星号以后就是可变参数元祖
def fun1(*x):
for i in range(len(x)):
print(x[i])
fun1(1,2)
def fun2():
l1 = eval(input("please input list:\n"))
dic = dict.fromkeys(l1,l1)
return dic
print(fun2())
10
1
2
please input list:
1,23,4
{1: (1, 23, 4), 4: (1, 23, 4), 23: (1, 23, 4)}
In [52]:
#局部变量,全局变量 global 定义
s = 0 #全局变量
def f():
aa = 10 #局部变量
print(aa,s)
f()
print(s)
#print(a) error
10 0
0
In [57]:
#匿名函数 lambda
f = lambda a,b,c:a+b+c
print(f(1,2,3))
6
In [59]:
#检测空格,数字 字符
def fn(st):
n_alpha = 0
n_digit = 0
n_space = 0
n_qt = 0
for i in st:
if i.isalpha():
n_alpha += 1
elif i.isdigit():
n_digit += 1
elif i.isspace():
n_space += 1
else:
n_qt += 1
print(n_alpha,n_digit,n_space,n_qt)
fn("1234abcdfff 1233,,,,")
7 8 3 4
Python基础入门(函数)
猜你喜欢
转载自blog.csdn.net/weixin_38452632/article/details/83584468
今日推荐
周排行