我是按照Python 2.5附带的文档来学的。文档很长,而且是英文的,我想以后查找起来会不太方便,所以将所学到的东西记在这里。因为有关Python更基础的东西自己早已知道,所以在这里就省略了。直接从比较新的部分学起。
if语句
问题:从键盘读入一个整数n,输出sgn(n)。
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
这个例子很简单,和其它语言没什么区别,相关用法都是一样的。只需注意一下elif是else if的缩写,别写错了就行。
for语句
问题:打印中一个List中的字符串和每个的长度。
a=['cat','window','defenestrate']
for x in a:
print x,len(x)
这个代码更加简单,要注意的仅仅是枚举List元素时可以简单地用in这个运算符。
问题:将上面字符串List中长度大于6的元素插入到List的头部,依次输出。
a=['cat','window','defenestrate']
for x in a[:]:
if len(x)>6:
a.insert(0,x)
for x in a:
print x
第一个循环里用的是for x in a[:],Python文档认为在循环中直接修改一个序列同时再枚举是不安全的,如果需要修改的话要生成一个Copy,再这个Copy中进行枚举。
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient.
range()函数
range()函数可以生成一个等差数列。例如,range(n)的结果就是一个包含0~n-1中的所有整数的List,range(m,n)结果是在[m,n)中的所有整数的List,而range(m,n,d)刚表示从m开始,到不超过n-1的以d为公差的List。
break和continue语句,以及在和循环语句一起使用的else语句
break和continue的作用和C语言中的一样,就不写了。
值得注意的是,for和while语句后可以和else引导的语句搭配。显然,它的意思是说在循环条件不再成立时用执行的操作。文档中的例子是一个判断[2,10)中每个整数是否是质数的程序。
for n in range(2,10):
for x in range(2,n):
if n%x==0:
print n,'equals',x,'*',n/x
break
else:
print n,'is a prime number'
pass语句
pass就是什么也不做,相当于一个空语句。
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
while True:
pass # Busy-wait for keyboard interrupt
![]()