Python条件、循环和其他语句

来源:互联网 发布:华为路由器配置端口ip 编辑:程序博客网 时间:2024/05/19 15:40

1.简单的知识点

从可以从一个模块一次导入多个函数
import somemodule import somefunction,anoterfunction,

也可以给模块和函数起别名
import math as foobar
from math import sqrt as foobar

1.1赋值

Python的赋值非常灵活,可以同时进行多个赋值操作
x,y,z = 1,2,3print (x,y,z)
1 2 3
当函数或者方法返回元组(或者其他序列或可迭代对象)时,这个特性尤其有用。
number = {'name':'zhao','age':42}key,value = number.popitem()print (key,value)
age 42

赋值两边的数量必须完全一致,否则会发生异常,这时需要使用另外一个特性
a,b,*rest = (1,2,3,4)print (a,b,rest)
1 2 [3, 4]
#可以看出如果右边是元组 也依然是一一对应的关系,输出也变成了列表
*号也可以放在其他位置也是可以的,这样他总会包含一个列表
*a,b,rest = (1,2,3,4)print (a,b,rest)
[1, 2] 3 4

a,*b,rest = (1,2,3,4)print (a,b,rest)
1 [2, 3] 4

链式赋值
x = y = somefunciton()  等价于
y = somefunction()
x = y
但是如果分开赋值就不一定等价了
y = somefunction()
x = somefunciton ()

增量赋值
Python不仅可以应用于数字,也应用于其他类型
world = 'foot'world += 'ball'world *= 2print (world)
footballfootball

语句块
在Python中用;冒号来标志语句块的开始,块中的每一个语句都是等量缩进的
伪代码:
this is a line 
this is another line:
this is another block
contuining the same block
there we escaped the inner block

2.条件和条件语句

False  None  0   ""   ()    {}     []
都会被解释器看做假,但是他们本身却不相等,其他一切为真。

2.1条件执行和if语句

基本参照C语言,除了格式有点区别

is:同一性运算符
x = [1,2,3]y = [1,2,3]z = xprint (y == z)print (y is z)print (x is z)
TrueFalseTrue
总结就是==运算符判断两个对象是否相等,使用is判断两者是否等同(同一个对象)

布尔运算符
布尔运算符有个有趣的特性:只有在有需要的时候才进行求值。x and y ,如果x为假,则表达式就会立刻返回False,而不管y的值
a if b else c :如果b为真,返回a,否则返回c

断言assert
与其让程序在晚些时候崩溃,不然在错误条件出现时直接让他崩溃
age = -1assert 0 <age <100,'the age must be realistic'
AssertionError                            Traceback (most recent call last)<ipython-input-13-b69cb103543d> in <module>()      1 age = -1----> 2 assert 0 <age <100,'the age must be realistic'AssertionError: the age must be realistic
#条件后可以添加字符串,用来解释断言

2.2循环

while语句类似C语言
重点是for语句
x = ['this','is','an','example']for word in x:    print (word)
thisisanexample
能使用for尽量不要使用while

d = {'name':'zhao','age':[42,'man']}for key in d:    print (key,":",d[key])
name : zhaoage : [42, 'man']

并行迭代
迭代是循环的另一种说法
names = ['zhao','qian','sun','li']ages = [34,35,36,37,38]for name,age in zip (names,ages):    print (name,'is',age,'years old')
zhao is 34 years oldqian is 35 years oldsun is 36 years oldli is 37 years old
#当序列不等长时,处理完最短的就会停止

按索引迭代
names = ['zhao','qian','sun','li']for index,string in enumerate(names):    if 'qian' in string:       names[index] = 'su'print (names)
['zhao', 'su', 'sun', 'li']

翻转和排序迭代
sorted,reversed课作用于任何序列和可迭代的对象上,不是原地修改对象,而是返回翻转或排序后的版本
names = ['zhao','chen','sun','li']print(sorted(names))print (names)
['chen', 'li', 'sun', 'zhao']['zhao', 'chen', 'sun', 'li']

names = ('zhao','chen','sun','li')list(reversed(names))
['li', 'sun', 'chen', 'zhao']

sorted('hello,world')
[',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

reversed('hello,world')
<reversed at 0x4478610>

list(reversed('hello,world'))
['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
#sorted返回列表,reversed返回是一个可迭代对象

跳出循环
break跳出当前整个循环,而continue跳到下一个循环开始,和c语言中的类似
在循环中增加一个else子句,它仅在没有调用break时执行
from math import sqrtfor n in range(99,81,-1):    root = sqrt(n)    if root == int(root):        print (n)        breakelse:    print ("don't find it")
don't find it

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

列表推导式是利用其它列表创建新列表的一种方法,类似于for循环

print([x*x for x in range(10) if x%3 == 0])

[0, 9, 36, 81]


print ([(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)]


3.三人行

pass、del和exec
当程序还没有编写完就行测试的时候,在缺少语句的地方加上pass,可以是程序顺利的进行测试
del删除的只是名称,而不是列表本身。事实上,在Python没有办法删除值Python解释器自动负责内存的回收

有些时候需要动态的创造Python代码:

就像print语句在Python 3里变成了一个函数一样,exec语句也是这样的。exec()函数使用一个包含任意Python代码的字符串作为参数,然后就像执行语句或者表达式一样执行它。exec()eval()是相似的,但是exec()更加强大并更具有技巧性。eval()函数只能执行单独一条表达式,但是exec()能够执行多条语句,导入(import),函数声明 — 实际上整个Python程序的字符串表示也可以。

NotesPython 2Python 3①exec codeStringexec(codeString)exec codeString in a_global_namespaceexec(codeString, a_global_namespace)exec codeString in a_global_namespace, a_local_namespaceexec(codeString, a_global_namespace, a_local_namespace)
  1. 在最简单的形式下,因为exec()现在是一个函数,而不是语句,2to3会把这个字符串形式的代码用括号围起来。
  2. Python 2里的exec语句可以指定名字空间,代码将在这个由全局对象组成的私有空间里执行。Python 3也有这样的功能;你只需要把这个名字空间作为第二个参数传递给exec()函数。
  3. 更加神奇的是,Python 2里的exec语句还可以指定一个本地名字空间(比如一个函数里声明的变量)。在Python 3里,exec()函数也有这样的功能。

引用python2和python3的不同

使用exec和eval一定要注意作用域的问题

















原创粉丝点击