分类: Python/Ruby
2009-08-18 08:31:43
fibs = [0, 1]
for i in range(8):
fibs.append(fibs[-2] + fibs[-1])
>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fibs = [0, 1]
num = input('How many Fibonacci numbers do you want? ')
for i in range(num-2):
fibs.append(fibs[-2] + fibs[-1])
print fibs
略
>>> import math
>>> x = 1
>>> y = math.sqrt
>>> callable(x)
False
>>> callable(y)
True
3.0中没有callable函数,要使用:hasattr(func, __call__).
函数定义:
def hello(name):
return 'Hello, ' + name + '!'
>>> print hello('world')
Hello, world!
def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result
函数注释:
def square(x):
'Calculates the square of the number x.'
return x*x
The docstring
>>> square.__doc__
'Calculates the square of the number x.'
__doc__是函数的特殊属性
无返回值的函数:
def test():
print 'This is printed'
return
print 'This is not'
不可变长度的参数不会改变实际参数的值,可变的则会改变。
必须要这样的拷贝:
>>> names = ['Mrs. Entity', 'Mrs. Thing']
>>> n = names[:]
参数的顺序可变:
>>> hello_1(greeting='Hello', name='world')
Hello, world!
建议参数较多的时候这样使用。
函数的定义可以使用默认参数:
def hello_3(greeting='Hello', name='world'):
print '%s, %s!' % (greeting, name)
*号表示吸收后面所有的参数为数组。但是不支持关键字参数。
>>> print_params_3(x=1, y=2, z=3)
{'z': 3, 'x': 1, 'y': 2}
def print_params_4(x, y, z=3, *pospar, **keypar):
print x, y, z
print pospar
print keypar
This works just as expected:
>>> print_params_4(1, 2, 3, 5, 6, 7, foo=1, bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1, 2)
1 2 3
()
{}
本节的余下部分和实例暂未涉及
访问全局变量:
globals()
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)