本次的主要内容包括:
range 函数和random函数模块
range函数
range()函数可创建一个整数列表,一般用在 for 循环中。
- 语法
range(start, stop[, step])
start: start 起始数。默认 0 。例如range(5)等价于range(0, 5);
stop: stop 结束数,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
与for结合使用1
2for radius in range(0,10):
print (radius)
random函数模块
是一个外部函数模块需要先导入
- 导入方法:
import random
random.random() 方法返回随机生成的一个[0,1)范围内实数
函数
函数定义规则
函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 括号内是参数列表,例如:def range (bengin=0,end=100)
任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
函数内容以冒号起始,并且缩进。
return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
语法
1 | def 函数名(参数列表): |
函数调用:变量传入参数,通过函数名调用
参数
- 默认参数
匿名函数
以表达式的形式创建函数,不再使用 def 语句的形式定义
语法
lambda [arg1 [,arg2,…..argn]]:expression
lambda实例:
1 | sum = lambda arg1, arg2: arg1 + arg2 |
例1:计算圆的面积
1 | import math |
例2:读取mongoDB的find功能中返回起始结点边界的函数
def slice_bounds(sequence, slice_obj, allow_step=False):
"""
Given a slice, return the corresponding (start, stop) bounds,
taking into account None indices and negative indices. The
following guarantees are made for the returned start and stop values:
- 0 <= start <= len(sequence)
- 0 <= stop <= len(sequence)
- start <= stop
:raise ValueError: If ``slice_obj.step`` is not None.
:param allow_step: If true, then the slice object may have a
non-None step. If it does, then return a tuple
(start, stop, step).
"""
#函数体
start, stop = (slice_obj.start, slice_obj.stop)
# If allow_step is true, then include the step in our return
# value tuple.
if allow_step:
step = slice_obj.step
if step is None: step = 1
# Use a recursive call without allow_step to find the slice
# bounds. If step is negative, then the roles of start and
# stop (in terms of default values, etc), are swapped.
if step < 0:
start, stop = slice_bounds(sequence, slice(stop, start))
else:
start, stop = slice_bounds(sequence, slice(start, stop))
return start, stop, step
# Otherwise, make sure that no non-default step value is used.
elif slice_obj.step not in (None, 1):
raise ValueError('slices with steps are not supported by %s' %
sequence.__class__.__name__)
# Supply default offsets.
if start is None: start = 0
if stop is None: stop = len(sequence)
# Handle negative indices.
if start < 0: start = max(0, len(sequence)+start)
if stop < 0: stop = max(0, len(sequence)+stop)
# Make sure stop doesn't go past the end of the list. Note that
# we avoid calculating len(sequence) if possible, because for lazy
# sequences, calculating the length of a sequence can be expensive.
if stop > 0:
try: sequence[stop-1]
except IndexError: stop = len(sequence)
# Make sure start isn't past stop.
start = min(start, stop)
# That's all folks!
return start, stop