《Python基础教程第二版》第五章-条件、循环和其他语句(一)
print和import
print打印多个表达式,用逗号,隔开
print 'abc:', 42, 'nonono' #输出在每个参数之间添加空格
print在结尾处加上逗号,,接下来的语句会与前一条语句打印在同一行
print 'hello', print 'word!' #hello word!
import从模块中导入函数
import module from module import function from module import function,function2,function3 from module import*
as子句,给出想要使用模块的别名
import math as fu1 fu1.sqrt(4) from math import sqrt as fun2 fun2(4)
赋值
序列解包/递归解包
多个赋值操作同时进行
x,y,z = 1,2,3
交换变量
x,y = y,x
popitem
popitem 获取并删除字典中任意的键值对,返回键值对元组,可以直接赋值到两个变量中。
scoundrel = {'name':'Robin', 'girlfriend':'Marion'}
key, value = scoundrel.popitem()Note:
所解包的序列中的元素数量必须和赋值符号=左边的变量数量完全一致。 #除非使用星号运算符: # a,b,*rest = [1,2,3,4] # rest结果为[3,4]
链式赋值
x = y = function()
增量赋值
x = 2 x += 2
语句块:缩进排版
创建语句块:
代码前放置空格缩进语句可以创建语句块。
Note: 块中的每行都应该缩进同样的量。
line1
line2:
block
same block
the last bolck
line3其中,
1. 冒号:标识语句块开始; 2. 块中每一个语句都是缩进相同量; 3. 退回到和已经闭合的块一样的缩进量时,表示当前块结束。
条件和条件语句
布尔变量
假fales(0)
Fales None 0 "" () [] {}
#其他都为真true(1)bool函数
bool('I think I'm ok.')
#true,一般Python会自动转换这些值if语句
if
name = raw_input(‘your name:’)
if name.endwith('afra'):
print 'hell, afra!'else
name = raw_input(‘your name:’)
if name.endswith('afra'):
print 'hell, afra!'
else:
print 'who?'elif
检查多个条件,else if简写
num = input('number:')
if num > 0:
print '>0'
elif num < 0:
print '<0'
else:
print '0'嵌套
if嵌套if语句
name = raw_input('name?')
if name.endswith('afra'):
if name.startswith('Mr.'):
print 'Mr.afra!'
elif name.startswith('Mrs.'):
print 'Mrs.afra'
else:
print 'afra'
else:
print 'who?'运算符
比较运算符
< == > >= <= != is 同一对象 is not 不同对象昂 x in y x是y容器的成员 not in 不是容器内的成员
连接运算符
比较运算符和赋值运算符都可以连接
0 < age < 10
- 相等运算符
== is同一性运算符`is`判定同一性,而不是相等性. 使用`==`运算符来判定两个对象是否相等,使用`is`判定两个是否是同一个对象。
in成员资格运算符name = raw_input('name?') if 's' in name: print 's' else: print '?'字符串和序列比较
字符串可按照字母顺序比较。 字母的顺序值可以用 ord函数 查到 ord()和chr()功能相反 忽略大小写可以使用 upper()\lower() 'KiJ'.lower() == 'kIj'.lower()
布尔运算符
and/or/notnumber = input('number?') if number <= 10 and number >=1: print 'yes' else: print 'no' #连接比较 1 <= number <= 10 #三个运算符结合 if ((cash > price) or customer_has credit) and not out_stock: give() #短路逻辑 略 #Python内置条件表达式 a if b else c b为真,返回a;否则,返回c
断言
asser
if not condition:
crash program可以要求某些条件必须为真,例如,检查函数参数的属性、作为初期测试和调试过程中的辅助条件。
age = 10 assert 0 < age < 100 age = -1 assert 0 < age < 100, 'must be realistic'
相关推荐
zhaobig 2020-08-17
TreasureZ 2020-08-02
NewActivity 2020-07-23
Jieen 2020-07-09
yawei 2020-07-06
AndroidAmelia 2020-05-17
fly00love 2020-05-16
zhuxianfeng 2020-05-17
银角大王 2020-05-11
joyjoy0 2020-05-09
伏雌摘星阁 2020-04-22
流云追风 2020-04-22
拉斯厄尔高福 2020-04-11
flycony 2020-04-10
致终将努力的我们 2020-04-08
xiaobater 2020-02-11
duanlove技术路途 2020-01-16
doubinning 2020-01-10
赵家小少爷 2020-01-04