busybeta

yjcps
61

# Learn Python with Steem #06 笔记

[toc]

• 函数

• 函数的结构

## 编程练习

``````# 作业
def my_average(data):
average = (sum(data) - max(data) - min(data)) / (len(data) - 2)
return average

my_list = [1, 8, 3, 6, 2, 345, -23, 7]
``````
``````4.5
``````
``````# 将计算busy机器人点赞比例的功能写成一个函数
import requests

minVests = 20000000
# maxVests = 4000000000000  # maxVests 不是这个值
maxVests = 5000000000000
limitVests = 10000000000000
minPercent = 6 / 100
maxPercent = 2500 / 100

response = requests.get(url)
data = response.json()[0]
followers_mvest = data.get('followers_mvest')
if followers_mvest < minVests or followers_mvest > limitVests:
percent = 0
else:
percent = (10000 / maxVests) * followers_mvest
#         print(percent)
percent = min(max(percent, minPercent), maxPercent) / 100

print('Hi,{}\nfollowers_mvest:{}\nyour busy vote percent is: {:.2%}\n'.

#     return percent

busy_vote_percent('yjcps')
busy_vote_percent('dapeng')
busy_vote_percent('shine.wong')
busy_vote_percent('deanliu')
``````
``````Hi,yjcps
followers_mvest:93266616.60498305
your busy vote percent is: 0.19%

Hi,dapeng
followers_mvest:1856251363.8415272
your busy vote percent is: 3.71%

Hi,shine.wong
followers_mvest:261131007.75513688
your busy vote percent is: 0.52%

Hi,deanliu
followers_mvest:18379826592.987816
your busy vote percent is: 25.00%
``````

## 补充

### 变量的作用域

• 全局变量

• 局部变量

``````# 全局变量
a = 20
b = 30
c = 5

def my_fun():
# 局部变量
a = 7
b = 10
print('call my_fun：a={}, b={}, c={}'.format(a, b, c))

#     在函数里面有定义a,b变量属于局部变量，
#     在使用的时候优先使用局部变量，
#     看不见函数外面的全局变量

#     函数里面没有定义c变量
#     使用的时候会去查找外面的全局变量

my_fun()

print('a={}, b={}, c={}'.format(a, b, c))

# 在外面看不见函数里面的局部变量
``````
``````call my_fun：a=7, b=10, c=5
a=20, b=30, c=5
``````
``````# 全局变量
a = 20
b = 30
c = 5

def my_fun():

# 局部变量
a = 7

# 可以用global声明b是函数外面的全局变量
global b
b = 10
print('call my_fun：a={}, b={}, c={}'.format(a, b, c))

my_fun()

print('a={}, b={}, c={}'.format(a, b, c))

# 在函数外面可以看到变量b被修改了
``````
``````call my_fun：a=7, b=10, c=5
a=20, b=10, c=5
``````

### 匿名函数

Python中用lambda定义匿名函数

``````f = lambda x: x * 2 + x + 2

## 等价f(x)
# def f(x):
#     return x * 2 + x + 2

print(f(2))
print(f(5))
``````
``````8
17
``````

### 递归函数

``````# 经典例子：计算n的阶乘n!

def factorial(n):

# 递归出口
if n == 0:
return 1
# 递归体
return n * factorial(n - 1)

print(factorial(4))
print(factorial(9))
``````
``````24
362880
``````

### 装饰器

``````# 定义一个装饰器
def print_fun_name(func):
def wrapper(*args, **kw):
print('-----------------')
print('call function:{}'.format(func.__name__))
print('-----------------')
return func(*args, **kw)

return wrapper

# 使用装饰器

@print_fun_name
def say_hello(name):
print('Hello', name)

@print_fun_name
def say_bye(name):
print('Bye', name)

say_hello('yjcps')
say_bye('hacper')
``````
``````-----------------
call function:say_hello
-----------------
Hello yjcps
-----------------
call function:say_bye
-----------------
Bye hacper
``````