Python 学习 Part1
1. 斐波那契数序列
>>> a,b=0,1 >>> a 0 >>> b 1 >>> while b<10: print(b) a,b=b,a+b 1 1 2 3 5 8
关键字end(参数)可以用来避免输出后换行:
>>> a,b=0,1 >>> while b<1000: print(b,end=' ') a,b=b,a+b 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
2. Python流程控制
- if Statements if 语句:if语句可以有零个或多个elif分支语句,并且else分支语句是可选的。
>>> x=int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x<0: x=0 print("Negative changed to zero") elif x==0: print("Zero") elif x==1: print("Single") else: print("More") More
- for语句:对任何序列(列表或字符串)的项按照它们在序列中的顺序进行迭代
>>> a=["cat","window","defenstrate"] >>> for x in a: print(x,len(x)) cat 3 window 6 defenstrate 11 >>> for x in a[:]: if len(x)>6: a.insert(0,x) >>> a ['defenstrate', 'cat', 'window', 'defenstrate']
- range()函数
如果你必须迭代一个数字序列,内置函数range()会派上用场。它生成一个等差级数序列
>>> for i in range(5): print(i,end=' ') 0 1 2 3 4 >>> for i in range(5,10): print(i, end=' ') 5 6 7 8 9 >>> for i in range(0,10,3): print(i, end=' ') 0 3 6 9
可以通过结合使用range()和len(), 来迭代序列的索引
>>> a=['Mary','had','a','little','lamb'] >>> for i in range(len(a)): print(i,a[i]) 0 Mary 1 had 2 a 3 little 4 lamb
list()从迭代(对象)中创建列表
>>> print(range(10)) range(0, 10) >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- break, continue,以及循环的else子句
break语句用于跳出最近的for循环或while循环;continue语句继续循环的下一次迭代过程;
>>> for n in range(2,10): for x in range(2,n): if n%x==0: print(n,'is not a prime number') break else: print(n,'is a prime number') 2 is a prime number 3 is a prime number 4 is not a prime number 5 is a prime number 6 is not a prime number 7 is a prime number 8 is not a prime number 9 is not a prime number
- pass语句:不做任何事,它被用于语法结构上需要一条语句但并不做任何事时
pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作,比如:
>>> while True: pass
pass通常用来创建一个最简单的类:
>>> class MyEmptyClass: pass
pass在软件设计阶段也经常用来作为TODO,提醒实现相应的实现,比如:
>>> def initlog(*args): pass #please implement this
- 定义函数
>>> def fib(n): a,b=0,1 while b<n: print(b,end=' ') a,b=b,a+b >>> fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> f=fib >>> f(100) 1 1 2 3 5 8 13 21 34 55 89 >>>
定义一个返回斐波那契数列数字列表的函数,而不是打印它:
>>> def fib3(n): result=[] a,b=0,1 while b<n: result.append(b) a,b=b,a+b return result >>> f300=fib3(300) >>> f300 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
默认值赋予在函数定义是定义域的值,例如:
>>> def f(arg=i): print(arg) >>> i=6 >>> f() 5
Important warning:默认值只被赋值一次。下面的函数在后续的调用中会累计前面传给它的参数:
>>> def f(a,L=[]): L.append(a) return L >>> print(f(1)) [1] >>> print(f(2)) [1, 2] >>> print(f(3)) [1, 2, 3]
如果不想让默认值在后续调用中累积,可以:
>>> def f2(a,L=None): if L is None: L=[] L.append(a) return L >>> print(f2(1)) [1] >>> print(f2(2)) [2]
posted on 2013-10-12 14:36 LilianChen 阅读(722) 评论(0) 编辑 收藏 举报