# -*- coding: cp936 -*-
#
def hello(name):
return "Hello,"+name+"!"
print(hello("zhangsan"))
#斐波那契数列
def fibs(num):
result = [0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
print(fibs(10))
print(fibs(15))
def square(x):
"Calculates the square of the number x"
return x*x
#square.__doc__
print(square.__doc__)
#help(square)可以查看
def hello2(greeting,name):
print("%s,%s!" % (greeting,name))
hello2("hello","zhangsan")
hello2(greeting="hello",name="zhangsan")#这种形式参数可以颠倒
def hello3(greeting="hello",name="name"):
print("%s,%s!" % (greeting,name))
hello3()
hello3(name="zhangsan")
hello3("Hello","zhangsan")
#返回元组
def params(*params):
print(params)
params(1,2,3,4)
#返回字典
def params2(**params):
print(params)
params2(x=1,y=2,z=3)
#联合使用
def params3(x,y,z,*a,**b):
print(x,y,z)
print(a)
print(b)
#关键字不能重复,x,y有问题,所以函数变量一般不要太简单
#params3(1,2,3,4,5,6,7,x=1,y=2)
params3(1,2,3,4,5,6,7,c=1,d=2)
#全局变量
x = 1
def inc():
global x #不加这句会报错,因为x没有初值
x = x + 1
inc()
print(x)
#递归
def jiecheng(num):
"阶乘算法,请输入大于等于0的整数"
if num==0:
return 0
elif num==1:
return 1
else:
return num*jiecheng(num-1)
print(jiecheng(6))
def pingfang(x1,num):
"x的num次方,第一个参数为x,第二个参数为大于等于0的整数num"
if num==0:
return 1
else:
return x1*pingfang(x1,num-1)
print(pingfang(2,10))
#查找一个数
def search(lst,num):
for i in range(0,len(lst)):
if lst[i]==num:
return i
return -1
seq = [1,2,3,5,4,6,5,3,34,32234,23,54,4,456,22]
seq.sort()
print(seq)
search(seq,23)
print(search(seq,23),seq[search(seq,23)])
#filter过滤,func返回true的保留
seq = [1,2,3,5,4,6,5,3,34,32234,23,54,4,456,22]
seq.sort()
def func(x):
if x==23:
return True
else:
return False
newSeq = filter(func,seq)
print(newSeq)
运行结果:
Hello,zhangsan!
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Calculates the square of the number x
hello,zhangsan!
hello,zhangsan!
hello,name!
hello,zhangsan!
Hello,zhangsan!
(1, 2, 3, 4)
{'y': 2, 'x': 1, 'z': 3}
(1, 2, 3)
(4, 5, 6, 7)
{'c': 1, 'd': 2}
2
720
1024
[1, 2, 3, 3, 4, 4, 5, 5, 6, 22, 23, 34, 54, 456, 32234]
(10, 23)
[23]