条件语句
真值也称布尔值。
用作布尔表达式时,下面的值都将被视为假:False None 0 "" () [] {}。
布尔值True和False属于类型bool,而bool与list、str和tuple一样,可用来转换其他的值。
>>> bool('I think,therefore I am') True >>> bool(10) True >>> bool('') False >>> bool(0) False
if语句
>>> name = input('What is your name?') What is your name?Gumby >>> if name.endswith('Gumby'): print(name) Gumby
如果条件(if和冒号之间的表达式)是前面定义的真,就执行后续代码块,如果条件为假,就不执行。
else子句,elif子句,嵌套代码块
>>> name = input('What is your name?') What is your name?Gumby >>> if name.endswith('Gumby'): if name.startswith('Mr.'): print('Hello,Mr.Gumby') elif name.startswith('Mrs.'): print('Hello,Mrs.Gumby') else: print('Hello,Gumby') else: print('Hello,stranger') Hello,Gumby
比较运算符:
表达式 | 描述 |
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的成员 |
>>> x = y = [1,2,3] >>> z = [1,2,3] >>> x == y True >>> x == z True >>> x is y True >>> x is z False >>> #is检查两个对象是否相同(不是相等),变量x和y指向同一个列表,而z指向另一个列表(即使它们包含的值是一样的),这两个列表虽然相等,但并非同一个列表。
ord函数可以获取字母的顺序值,chr函数的作用与其相反:
>>> ord('a') 97 >>> ord('v') 118 >>> chr(118) 'v'
断言:assert
>>> age = 10 >>> assert 0 < age < 11 >>> age = -1 >>> assert 0 < age < 11 Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> assert 0 < age < 11 AssertionError >>> age = -1 >>> assert 0 < age < 11,'the age must be realistic' #字符串对断言做出说明 Traceback (most recent call last): File "<pyshell#49>", line 1, in <module> assert 0 < age < 11,'the age must be realistic' #字符串对断言做出说明 AssertionError: the age must be realistic
循环
while 循环
>>> name = '' >>> while not name.strip(): #屏蔽空格 name = input('please enter your name:') print('hello,{}!'.format(name)) please enter your name:Momo hello,Momo!
for循环
>>> numbers = [0,1,2,3,4,5,6,7,8] >>> for number in numbers: print(number) 0 1 2 3 4 5 6 7 8
内置函数range():
>>> range(0,10) range(0, 10) >>> list(range(0,10)) #范围[0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(10) #如果只提供1个位置,将把这个位置视为结束位置,并假定起始位置为0 range(0, 10) >>> for num in range(1,10): print(num) 1 2 3 4 5 6 7 8 9
迭代字典:
>>> d = dict(a=1,b=2,c=3) >>> d {'a': 1, 'b': 2, 'c': 3} >>> for key in d: print(key,'to',d[key]) a to 1 b to 2 c to 3
换一种方式迭代:
>>> for key,value in d.items(): print(key,'to',value) a to 1 b to 2 c to 3 >>> d.items() dict_items([('a', 1), ('b', 2), ('c', 3)])
并行迭代:
同时迭代2个序列。
>>> names = ['aaa','bbb','ccc'] >>> ages = [10,11,12] >>> for i in range(len(names)): print(names[i],'is',ages[i],'years old') aaa is 10 years old bbb is 11 years old ccc is 12 years old
内置函数zip,可以将2个序列缝合起来,并返回一个由元组组成的序列。
>>> list(zip(names,ages)) [('aaa', 10), ('bbb', 11), ('ccc', 12)] >>> for name,age in zip(names,ages): print(name,'is',age,'years old') aaa is 10 years old bbb is 11 years old ccc is 12 years old
zip函数可以缝合任意数量的序列,当序列的长度不同时,zip函数将在最短的序列用完后停止缝合。
>>> list(zip(range(5),range(10))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
迭代时获取索引:
>>> strings = ['aac','ddd','aa','ccc'] >>> for string in strings: if 'aa' in string: #替换列表中所有包含子串‘aa’的字符串 index = strings.index(string) #在列表中查找字符串 strings[index] = '[censored]' >>> strings ['[censored]', 'ddd', '[censored]', 'ccc']
优化一下:
>>> strings = ['aac','ddd','aa','ccc'] >>> index = 0 >>> for string in strings: if 'aa' in string: strings[index] = '[censored]' index += 1 >>> strings ['[censored]', 'ddd', '[censored]', 'ccc']
继续优化:
内置函数enumerate能够迭代索引-值对,其中的索引是自动提供的。
>>> strings = ['aac','ddd','aa','ccc'] >>> for index,string in enumerate(strings): if 'aa' in string: strings[index] = '[censored]' >>> strings ['[censored]', 'ddd', '[censored]', 'ccc']
反向迭代和排序后在迭代:
>>> sorted([4,2,5,1,3]) [1, 2, 3, 4, 5] >>> sorted('hello,world') #sorted返回一个列表 [',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] >>> list(reversed('Hello,world')) #reversed返回一个可迭代对象, ['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H'] >>> ''.join(reversed('Hello,world')) 'dlrow,olleH' >>> sorted('aBc',key=str.lower) #按照字母表排序,可以先转换为小写 ['a', 'B', 'c']
break 跳出循环
>>> from math import sqrt >>> for n in range(99,1,-1): #找出2-100的最大平方值,从100向下迭代,找到第一个平方值后,跳出循环。步长为负数,让range向下迭代。 root = sqrt(n) if root == int(root): #开平方为整 print(n) break 81
while True/break
>>> while True: #while True导致循环永不结束 word = input('enter your name:') if not word:break #在if语句中加入break可以跳出循环 print(word) enter your name:aa aa enter your name:bb bb enter your name: >>>
简单推导
列表推导式一种从其他列表创建列表的方式,类似于数学中的集合推导。
>>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
打印能被3整除的平方值
>>> [x*x for x in range(10) if x%3 == 0] [0, 9, 36, 81]
使用多个for部分,将名字的首字母相同的男孩和女孩配对。
>>> girls = ['aaa','bbb','ccc'] >>> boys = ['crde','bosy','adeb'] >>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]] ['crde+ccc', 'bosy+bbb', 'adeb+aaa']
上面的代码还能继续优化:
>>> girls = ['aaa','bbb','ccc'] >>> boys = ['crde','bosy','adeb'] >>> letterGrils = {} >>> for girl in girls: letterGrils.setdefault(girl[0],[]).append(girl) #每项的键都是一个字母,值为该字母开头的女孩名字组成的列表 >>> print([b+'+'+g for b in boys for g in letterGrils[b[0]]]) ['crde+ccc', 'bosy+bbb', 'adeb+aaa']
字典推导
>>> squares = {i:'{} squared is {}'.format(i,i**2) for i in range(10)} >>> squares[8] '8 squared is 64'