条件、循环和其他语句
- print、import
- 使用逗号输出多个表达式
>>> name="Gumby" >>> salutation="Mr." >>> greeting="Hello," ##同时输出三个变量 >>> print greeting + salutation + name Hello,Mr.Gumby # 普通输出,相邻两个变量之间有空格 >>> print greeting, salutation, name Hello, Mr. Gumby # 逗号输出,相邻两个变量之间有空格 >>> print "%s %s %s" % (greeting, salutation, name) Hello, Mr. Gumby # %格式化字符串输出,有无空格看""内如何定义 ##解决空格问题 >>> greeting="Hello" >>> print greeting , "," , salutation , name Hello , Mr. Gumby >>> print greeting + "," , salutation , name Hello, Mr. Gumby ##语句结尾处打逗号会去掉回车 text.txt: print "Hello,", print "world" cmd: py text.txt Hello, world
- 导入
1. import somemodule 2. from somemodule import somefunction 3. from somemodule import somefunction, anotherfunction, yetanotherfunction 4. from somemodule import *
当导入的两个函数重名时,只导入模块,或者as设置别名## module1.open() module2.open() ## from module1 import open as open1 open1() from module2 import open as open2 open2()
- 使用逗号输出多个表达式
- 赋值魔法
- 序列解包:将多个值的序列解开,然后放到变量的序列中。
>>>values = 1,2,3 >>>values (1,2,3) >>>x, y, z = values >>>print x, y, z 1 2 3 ##交换变量 >>>x, y = y, x >>>print x, y, z 2 1 3 ##当函数返回序列或映射时,序列解包很好用 >>> dic = {'name':{'one':'One','two':'Two'},'pho':{1:1,2:2}} >>> key, values = dic.popitem() >>> key 'pho' >>> values {1: 1, 2: 2} >>> key, values = dic.popitem() >>> key 'name' >>> values {'two': 'Two', 'one': 'One'} - 链式赋值
>>>x = y = somefunction()
注:关于 Python 链式赋值的坑 赋值从左往右:x = somefunction() -> y = somefunction() - 增量赋值
>>>x+=1 x-=1 x*=1 x/=1 #x为任意数据类型。
- 序列解包:将多个值的序列解开,然后放到变量的序列中。
- 语句块:缩排的乐趣
-
test..txt: x=[1,2,3] for i in x: print i print "end" cmd: py test.txt 1 2 3 end
-
- 条件和条件语句
- 比较运算符: == < > <= >= != is is not in not in
- 断言:assert
>>>if number<=10 and number >=1: >>> print "great" >>>elif number>=11: >>> print "wonderful" >>>else: >>> print "bad" >>>number = 101 >>>assert number >=100, 'The number is too big.' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: The number is too big.
- 循环
- 列表推导式-轻量级循环
- 1
- 三人行
- 1

浙公网安备 33010602011771号