Python基础教程笔记——条件,循环和其他语句
条件,循环和其他语句Table of Contents1 print和import的更多信息 1.1 使用逗号输出 1.2 把一些东东作为另一些东东导入 2 赋值魔法 2.1 序列解包 2.2 链式赋值 2.3 增量赋值 3 语句块:缩排的乐趣 4 条件和条件语句 4.1 这就是布尔变量的作用 4.2 条件执行和if语句 4.3 else子句 4.4 elif子句 4.5 嵌套代码块 4.6 更复杂的条件 4.6.1 比较运算符 4.6.2 相等运算符 4.6.3 同一性运算符 4.6.4 成员资格运算符 4.6.5 字符串和序列比较 4.6.6 布尔运算符 4.7 断言 5 循环 5.1 while循环 5.2 for循环 5.3 循环遍历字典元素 5.4 一些迭代工具 5.4.1 并行迭代 5.4.2 编号迭代 5.4.3 翻转和排序迭代 5.5 跳出循环 5.5.1 break 5.5.2 continue 5.5.3 while True/break 5.5.4 循环中的else子句 6 列表推导式 7 三人行 7.1 pass 7.2 del 7.3 exec和eval 1 print和import的更多信息?1.1 使用逗号输出说明:使用print时,也可以在语句中添加多个表达式,每个表达式用逗 号分隔;注意:在用逗号分隔输出时,print语句会在每个输出项后面自动添加一 个空格;例子: 1: >>> greeting = 'Hello' 2: >>> salution = 'Mr.' 3: >>> name = 'Bill' 4: #以逗号分隔输出项 5: >>> print(greeting, salution, name) 6: Hello Mr. Bill 7: #在逗号前增加了一个空格符 8: >>> print(greeting, ',', salution, name) 9: Hello , Mr. Bill10: #为了显示成'Hello, Mr. Bill'这个样式,可以使用连接符‘+’11: >>> print(greeting + ',', salution, name)12: Hello, Mr. Bill13: >>>14:
1.2 把一些东东作为另一些东东导入说明: 将整个模块导入,格式为:import somemodule;从某个模块中导入某个函数,格式为:from somemodule import somefunction;从某个模块中导入多个函数,格式为:from somemodule import firstfunc, secondfunc, thirdfunc将某个模块中的全部函数导入,格式为:from somemodule import *
注意:如果两个模块中都有相同的函数,则可以使用第一种方法导入模块, 也可以使用关键字 as为相同的函数取个别名,例子: 1: #第一种导入方法 2: #导入模块 3: import module1 4: import module2 5: #调用同名函数的方法 6: module1.open() 7: module2.open() 8: 9: #第二种导入方法10: #导入函数,并给函数取相应的别名11: from module1 import open as open112: from module2 import open as open213:
例子: 1: #从math中导入sqrt 2: >>> from math import sqrt as msqrt 3: #从cmath中导入sqrt 4: >>> from cmath import sqrt as csqrt 5: >>> msqrt(100) 6: 10.0 7: >>> csqrt(-1) 8: 1j 9: >>>10:
2 赋值魔法?2.1 序列解包说明:多个赋值操作可以同时进行例子: 1: #一般的同时赋值操作 2: >>> x, y, z = (1,2,3) 3: >>> x 4: 1 5: >>> y 6: 2 7: >>> z 8: 3 9: >>>10: 11: #从字典中弹出任意一对儿键值对儿,并赋值给两个变量12: >>> people = {'first': 'Andy', 'second':'Bill'}13: >>> key, value = people.popitem()14: >>> key15: 'second'16: >>> value17: 'Bill'18: >>>19:
2.2 链式赋值说明:同时将一个值赋给多个变量;例子: 1: #链式赋值 2: >>> x=y=z=1 3: >>> x 4: 1 5: >>> y 6: 1 7: >>> z 8: 1 9: >>>10:
2.3 增量赋值说明:包括以下增量操作: +=:将右侧的值加到变量上的和,然后再赋值给变量;-=:将变量减去右侧的值得到的差,再赋值给变量;/=:用变量除以右侧值得到的商,再赋值给变量;%=:用变量取右侧值的余数,再赋值给变量;
注意: += 和 \*= 还可以应用在字符串上,见下面的示例;例子: 1: #针对数字的各种操作 2: >>> x = 123 3: >>> x += 1 4: >>> x 5: 124 6: >>> x -= 4 7: >>> x 8: 120 9: >>> x *=210: >>> x11: 24012: >>> x /=313: >>> x14: 80.015: >>> x %=916: >>> x17: 8.018: >>>19: 20: #字符串的增量赋值21: >>> y = 'Test string'22: >>> y += ', haha!'23: >>> y24: 'Test string, haha!'25: >>> y *= 226: >>> y27: 'Test string, haha!Test string, haha!'28: >>>29:
3 语句块:缩排的乐趣说明:语句块是一组语句,在代码前放置空格来缩进语句即可创建语句 块;
4 条件和条件语句?4.1 这就是布尔变量的作用说明:布尔值, 假值:false,None,所有类型的数字0,空序列,空字典;真值:所有的非空值;bool函数可以用来将其他值转换成布尔值;
注意:尽管假值具有不同的类型,但是不同的假值之前也是 不相等 的例子: 1: >>> True 2: True 3: >>> False 4: False 5: >>> [] 6: [] 7: >>> bool ([]) 8: False 9: >>> bool ([1,])10: True11: >>> bool (0)12: False13: >>> bool (0.0)14: False15: >>> bool (0.1)16: True17: #不同的假值之间也是不相同的18: >>> [] == {}19: False20: >>> [] == None21: False22: >>>23:
4.2 条件执行和if语句说明:if 判断其后面的条件语句是否为真,如果为真,执行if后面的语句 块,否则不执行;
4.3 else子句说明:之所以称为子句是因为else必须跟在if语句后面,而不能单独使用;
4.4 elif子句说明:如果需要更多的判断,可以使用elif,判断更多的条件;例子: 1: #if, elif, else应用 2: num = input("Please enter a number:") 3: num = int(num) 4: if num > 0: 5: print ('You input a positive number!') 6: elif num < 0: 7: print ('You input a negative number!') 8: else: 9: print ('You input a zero!')10:
4.5 嵌套代码块说明:在if判断后,还需要进一步进行判断就可以使用嵌套代码的方式。例子: 1: key = input("Please select type, color(c) or number(n):") 2: if key == 'c': 3: color = input ("Please select a color, Red(r), Green(g), Blue(b):") 4: if color == 'r': 5: print('You selected red') 6: elif color == 'g': 7: print('You selected green') 8: elif color == 'b': 9: print('You selected blue')10: else:11: print("Illegal color type!")12: else:13: print ("You select number!")14:
4.6 更复杂的条件?4.6.1 比较运算符说明: 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中;
注意: 比较运算符是可连接的,例如:14 < age < 26;比较运算符不能比较不同类型的数据;
4.6.2 相等运算符说明:用来判断两个数据是否相等;
4.6.3 同一性运算符说明:用于判断两个变量是否指向同一对象;注意:避免把 is 比较运算符应用于比较常量值,如数字,字符串等。 即 避免以下比较:1: if '123' is '123':
4.6.4 成员资格运算符说明:判断元素是否被包含在对象中;
4.6.5 字符串和序列比较说明:字符串可以按照字母顺序排列进行比较;
4.6.6 布尔运算符说明:包括,and, or, not例子: 1: #or的特殊用法,如果没有输入,则会返回or后面的值 2: >>> name = input("Please enter a name:") or '<unknown>' 3: Please enter a name: 4: >>> name 5: '<unknown>' 6: 7: >>> a = 'a' 8: >>> c = 'c' 9: #如果if后面的判断语句为真,返回a10: >>> a if True else c11: 'a'12: #如果if后面的判断语句为假,返回c13: >>> a if False else c14: 'c'15: >>>16:
4.7 断言说明:关键字为 assert , 如果断言的条件判断为假,则程序直接崩溃例子: 1: >>> age = 10 2: >>> assert 1<age<120, "Age must be realistic" 3: >>> age = -1 4: >>> assert 1<age<120, "Age must be realistic" 5: Traceback (most recent call last): 6: File "<pyshell#26>", line 1, in <module> 7: assert 1<age<120, "Age must be realistic" 8: AssertionError: Age must be realistic 9: >>>10:
5 循环?5.1 while循环说明:关键字 while ,判断条件为真就一直执行例子:1: name = ''2: while not name.strip():3: name = input("Please input your name:")4: print("Hello,", name)
5.2 for循环说明:可以用于迭代集合中的每个元素;例子: 1: #遍历列表中的各个元素 2: >>> x = [1,2,3,4,5] 3: >>> for number in x: 4: print (number) 5: 1 6: 2 7: 3 8: 4 9: 510: >>> 11: 12: #使用内建函数range13: >>> x = range(10)14: >>> x15: range(0, 10)16: >>> for number in x:17: print(number)18: 019: 120: 221: 322: 423: 524: 625: 726: 827: 928: >>> 29:
5.3 循环遍历字典元素说明:通过keys遍历字典,或者通过values;例子:1: x = {'a':'1', 'b':'2', 'c':'3'}2: for key in x.keys():3: print (key, x[key])4: 5: for val in x.values():6: print(val)7:
5.4 一些迭代工具?5.4.1 并行迭代说明:zip内置函数可以将多个序列“压缩”成一个元组的序列;例子: 1: >>> x = list(range(0,5)) 2: >>> y = list(range(5,10)) 3: >>> z = list(range(10, 15)) 4: >>> z 5: [10, 11, 12, 13, 14] 6: >>> y 7: [5, 6, 7, 8, 9] 8: >>> x 9: [0, 1, 2, 3, 4]10: 11: >>> zipped = zip(x, y, z)12: >>> list(zipped)13: [(0, 5, 10), (1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]14: >>> 15:
5.4.2 编号迭代说明:使用内建函数enumerate来进行迭代操作;例子: 1: >>> mylist = ['12312', '12ab', '123sa', '1231s'] 2: >>> for index, string in enumerate(mylist): 3: print(index, string) 4: 5: 6: 0 12312 7: 1 12ab 8: 2 123sa 9: 3 1231s10: >>> 11:
5.4.3 翻转和排序迭代说明:内建函数reversed用于翻转序列,内建函数sorted用于对序列排 序,他们都是返回操作后的序列,不对原序列进行修改;例子:1: >>> data = [1,67,1,13,14,61,2]2: >>> sorted(data)3: [1, 1, 2, 13, 14, 61, 67]4: >>> list(reversed(data))5: [2, 61, 14, 13, 1, 67, 1]6: >>> 7:
5.5 跳出循环?5.5.1 break说明:符合条件时直接中断循环;例子:1: >>> import math2: >>>for x in range(99, 0, -1):3: >>> root = math.sqrt(x)4: >>> if root == int(root):5: >>> print ('Max number is:', x)6: >>> break7: 8: Max number is 819:
5.5.2 continue说明:结束当前循环,并跳到下一轮循环开始;例子: 1: #一个打印偶数的例子,不加else 语句,程序也能正确执行 2: >>> for x in range(10): 3: if x%2 == 0: 4: print(x) 5: else: 6: continue 7: 8: 9: 010: 211: 412: 613: 814: >>> 15:
5.5.3 while True/break说明:while True部分实现了一个永不停止的循环,由内部的if判断语 句控制跳出循环;例子: 1: while True: 2: word = input("Please enter a word:") 3: if not word: 4: break 5: print("You input:" , word) 6: 7: Please enter a word:TEst 8: You input: TEst 9: Please enter a word:ls10: You input: ls11: Please enter a word:12: >>> 13:
5.5.4 循环中的else子句说明:else子句可以用于判断循环操作是否始终没有执行break操作。例子: 1: #设置一个奇数序列,判断里面是不是有偶数(一个蛋疼的程序,哈哈) 2: x = list(range(1,100,2)) 3: for val in x: 4: if val%2 == 0: 5: print (x) 6: break; 7: else: 8: print("Did not break!") 9: #执行结果10: Did not break!11:
6 列表推导式说明:利用其他列表创建列表,利用for循环遍历序列,将元素执行相应的 操作;例子:1: #得到10以内数字的平方的列表2: import math3: mylist = [math.pow(x, 2) for x in list(range(0,10))]4: print (mylist)5: 6: #得到10以内偶数的平方的列表7: mylist = [math.pow(x, 2) for x in list(range(0,10)) if x % 2 == 0]8: print (mylist)9:
7 三人行?7.1 pass说明:pass关键字用于占位,当函数或者代码块还没有添加时,可以用 pass来占位,以免语法错误例子1: >>> a = 102: #if的语句块中并没有其他语句需要执行,先用pass占位,执行的时候,如果if判断为真直接跳过。3: >>> if a>0:4: pass5: >>>
7.2 del说明:用于删除对象;注意:del仅能删除变量或者对象中的项,不能直接删除变量指向的对象, 当对象没有被任何变量引用时,python会将变量回收;例子: 1: >>> x = {'a':'1', 'b':'2', 'c':'3'} 2: >>> y = x 3: >>> y 4: {'a': '1', 'c': '3', 'b': '2'} 5: #删除变量x,再调用会报“未定义”的错误 6: >>> del x 7: >>> x 8: Traceback (most recent call last): 9: File "<pyshell#15>", line 1, in <module>10: x11: NameError: name 'x' is not defined12: >>> y13: {'a': '1', 'c': '3', 'b': '2'}14: #删除字典中的项15: >>> del y['a']16: >>> y17: {'c': '3', 'b': '2'}18: >>> 19:
7.3 exec和eval说明: exec用于执行一个字符串的语句;eval用于执行字符串语句,并返回语句执行的结果;
注意:通过增加字典,起到命名空间的作用,以防止由字符串的语句导致 的安全问题;例子 1: #exec直接执行语句 2: >>> exec('print("Hello, world!")') 3: Hello, world! 4: #exec执行后不返回执行结果 5: >>> exec("2*2") 6: >>> 7: #exec在命名空间中执行语句 8: >>> exec(""" 9: x=210: y=311: z=412: """, scope)13: >>> scope.keys()14: dict_keys(['__builtins__', 'x', 'z', 'y'])15: >>> scope['x']16: 217: >>> 18: 19: #eval直接执行语句20: >>> eval('print("Hello, world!")')21: Hello, world!22: #eval在执行后将执行结果返回23: >>> eval('2*2')24: 425: >>> 26: #eval操作字典中的数据27: >>> scope.keys()28: dict_keys(['__builtins__', 'x', 'z', 'y'])29: >>> eval('x+y+z', scope)30: 931: >>> 32:
1: >>> greeting = 'Hello' 2: >>> salution = 'Mr.' 3: >>> name = 'Bill' 4: #以逗号分隔输出项 5: >>> print(greeting, salution, name) 6: Hello Mr. Bill 7: #在逗号前增加了一个空格符 8: >>> print(greeting, ',', salution, name) 9: Hello , Mr. Bill10: #为了显示成'Hello, Mr. Bill'这个样式,可以使用连接符‘+’11: >>> print(greeting + ',', salution, name)12: Hello, Mr. Bill13: >>>14:
- 将整个模块导入,格式为:import somemodule;从某个模块中导入某个函数,格式为:from somemodule import somefunction;从某个模块中导入多个函数,格式为:from somemodule import firstfunc, secondfunc, thirdfunc将某个模块中的全部函数导入,格式为:from somemodule import *
1: #第一种导入方法 2: #导入模块 3: import module1 4: import module2 5: #调用同名函数的方法 6: module1.open() 7: module2.open() 8: 9: #第二种导入方法10: #导入函数,并给函数取相应的别名11: from module1 import open as open112: from module2 import open as open213:例子:
1: #从math中导入sqrt 2: >>> from math import sqrt as msqrt 3: #从cmath中导入sqrt 4: >>> from cmath import sqrt as csqrt 5: >>> msqrt(100) 6: 10.0 7: >>> csqrt(-1) 8: 1j 9: >>>10:
1: #一般的同时赋值操作 2: >>> x, y, z = (1,2,3) 3: >>> x 4: 1 5: >>> y 6: 2 7: >>> z 8: 3 9: >>>10: 11: #从字典中弹出任意一对儿键值对儿,并赋值给两个变量12: >>> people = {'first': 'Andy', 'second':'Bill'}13: >>> key, value = people.popitem()14: >>> key15: 'second'16: >>> value17: 'Bill'18: >>>19: 1: #链式赋值 2: >>> x=y=z=1 3: >>> x 4: 1 5: >>> y 6: 1 7: >>> z 8: 1 9: >>>10:
- +=:将右侧的值加到变量上的和,然后再赋值给变量;-=:将变量减去右侧的值得到的差,再赋值给变量;/=:用变量除以右侧值得到的商,再赋值给变量;%=:用变量取右侧值的余数,再赋值给变量;
1: #针对数字的各种操作 2: >>> x = 123 3: >>> x += 1 4: >>> x 5: 124 6: >>> x -= 4 7: >>> x 8: 120 9: >>> x *=210: >>> x11: 24012: >>> x /=313: >>> x14: 80.015: >>> x %=916: >>> x17: 8.018: >>>19: 20: #字符串的增量赋值21: >>> y = 'Test string'22: >>> y += ', haha!'23: >>> y24: 'Test string, haha!'25: >>> y *= 226: >>> y27: 'Test string, haha!Test string, haha!'28: >>>29:
- 假值:false,None,所有类型的数字0,空序列,空字典;真值:所有的非空值;bool函数可以用来将其他值转换成布尔值;
1: >>> True 2: True 3: >>> False 4: False 5: >>> [] 6: [] 7: >>> bool ([]) 8: False 9: >>> bool ([1,])10: True11: >>> bool (0)12: False13: >>> bool (0.0)14: False15: >>> bool (0.1)16: True17: #不同的假值之间也是不相同的18: >>> [] == {}19: False20: >>> [] == None21: False22: >>>23: 1: #if, elif, else应用 2: num = input("Please enter a number:") 3: num = int(num) 4: if num > 0: 5: print ('You input a positive number!') 6: elif num < 0: 7: print ('You input a negative number!') 8: else: 9: print ('You input a zero!')10: 1: key = input("Please select type, color(c) or number(n):") 2: if key == 'c': 3: color = input ("Please select a color, Red(r), Green(g), Blue(b):") 4: if color == 'r': 5: print('You selected red') 6: elif color == 'g': 7: print('You selected green') 8: elif color == 'b': 9: print('You selected blue')10: else:11: print("Illegal color type!")12: else:13: print ("You select number!")14: - 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中;
- 比较运算符是可连接的,例如:14 < age < 26;比较运算符不能比较不同类型的数据;
1: if '123' is '123':
1: #or的特殊用法,如果没有输入,则会返回or后面的值 2: >>> name = input("Please enter a name:") or '<unknown>' 3: Please enter a name: 4: >>> name 5: '<unknown>' 6: 7: >>> a = 'a' 8: >>> c = 'c' 9: #如果if后面的判断语句为真,返回a10: >>> a if True else c11: 'a'12: #如果if后面的判断语句为假,返回c13: >>> a if False else c14: 'c'15: >>>16: 1: >>> age = 10 2: >>> assert 1<age<120, "Age must be realistic" 3: >>> age = -1 4: >>> assert 1<age<120, "Age must be realistic" 5: Traceback (most recent call last): 6: File "<pyshell#26>", line 1, in <module> 7: assert 1<age<120, "Age must be realistic" 8: AssertionError: Age must be realistic 9: >>>10:
1: name = ''2: while not name.strip():3: name = input("Please input your name:")4: print("Hello,", name)1: #遍历列表中的各个元素 2: >>> x = [1,2,3,4,5] 3: >>> for number in x: 4: print (number) 5: 1 6: 2 7: 3 8: 4 9: 510: >>> 11: 12: #使用内建函数range13: >>> x = range(10)14: >>> x15: range(0, 10)16: >>> for number in x:17: print(number)18: 019: 120: 221: 322: 423: 524: 625: 726: 827: 928: >>> 29:
1: x = {'a':'1', 'b':'2', 'c':'3'}2: for key in x.keys():3: print (key, x[key])4: 5: for val in x.values():6: print(val)7: 1: >>> x = list(range(0,5)) 2: >>> y = list(range(5,10)) 3: >>> z = list(range(10, 15)) 4: >>> z 5: [10, 11, 12, 13, 14] 6: >>> y 7: [5, 6, 7, 8, 9] 8: >>> x 9: [0, 1, 2, 3, 4]10: 11: >>> zipped = zip(x, y, z)12: >>> list(zipped)13: [(0, 5, 10), (1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)]14: >>> 15:
1: >>> mylist = ['12312', '12ab', '123sa', '1231s'] 2: >>> for index, string in enumerate(mylist): 3: print(index, string) 4: 5: 6: 0 12312 7: 1 12ab 8: 2 123sa 9: 3 1231s10: >>> 11:
1: >>> data = [1,67,1,13,14,61,2]2: >>> sorted(data)3: [1, 1, 2, 13, 14, 61, 67]4: >>> list(reversed(data))5: [2, 61, 14, 13, 1, 67, 1]6: >>> 7:
1: >>> import math2: >>>for x in range(99, 0, -1):3: >>> root = math.sqrt(x)4: >>> if root == int(root):5: >>> print ('Max number is:', x)6: >>> break7: 8: Max number is 819: 1: #一个打印偶数的例子,不加else 语句,程序也能正确执行 2: >>> for x in range(10): 3: if x%2 == 0: 4: print(x) 5: else: 6: continue 7: 8: 9: 010: 211: 412: 613: 814: >>> 15:
1: while True: 2: word = input("Please enter a word:") 3: if not word: 4: break 5: print("You input:" , word) 6: 7: Please enter a word:TEst 8: You input: TEst 9: Please enter a word:ls10: You input: ls11: Please enter a word:12: >>> 13: 1: #设置一个奇数序列,判断里面是不是有偶数(一个蛋疼的程序,哈哈) 2: x = list(range(1,100,2)) 3: for val in x: 4: if val%2 == 0: 5: print (x) 6: break; 7: else: 8: print("Did not break!") 9: #执行结果10: Did not break!11: 1: #得到10以内数字的平方的列表2: import math3: mylist = [math.pow(x, 2) for x in list(range(0,10))]4: print (mylist)5: 6: #得到10以内偶数的平方的列表7: mylist = [math.pow(x, 2) for x in list(range(0,10)) if x % 2 == 0]8: print (mylist)9:
1: >>> a = 102: #if的语句块中并没有其他语句需要执行,先用pass占位,执行的时候,如果if判断为真直接跳过。3: >>> if a>0:4: pass5: >>>
1: >>> x = {'a':'1', 'b':'2', 'c':'3'} 2: >>> y = x 3: >>> y 4: {'a': '1', 'c': '3', 'b': '2'} 5: #删除变量x,再调用会报“未定义”的错误 6: >>> del x 7: >>> x 8: Traceback (most recent call last): 9: File "<pyshell#15>", line 1, in <module>10: x11: NameError: name 'x' is not defined12: >>> y13: {'a': '1', 'c': '3', 'b': '2'}14: #删除字典中的项15: >>> del y['a']16: >>> y17: {'c': '3', 'b': '2'}18: >>> 19: - exec用于执行一个字符串的语句;eval用于执行字符串语句,并返回语句执行的结果;
1: #exec直接执行语句 2: >>> exec('print("Hello, world!")') 3: Hello, world! 4: #exec执行后不返回执行结果 5: >>> exec("2*2") 6: >>> 7: #exec在命名空间中执行语句 8: >>> exec(""" 9: x=210: y=311: z=412: """, scope)13: >>> scope.keys()14: dict_keys(['__builtins__', 'x', 'z', 'y'])15: >>> scope['x']16: 217: >>> 18: 19: #eval直接执行语句20: >>> eval('print("Hello, world!")')21: Hello, world!22: #eval在执行后将执行结果返回23: >>> eval('2*2')24: 425: >>> 26: #eval操作字典中的数据27: >>> scope.keys()28: dict_keys(['__builtins__', 'x', 'z', 'y'])29: >>> eval('x+y+z', scope)30: 931: >>> 32: Date: 2011-11-23 20:40:47
Org version 7.7 with Emacs version 23
Validate XHTML 1.0