您的位置:首页 > 编程语言 > Python开发

Python学习笔记(五),条件,循环和其它语句(下)

2013-12-19 09:49 821 查看
5.5.5 跳出循环

1 break

与C一样.



>>> from math import sqrt
>>> for n in range(99,0,-1):
	root = sqrt(n)
	if root == int (root):
		print n
		break

	
81


2 continue

与C中一样,不赘述.

3 while True/break 习语

样例:



>>> while True:
	word=raw_input('p;ease enter a word:')
	if not word: break
	print ' the word was ' +word

	
p;ease enter a word: a
 the word was  a
p;ease enter a word: b
 the word was  b
p;ease enter a word: 
 the word was  
p;ease enter a word:
5.5.6 循环中的else子句

for n in range(99,0,-1):
	root = sqrt(n)
	if root == int (root):
		print n
		break
	else :print " don't find "

	
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
 don't find 
81


5.6 列表推导式-----轻量级循环

列表推导式是利用其它列表创建新列表, 他的工作方式类似于for循环, 也很简单:

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
也可以嵌套其它语句

[x*x for x in range(10)if x%3==0]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 9, 36, 81]
>>> [(x,y)for x in range(3)for y in range (3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]


5.7 三人行

5.7.1 什么都没发生

有时候,需要程序什么都不做

if name == 'l':

print 1

elif name =='2':

pass

elif:

print 3

5.7.2 使用del删除

一般来说,Python会删除那些不再使用的对象.



>>> x= [1,2]
>>> x
[1, 2]
>>> x=None
>>> x
此时[1,2] 这个字典便无法被获取和使用了. 这个时候,Python的解释器(以无穷的智慧)直接删除那个字典.

另一个方法是使用del, 他不仅会移除一个对象的引用,也会移除那个名字本身

>>> x=1
>>> del x
>>> x

Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    x
NameError: name 'x' is not defined


下面例子中,x 和 y都指向同一列表,删除x后 , y还在.因为删除的只是x这个名字

>>> x=y=[1,2]
>>> x
[1, 2]
>>> y
[1, 2]
>>> del x
>>> x

Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>> y
[1, 2]


5.7.3 使用exec和eval 执行和求值字符串

有些时候可能会需要动态地创造Python代码,然后将其作为语句执行,或作为表达式计算:

1 exec

执行一个字符串的语句是exec:



>>> exec "print 'hello,world!' "
hello,world!
但是,使用简单形式的exec语句绝不是好事.很多情况下可以给他提供命名空间----可以放置变量的地方.

可以通过增加in <scope> 来实现, 其中的<scope> 就是起到防止代码字符串命名空间作用的字典

>>> from math import sqrt
>>> scope={}
>>> exec 'sqrt=1' in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1


这部分内容下一章深入学习

2. eval

eval 是类似于exec的内建函数. exec语句会执行一系列的Python语句,而eval会计算Python表达式,并且返回结果值.例如,可以使用下面的代码常见一个Python计算器

eval(raw_input("enter an arithmet expression:"))
enter an arithmet expression:6+18*2
42


小结:

打印

导入

赋值



条件

断言

循环

列表推导式

pass,del,exec语句

现在基本知识已经学完,实现任何自己想到的算法已经没有问题.也可以让程序读取参数并打印结果.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: