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

Python基础学习三

2014-03-17 08:38 323 查看
条件、循环和其他语句

print使用逗号输出

>>> print 'age:',11

age: 11

>>> print 1,2,5,3,4

1 2 5 3 4

导入模块和模块中的方法

import somemodule

from somemodule import somefunction

from somemodule import somefunction,anotherfunction

from somemodule import *

另import math as foobar使用时foobar.sqrt(4)

from math import sqrt as foobar 使用时foobar(4)

赋值

序列解包

>>> x,y,z = 1,2,3 #多个变量同时赋值

>>> x,y,z

(1, 2, 3)

>>> x,y = y,x #两个或多个变量交换值

>>> x,y

(2, 1)

>>> sc = {'name':'fjia','age':22}

>>> sc.popitem()

('age', 22)

>>> key,value = sc.popitem() #允许函数返回一个以上的值并且打包成元组返回。

>>> key

'name'

>>> value

'fjia'

链式赋值

x = y = somefunction()

等价与

y = somefunction()

x = y

增量赋值

x += 1 === x = x+1 #适用于*、/、%运算符

语句块:缩进

Python中使用缩进相同的量表示同一个语句块,冒号表示语句块的开始。

条件、条件语句

下面的值作为布尔表达式的时候表示假(false)

False、None、0、""、()、[]、{}

条件执行和if语句、else子句、elif子句。

name = raw_input('What is your name ?')

if name.endswith('Fjia'):

print 'hello world Fjia'

num = int(raw_input('Enter a number:'))

if num>0:

print 'the number is positive'

elif num<0:

print 'the number is negative'

else:

print 'the number is zero'

name = raw_input('What is your name ?')

if name.endswith('Fjia'):

if name.startswith('Mr'):

print 'hello Mr Fjia'

elif name.startswith('Mrs'):

print 'hello Mrs Fjia'

else :

print 'hello Fjia'

else:

print 'hello anyone'

比较运算符

x == y x 等于 y

x < y x 小于 y

x > y x 大于 y

x >= y x 大于等于 y

x <= y x 小于等于 y

x != y x 不等于 y

x is y x和y是同一个对象

x is not y x和y不是同一个对象

x in y x是y容器的成员

x not in y x不是y容器的成员

字符串和序列比较

'abc' < 'bac'

[1,2,3] < [1,2,4]

[2,[1,2]] < [2,[1,3]]

布尔运算符

and、or、not (与、或、非)计算时短路逻辑的思想 如果第一个为真不计算第二个。

断言:确保程序中某一条件一定为真,才继续执行后面操作。

age = -1

assert 0<age<100 , 'this age must be realistic'

报错

assert 0<age<100 , 'this age must be realistic'

AssertionError: this age must be realistic

循环语句

while循环

name = ''

while not name:

name = raw_input('please input your name:')

print 'hello %s!' %name

for循环

words = ['this','si','an','ex','parrot']

for word in words:

print word

numbers = [0,1,2,3,4,5,6,7,8,9]

for number in numbers:

print number

内建函数range提供返回某范围数字序列的功能,下限包含,上限不包含。如果下限为0可以只提供上限。

range(0,10) == range(10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

遍历字典元素

d = {'x':1,'y':2,'z':3}

for key in d:

print key,'corresponds to', d[key]

d = {'x':1,'y':2,'z':3}

for key,value in d.items():

print key,'corresponds to',value

一些迭代工具

names = ['anne','beth','george','damon']

ages = [12,11,33,44]

for i in range(len(names)):

print names[i],'age is',ages[i]

#内建函数zip可以用来进行并行迭代,可以将两个序列压缩到一起,然后返回一个元组的序列。

#zip函数也可以作用于任意多个序列,zip可以应用与不等长的序列,当最短的用完是就会停止。

zip(names,ages) == [('anne', 12), ('beth', 11), ('george', 33), ('damon', 44)]

for name,age in zip(names,ages):

print name,'age is ',age

#内建函数enumerate,一般对一个列表或数组遍历时既要得到值又要得到索引可以使用该函数。

for index,value in enumerate(list):

print index,value

当然也可以

for i in range(0,len(list)):

print i,list[i]

反转和排序迭代

reversed 返回一个反序的列表副本,sorted返回一个排序的列表副本。

h = sorted('hello world') #返回列表

print h>>>[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

hello = reversed('hello world') #返回一个可用于迭代的对象,可使用list类型转换成的对象。

print list(hello)>>>['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']

hello = reversed('hello world')

print ''.join(hello) >>>dlrow olleh

跳出循环

break、continue前者是结束循环,后者是结束本次循环继续下一次循环。

while True/break习语

循环中的else子句,当不执行break时执行else的程序块

from math import sqrt

for n in range(99,81,-1):

root = sqrt(n)

if root == int(root):

print n

break

else:

print "Don't find it"

列表推导式,里面可以有多个条件

[x*x for x in range(9) if x%3 == 0] >>> [0, 9, 36]

pass语句什么都不做,可以用作代码中的占位符。

del删除不再使用的变量。

exec 执行一个Python语句

>>> exec "print 'hello'"

hello

>>> from math import sqrt

>>> exec "sqrt = 1"

>>> sqrt(4) 执行时会报错,因为sqrt的命名空间已经被占用。

可以增加in <scope>来实现

eval用于计算Python表达式的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: