function函数定义
def定义函数
参数
参数:形参 实参
形参:位置参数 默认参数 可变参数 关键字参数
#位置参数
# def getInfo(name,age):
# print(name,age)
#
# getInfo('westos',11)
# getInfo(11,'westos')
# getInfo(age=11,name='westos')
#默认参数
# def mypow(x,y=2):
# print(x**y)
#
# mypow(4)
# mypow(2,3)
#可变参数
# def mysum(*a):
# sum = 0
# for item in a:
# sum += item
# print(sum)
#
# mysum(1,2,3,4,5)
#关键字参数
def getInfo(name,age,**kwargs):
print(name,age)
print(kwargs)
getInfo('westos',18,gender='female',hobbies=['coding','running'])
返回值
return关键字 函数返回值(可以是多个)
变量作用域
局部变量:在函数内部定义的变量,只在函数内部起作用,函数执行结束,变量会自动删除
全局变量
通过 global关键字改变全局变量
练习
编写一个函数, 接收字符串参数, 返回一个元组,'ehllo WROLD'
元组的第一个值为大写字母的个数, 第二个值为小写字母个数.
def fun(x):
upper_count = 0
lower_count = 0
for i in x:
if i.isupper():
upper_count += 1
elif i.islower():
lower_count += 1
else:
continue
return upper_count,lower_count
a = fun('ehllo WROLD')
print(a)
编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.
元组的第一个值为所有参数的平均值, 第二个值是大于平均值的所有数.
模拟轮盘抽奖游戏
# 轮盘分为三部分: 一等奖, 二等奖和三等奖;
# 轮盘转的时候是随机的,
# 如果范围在[0,0.08)之间,代表一等奖,
# 如果范围在[0.08,0.3)之间,代表2等奖,
# 如果范围在[0.3, 1.0)之间,代表3等奖,# 模拟本次活动1000人参加, 模拟游戏时需要准备各等级奖品的个数.
import random
rewardDict = {
'一等奖': (0,0.08),
'二等奖': (0.08,0.3),
'三等奖': (0.3,1)
}
def userfun():
num = random.random()
for k,v in rewardDict.items():
if v[0] <= num < v[1]:
return k
resultDict = {}
for i in range(1000):
res = userfun()
if res not in resultDict:
resultDict[res] = 1
else:
resultDict[res] += 1
for k,v in resultDict.items():
print(k,'--->',v)
列表生成式
1-10以内的偶数取平方生成列表