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

python学习笔记(五)——语句

2013-04-08 22:16 579 查看
               语句(条件、循环和其他语句)

  之前一直在学习数据结构,单纯的结构并不能做什么事,只有组成语句之后才能实现比较复杂的功能,和其他语言一样,条件、循环是必不可少的。学习基本语句之前,先看一些其它知识。

关于print:

>>> print 1,2,3  #print的参数不能构成一个元组
1 2 3
>>> 1,2,3
(1, 2, 3)
>>> print (1,2,3)
(1, 2, 3)
>>> print 'Age',22  #输出的每个参数之间插入了一个空格
Age 22
>>> name='jason'
>>> greeting='hello,'
>>> print greeting,name  #同时输出文本和变量值
hello, jason


如果在结尾处加上逗号,那么接下来的语句会和前一条语句在同一行打印,如:

print 'hello,',
print 'world!'    #输出的结果为hello,world,注意这里要在脚本中运行


关于模块导入:

已经知道,导入模块的时候可以有以下几个方式:

import module

from module import function

from module import function1,function2,.....

from module import *

可以使用as为整个模块或者函数提供别名:

>>> import math as m
>>> m.sqrt(4)
2.0
>>> from math import sqrt as S
>>> S(4)
2.0


关于赋值:

(1)、序列解包——将多个值的序列解开,然后放到变量的序列中

>>> x,y,z=1,2,3  #多个赋值操作可以同时进行
>>> print x,y,z
1 2 3
>>> x,y=y,x  #两个或多个变量交换
>>> print x,y,z
2 1 3
>>> values=1,2,3  #序列解包
>>> values
(1, 2, 3)
>>> a,b,c=values
>>> a
1
#当函数或者方法返回元组时,这个很有用,它允许返回一个以上的值并打包成元组
>>> seq={'name':'jason','phone':'34223'}
>>> key,value=seq.popitem() #获取popitem方法删除时返回的键值对
>>> key
'phone'
>>> value
'34223'


注意:解包的序列中的元素数量必须和放置在赋值号=左边的变量数量完全一致

(2)、链式赋值

>>> x=y=z=2  #则xyz的值均为2
>>> y=3
>>> x=y
>>> x
3


(3)、增量赋值

>>> x=2
>>> x+=1
>>> x*=2
>>> x
6
>>> str='python'
>>> str*=2
>>> str
'pythonpython'


  在学习语句之前,我想说python中的缩进是个很坑爹的东西,它不仅仅是可读性那么简单了,少了或多了一个空格都是语法错误,而且很难排查,而且tab键也不太建议用,每个缩进是4个空格。因为python中的语句块不是通过大括号来区分的,所以就由缩进担当了这个大括号的角色,对它要求严格也很正常。

条件和条件语句:

(1)、布尔变量

  python中把空值和0也看作是false,总结下来,python中的假有如下几个:

False,None,0,"",(),[],{} 即空字符串、空元组、空列表、空字典都为假。其它的一切都被解释器解释为真

>>> True
True
>>> False
False
>>> bool(0)
False
>>> bool("")
False
>>> bool(42)
True
>>> 0==0
True


(2)、if、elif、else语句(注意缩进且最好作为脚本运行而不是在交互式环境下)

num=input('enter a number:')
if num>0:
print 'positive number'
elif num<0:
print 'negative number'
else :
print 'zero'
raw_input('press any key to exit!')


(3)、嵌套代码块

name=input('please input your name:')
if name.endswith('jzhou'):
if name.startswith('Mr.'):
print 'hello,Mr.jzhou'
elif name.startswith('Mrs.'):
print 'hello,Mrs.jzhou'
else:
print 'hello,jzhou'
else:
print 'hello,stranger!'
raw_input('press any key to exit!')


(4)、更复杂的条件

  1)、比较运算符(==,<,<=,>,>=,!=)

>>> 'foo'=='foo'
True
>>> 'foo'=='oof'
False
>>> 'foo'!='oof'
True


  2)、is:同一性运算符(判断是否属于同一个对象,而不是值是否相等)

>>> x=y=[1,2,3]
>>> z=[1,2,3]
>>> x==y
True
>>> x==z
True
>>> x is y
True
>>> x is z
False


  再看一个例子,有意让x和y的值相等,看看它们是否属于同一对象

>>> x=[1,2,3]
>>> y=[2,4]
>>> x is not y
True
>>> del x[2]  #删除x中的元素3,即为[1,2]
>>> y[1]=1   #将y的第二个元素改为1,即为[2,1]
>>> y.reverse ()  #将y的元素倒序,即为[1,2]
>>> x==y
True
>>> x is y
False


  3)、in:成员资格运算符

>>> name
'jason'
>>> if 's' in name:
print 'your name contains the letter "s"'
else :
print 'your name doesn\'t contains the letter "s"'

your name contains the letter "s"


  4)、字符串和序列的比较

