python 语句块_python学习记录(五) --语句块和比较符

1、print和import  P83

import ... as ...

2、赋值

3、语句块

语句块是在条件为真if时执行或者执行多次for的一组语句。在代码前放置空格来缩进语句即可创建语句块。

使用冒号: 表示语句块的开始

假: False, None, 0, "", (), []

注意: [] != False   []:空的字典

() != "" ():空的元组和序列

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

if name.endswith('Yilia'):

print 'hello %s' %name

else:

print 'input error'

4、比较运算符

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容器的成员

0

>>> x = [1,2,3]

>>> z = [1,2,3]

>>> y = x

>>> x == y

True

>>> x == z

True

>>> y == z

True

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

True

>>> x is z # x和z不是同一个对象

False

>>> y is x

True

>>> y is z

False

5、断言

错误出现时程序直接崩溃

要求某些条件必须为真时,使用断言。关键字:assert

num = input('enter a number:') # 注意这里使用数字,必须使用input

assert -10 < num < 10

6、while循环和for循环

range函数

>>> range(0,10)

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

>>> [x*x for x in range(1,10)]

[1, 4, 9, 16, 25, 36, 49, 64, 81]

遍历字典

>>> x = {'name':'yilia', 'age':'16', 'class':['math','english','music']}

>>> for key in x:

...    print key, 'corresponds to ', x[key]

...

age corresponds to 16

name corresponds to yilia

class corresponds to ['math', 'english', 'music']

>>> for key,value in x.items():

...    print key, ' corresponds to ', value

...

age corresponds to 16

name corresponds to yilia

class corresponds to ['math', 'english', 'music']

跳出循环:

break

continue

简单例子:

girls = ['alice', 'birnice', 'clacrice']

boys = ['chris', 'arnold', 'bob']

letterGirls={}

for girl in girls:

letterGirls.setdefault(girl[0], []).append(girl)

print [b+' + ' + g for b in boys for g in letterGirls[b[0]]]

['chris + clacrice', 'arnold + alice', 'bob + birnice']

7、三人行 pass del exec

pass: 用来代替空代码块

del : 删除不再使用的对象

>>> x = 9

>>> x = None # 移除对象引用

>>> x

>>> x = 9

>>> del x # 不仅移除对象的引用,也移除对象名称,而不会删除本身值

>>> x

Traceback (most recent call last):

File "", line 1, in

NameError: name 'x' is not defined

>>> x = 9

>>> y = x

>>> y

9

>>> x

9

>>> del x

>>> x # x不存在

Traceback (most recent call last):

File "", line 1, in

NameError: name 'x' is not defined

>>> y # y的值仍然存在

9

exec: 执行字符串中的python代码

>>> exec "print 'hello,world'"

hello,world

eval: 计算Python表达式(以字符串形式书写),并且返回结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值