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

Python基础教程笔记——第5章:条件,循环和其他语句

2015-08-06 19:29 381 查看
5.1 print和import的更多信息

1. print()3.0之后print不再是语句,而是函数,

>>> print('udg',12,13) udg 12 13

>>> name='yanliang' >>> print(name) yanliang

2. import 把某件事当做另外一件事导入

import somemodule

from somemodule import somefunction

from somemodule import somefunction1,somefunction2,somefunction3.。。。

from somemodule import *

(1)为导入的模块提供别名:>>> import math as foo >>> foo.sqrt(4) 2.0

(2)也可以为函数提供别名:>>>from module import function as function1

5.2 赋值魔法

1. 序列解包

(1)多个赋值同时进行:>>> x,y,z=1,2,3 >>> print(x,y,z) 1 2 3

(2)>>> x,y=y,x >>> print(x,y) 2 1

2. 链式赋值

(1)>>> x=y=2 相当于 >>> y=2 >>> x=y

3. 增量赋值

(1)>>> x+=3 类似于C++中的

5.3 语句块:缩排的乐趣

5.4 条件和条件语句

1. bool值是True配合False ,bool()函数可以用来转换其它的值。

2. if语句

name=input("what is your name!")
if name.endswith('liang'):
print('hello,yanliang')


3.else子句

name=input("what is your name!")
if name.endswith('liang'):
print('hello,yanliang')
else:
print("hello stringer")


4. elseif

5. 嵌套代码块

6. 更复杂的条件

(1)比较运算符:例如x<y , x<=y ,0<x<100也可以等

(2)相等运算符:>>> "foo"=="foo" True >>> "foo"=="fod" False

(3)is: 同一性运算符:

>>> x=y=[1,2,3] >>> x is y True 这里x,y被绑定到同一个对象上,所以具有同一性

>>> z=[1,2,3] >>> z is y False z虽然与y是相等的但不是同一个对象所以不具有同一性

(4)in 成员资格运算符

(5)字符串和序列的比较:按照字母顺序排列

(6)bool运算符:and or not

name=int(input("input the number"))
if name<10 and name>1:
print("OK")
else:
print("wrong")


(7)断言 assert 当不满足条件时直接崩溃退出

5.5 循环

1. while循环

name=''
while not name:
name=input("please input your name")
print("hello %s !" % name)


2. for循环

for number in range(10):
print(number)


3. 循环遍历字典元素

d={"a":1,"b":2,"c":3}
for key in d:
print(key,"corrsponds to",d[key])


4. 一些迭代工具

(1)并行迭代:zip()可以将两个序列合成一个字典对应起来

key1=['a','b','c']
value2=[1,2,3]
mapa=zip(key1,value2)

for name,age in mapa:
print(name,'is',age)


(2)编号迭代

将字符串数组中的包含‘yan’的自字符串全部替换成‘yanliang’

一种方法:

strings=['jhsf','yansgd','gd']
print(strings,'\n')
index=0;
for string in strings:
if 'yan' in string:
strings[index]='yanliang'
index+=1
print(strings,'\n')


第二种方法:采用enumerate函数 enumerate(strings)可以返回索引-值对

strings=['jhsf','yansgd','gd']
print(strings,'\n')
index=0;
for index,string in enumerate(strings):
if 'yan' in string:
strings[index]='yanliang'
print(strings,'\n')


(3)翻转和排序迭代

sorted和reserved 返回排好序或翻转后的对象

sort和reserve 在原地进行排序或翻转

5. 跳出循环

(1)break

(2)continue

(3)while True 。。。break

6. 循环中的else 语句

5.6 列表推导式——轻量级的循环

>>> [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, 9, 36, 81]

5.7 pass del exec

pass: 程序什么也不做

del: 不仅会删除对象的引用也会删除对象的名称,但是那个指向的对象的值是没办法删除的

exec: 执行一个字符串语句

最好是为这个exec语句提供一个命名空间,可以放置变量的地方

eval:

>>> eval(input('please input the number \n'))

please input the number

1+2+3

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