一,再谈print,import
1.1打印多个参数
①多个参数用逗号隔开,打印时参数之间自动加一个空格
>>> print('hello','i am','Peter')
hello i am Peter
②可自定义分隔符 sep
>>> print("I", "wish", "to", "register", "a", "complaint", sep="_")
I_wish_to_register_a_complaint
③还可自定义结束字符串,以替换默认的换行符
print('Hello,', end='')
print('world!')
运行结果:
Hello, world!
1.2导入模块时重命名
导入模块:
import somemodule
from somemodule import somefunction
from somemodule import somefunction,anotherfunction,yetanotherfunction
#当你确定要导入模块中的一切时
from somemodule import *
指定别名:
在语句末尾添加as子句并指定别名(给模块或模块.函数):
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
二,赋值魔法
2.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)
>>> x, y, z = values
>>> x
1
可将字典的某一项(以元组的形式解包)
>>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
>>> key, value = scoundrel.popitem()
>>> key
'girlfriend'
>>> value
'Marion'
可使用星号运算符( * )来收集多余的值,这样无需确保值和变量的个数相同
>>> a, b, *rest = [1, 2, 3, 4]
>>> rest
[3, 4]
还可将带星号的变量放在其他位置
>>> x,*y,z=1,2,3,4,5
>>> x
1
>>> y
[2, 3, 4]
>>> z
5
>>> x,*t,z=y
>>> x
2
>>> t
[3]
>>> z
4
!!!注意加(*)的变量最终都是一个列表
2.2.链式赋值
将多个变量关联到同一个值
>>> x=y=3
>>> x
3
>>> y
3
2.3.增强赋值
x+=1…
三,代码块
缩进,冒号…
四,条件和条件语句
4.1.布尔值
①用作布尔表达式(如用作 if 语句中的条件)时,下面的值都将被解释器视为假:
False , None , 0 ,"", (), [] ,{}
②布尔值 True 和 False 属于类型 bool ,而 bool 与 list 、 str 和 tuple 一样,可用来转换其他的值。但python一般会自动转换
4.2 if else
if 条件:
...
else:
...
条件表达式(三目运算符):
结果 = <结果1> if 条件 else <结果2>
条件为真,结果=结果1,否则结果=结果2.。
4.3 elif 子句
检查多个条件
if 条件1:
...
elif 条件2:
...
else:
...
4.4 更复杂的条件
①比较运算符
表 达 式 | 描 述 |
---|---|
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 的成员 |
is 与 ==:
>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
Fals
!!!警告
不要将 is 用于数和字符串等不可变的基本值。鉴于Python在内部处理这些对象的方式,这样做的结果是不可预测的。
②字符串和序列的比较
字符串是根据字符的字母排列顺序进行比较的。
虽然基于的是字母排列顺序,但字母都是Unicode字符,它们是按码点排列的
③链式比较 1 <= number <= 10
④and 与 or
即C语言的 && 与 || 效果一样 也会“短路”
4.5 断言 assert
assert 条件
不满足条件立即崩溃
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
五,循环
5.1 while循环
while 条件:
...
5.2 for循环
为序列(或其他可迭代对象)中每个元素执行代码块
即迭代(遍历)
>>> words = ['this', 'is', 'an', 'ex', 'parrot']
>>> for word in words:
print(word)
this
is
an
ex
parrot
① range 创建范围的内置寒素(类?)
range(起始位置,结束位置后一位)
>>> range(0, 10)
range(0, 10)
>>> list(range(0, 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])
x corresponds to 1
y corresponds to 2
z corresponds to 3
!!!可在for中使用序列解包
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for key,values in d.items():
print(key ,'corresponds to', values)
x corresponds to 1
y corresponds to 2
z corresponds to 3
注意:
字典元素的排列顺序是不确定的。换而言之,迭代字典的键或值时,一定会处理所有的键或值,但不知道处理的顺序。如果顺序很重要,可将键或值存储在一个列表中并对列表排序,再进行迭代。要让映射记住其项的插入顺序,可使用模块 collections 中的OrderedDict 类。
③ 一些迭代工具
- 并行迭代
有时候,你可能想同时迭代两个序列。
zip
内置函数 zip ,它将两个序列“缝合”起来,并返回一个由元组组成的序列(可解包)。返回值是一个适合迭代的对象。
>>> names = ['anne', 'beth', 'george', 'damon']
>>> ages = [12,45,32,102]
>>> for name,age in zip(names,ages):
print(name,'is',age,'years old')
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old
!!!当序列的长度不同时,函数 zip 将在最短的序列用完后停止“缝合”。
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
④迭代时获取索引
enumerate
能够迭代索引值对,其中的索引是自动提供的
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
⑤. 反向迭代和排序后再迭代
sorted 排序序列或可迭代对象,但不修改对象,返回列表。
reverse 反转序列或可迭代对象,不修改对象,返回一个可迭代对象,可在for循环或join等方法中调用。
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
5.3跳出循环
5.3.1.break
5.3.2.continue
5.4 循环中的else
仅在没有调用break时执行
5.5简单推导
列表推导
>>> [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]
>>> [(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)]
使用圆括号代替方括号并不能实现元组推导,而是将创建生成器
可使用花括号来执行字典推导
>>> squares = {i:"{} squared is {}".format(i, i**2) for i in range(10)}
>>> squares[8]
'8 squared is 64
5.6. pass ,del ,exec
①pass:什么都不做,可用于表示还未完成,待以后添加
②del:
对于你不再使用的对象,Python通常会将其删除(因为没有任何变量或数据结构成员指向它)。
使用 del 语句,不仅会删除到对象的引用,还会删除名称本身
③exec 和 eval
1)函数 exec 将字符串作为代码执行。
在大多数情况下,还应向它传递一个命名空间——用于放置变量的地方;否则代码将污染你的命名空间,即修改你的变量。
添加第二个参数——字典,用作代码字符串的命名空间。
>>> from math import sqrt
>>> scope = {}
>>> exec('sqrt = 1', scope)
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
如果你尝试将 scope 打印出来,将发现它包含很多内容,这是因为自动在其中添加
了包含所有内置函数和值的字典 builtins 。
>>> len(scope)
2
>>> scope.keys()
['sqrt', '__builtins__']
实际上,可向 exec 提供两个命名空间:一个全局的和一个局部的。提供的全局命名空间必须是字典,而提供的局部命名空间可以是任何映射。这一点也适用于 eval 。
2)eval 是一个类似于 exec 的内置函数。 exec 执行一系列Python语句,而 eval 计算用字符串表示的Python表达式的值,并返回结果( exec 什么都不返回,因为它本身是条语句)
也应该向eval添加命名空间
>>> scope={}
>>> eval(input("Enter an arithmetic expression: "),scope)
Enter an arithmetic expression: 2+14
16
>>> scope={'x':13,'y':12}
>>> eval(input("Enter an arithmetic expression: "),scope)
Enter an arithmetic expression: x+6
19