>>> "alpha"<"beta"
True
>>> 'Jzhou'.lower()=='JZHOU'.lower()
True
>>> [1,2]<[2,1]
True
>>> [2,[1,5]]>[2,[1,4]]
True


  5)、逻辑运算符(and,or)

>>> number=input('enter a number between 1 and 10:')
enter a number between 1 and 10:4
>>> if number <=10 and number >=1:
print 'Great!'
else:
print 'wrong!'

Great!


断言——当输入不符合条件时,可以用断言来解释,即在程序中置入检查点

>>> age=-1
>>> assert 0<age<100,'The age must be realistic' #如果age输入在[0,100]之外,则提示出错

Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
assert 0<age<100,'The age must be realistic'
AssertionError: The age must be realistic


循环

(1)、while

>>> x=1
>>> while x<=100:
print x
x+=1


(2)、for

>>> words=['this','is','an','egg']
>>> for word in words:
print word

this
is
an
egg
>>> numbers=[1,2,3,4,5,6,7,8,9]
>>> for num in numbers:
print num


有个内建的迭代函数range,它类似于分片,包含下界,不包含上界

>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for num in range(1,5):
print num


(3)、循环遍历字典元素

>>> d={'x':1,'y':2,'z':3}
>>> for key in d:
print key,'corresponds to',d[key]

y corresponds to 2
x corresponds to 1
z corresponds to 3
>>> for key,value in d.items ():  #这种用法很重要
print key,'corresponds to',value

y corresponds to 2
x corresponds to 1
z corresponds to 3


常见迭代工具

(1)、并行迭代

>>> names=['jzhou','jason','james']
>>> ages=[22,42,45]
>>> for i in range(len(names)):  #i是循环索引
print names[1],'is',ages[i],'years old'

jason is 22 years old
jason is 42 years old
jason is 45 years old


内建的zip函数可以进行并行迭代,并可以把两个序列“压缩”在一起,然后返回一个元素的列表

>>> for name,age in zip(names,ages):  #在循环中解包元组
print name,'is',age,'years old'

jzhou is 22 years old
jason is 42 years old
james is 45 years old
# zip函数可以作用于任意多的序列,并且可以应付不等长的序列,最短的序列“用完”则停止
>>> zip(range(5),xrange(10000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
#注意:这里最好不要用range,因为range函数一次创建整个序列,而xrange一次只创建一个数。当需要迭代一个巨大的序列时,无疑xrange更高效。即此例中,使用xrange,序列只创建前5个数,而使用range则创建10000个,而我们只需要5个


(2)、翻转和排序迭代

>>> sorted([4,3,6,8,3])
[3, 3, 4, 6, 8]
>>> sorted('hello,python!')
['!', ',', 'e', 'h', 'h', 'l', 'l', 'n', 'o', 'o', 'p', 't', 'y']
>>> list(reversed ('hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
>>> ''.join(reversed('Hello,world!'))
'!dlrow,olleH'


reversed和sorted函数和列表的reverse和sort函数类似

跳出循环

(1)、break——退出循环

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

81


设置range的步长(第三个参数)也可以进行迭代

>>> range(0,10,2)
[0, 2, 4, 6, 8]


(2)、continue——跳出本次循环,继续下轮循环(不常用)

列表推导式——轻量级循环(列表推导式是利用其它列表创建新列表)

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


也可以在循环中加判断条件,如计算能被3整除的数的平方

>>> [x*x for x in range(10) if x%3==0]
[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)]


如果我们用普通方式实现上述的双重循环,则代码显得有点冗余

>>> result=[]
>>> for x in range(3):
for y in range(3):
result .append((x,y))

>>> result
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]


其它语句——pass,del,exec

(1)、pass

  由于python中空代码块是非法的,所以在什么事都不用做到情况下,可以使用pass作为占位符。(注释和pass语句联合的代替方案是插入字符串,后面笔记会介绍文档字符串)

(2)、del

>>> x=1
>>> del x  #del会移除一个对象的引用,也会移除名字本身
>>> x   #x被删除后,则不存在

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
x
NameError: name 'x' is not defined
>>> x=['hello','world']
>>> y=x  #x和y指向同一个列表
>>> y[1]='python'
>>> x
['hello', 'python']
>>> del x  #删除x后,y依然存在,因为删除的只是名称,而不是列表本身的值
>>> y
['hello', 'python']


(3)、exec

  用来执行储存在字符串或文件中的Python语句。

>>> exec 'a=100'
>>> a
100
>>> exec 'print "hello,world!"'
hello,world!
>>> h=['hello']
>>> w='world'
>>> exec ('h.append(%s)' % 'w')
>>> h
['hello', 'world']

>>> str = "for i in range(0,5): print i"
>>> c = compile(str,'','exec')
>>> exec c
0
1
2
3
4

(4)eval

  用来计算存储在字符串中的有效Python表达式。

>>> eval('2*3')
6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: