1.定义函数
# 定义一个函数
def hello():
print('hello')
print('python')
# 通过函数名来调用函数
hello()
# 函数内定义函数
def westos():
print('it is westos')
def python():
print('is python')
python() #调用内置函数
westos()
2.形参
# 定义函数的时候的变量 叫形参(名字任意)
def welcome(a):
print('welcome',a)
# 真实的数据信息 被调用函数的时候 传递的值 叫实参
welcome('tom')
2.1.位置参数
def getinfo(name,age):
print('姓名:',name,'年龄:',age)
getinfo('westos',12)
getinfo(12,'westos') ##必须与参数位置对应,否则会错位
getinfo(age=12,name='westos')
2.2.默认参数
def mypow(x,y=2):
print(x ** y)
mypow(2,3) ##默认位置参数也可以赋值
mypow(2)
2.3.可变参数
# "*"表示,函数可以接受多个参数,全部放入一个元祖中。
def mysum(*args):
print(args)
sum = 0
for item in args:
sum += item
print(sum)
mysum(1,2,3,4,5,6,7,8)
# 参数的解包:在参数名前加*(在列表,元组或集合前面加*,可以装换为元组)
nums1 = [1, 2, 3]
nums2 = (1, 2, 3)
nums3 = {1, 2, 3}
# 参数的解包:在参数名前加*
mysum(*nums1)
mysum(*nums2)
mysum(*nums3)
2.3.关键字参数
def getinfo(name,age,**b):
print(name)
print(age)
print(b)
d = dict(a=1,b=2)
getinfo('westos',12,**d)
getinfo('tom',19,hobbies=['code','running'],gender='female')
3.函数的返回值
- 返回值:函数运算的结果 还需要进一步操作,给函数一个返回值
- return用来返回函数执行的结果 如果函数没有返回值 默认返回None
- 函数一旦遇到return 函数执行结束 后面的代码不会执行
- 多个返回值的时候 python会帮我们封装成一个元组类型
def mypow(x,y=2):
return x ** y, x + y
a = mypow(4)
print(a)
4.变量的作用域
- 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。
total = 0 # 这是一个全局变量
def sum(arg1, arg2):
# 返回2个参数的和."
total = arg1 + arg2 # total在这里是局部变量.
print("函数内是局部变量 : ", total)
return total
# 调用sum函数
sum(10, 20)
print("函数外是全局变量 : ", total)
- 当内部作用域想修改外部作用域的变量时,就要用到 global关键字。
num = 1
def fun1():
global num # 需要使用 global 关键字声明
print(num)
num = 123
print(num)
fun1()
print(num)
练习
test–1
编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.
元组的第一个值为所有参数的平均值, 第二个值是大于平均值的所有数.
def cacluate(*num):
all = 0
for i in num:
all += i
average = all / len(num)
num1 = []
for i in num:
if i > average:
num1.append(i)
return average, num1
print(cacluate(2,5,3,4,9,5,6,8))
test–2
编写一个函数, 接收字符串参数, 返回一个元组,‘ehllo WROLD’
元组的第一个值为大写字母的个数, 第二个值为小写字母个数.
ef fun(word):
num1=0
num2=0
for i in word:
if i.isupper():
num1+=1
elif i.islower():
num2+=1
else:
pass
return num1,num2
print(fun('xIwY nzJY'))
test–3
编写函数, 接收一个列表(包含30个整形数)和一个整形数k, 返回一个新列表.
函数需求:
- 将列表下标k之前对应(不包含k)的元素逆序;
- 将下标k及之后的元素逆序;
[1,2,3,4,5] 2----> [2,1,5,4,3]
def fun(alist,k):
if k < 0 or k > len(alist):
return 'error key'
return alist[:k][::-1] + alist[k:][::-1]
print(fun([1,2,3,4,5],2))
test–4
用函数实现求100-200里面所有的素数。
提示:素数的特征是除了1和其本身能被整除,其它数都不能被整除的数
# 判断一个数是不是素数
def test(num):
list = [] #定义一个列表 用于存储计算的数
i = num -1 # 去除本身
while i > 1: # 去除1
if num %i == 0 : #判断是否有余数
list.append(i) # 将所有的能整除i的数加入列表
i -= 1
if len(list) == 0:# 如果列表为空 就是表示除了1和它本身能整除
print(num,end=' ')
def test2(start_num,end_num):
j = start_num
while j < end_num:
test(j)
j += 1
test2(100,200)
print('')