ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
前面的学习过程中,我们都是在IDLE中运行单条的代码。但在编程过程中,我们可能希望在某时重复执行某条代码,或选择性执行某几条代码等。此时,我们便需要借助流程控制语句来实现对程序运行流程的选择、循环和返回等进行控制。 ***** [TOC] **** # 3.1 布尔值与布尔操作符和比较操作符 **布尔(Boolean)数据类型** 只有两种值:True 和 False。 ``` >>> test = True >>> test True >>> True True >>> true Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> true NameError: name 'true' is not defined >>> True = False SyntaxError: can't assign to keyword ``` 如上:两种布尔值,首字母必须大写,它们是关键字,不可用作变量名。 **布尔操作符和比较操作符** 布尔操作符: ``` >>> True and True True >>> True and False False >>> False or True True >>> False or False False >>> not True False >>> not False True ``` 比较操作符: ``` >>> 100 == 100 True >>> 23 > 32 False >>> 'hello' == 'hello' True >>> 'Hello' == 'hello' False >>> True != False True >>> 55 == 55.0 True >>> 55 == '55' False ``` 混合布尔和比较操作符: ``` >>> (2 < 5) and (6 < 7) True >>> (2 < 5) and (6 < 4) False >>> (1 == 2) or (2 == 2) True >>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 True ``` **** # 3.2 代码块与作用域 在 Python 中,通过缩进来表示代码块和作用域,即相同缩进范围内的代码在一个代码块和作用域中,且同一代码块和作用域中不能有不同的缩进。Python 中用冒号“:”标记同一代码块。如下: ``` if True: print('Hello') print('Python') ``` 在使用代码块的过程中,可以用 `pass` 占位符来占据代码块位置,以便后续添加代码。如下: ``` if True: pass ``` **** # 3.3 if 语句 **简单的 if 语句:** 语法: ``` if conditional_test: do something ``` 示例: ``` age = input('请输入你的年龄:') if int(age) >= 18: print('恭喜你,你成年了哎。') ``` ``` # Out: 请输入你的年龄:19 恭喜你,你成年了哎。 ``` **if-else 语句:** 语法: ``` if conditional_test: do something else: do other thing ``` 示例: ``` name = input('Please type your name:') if name == 'your name': print('Success.') else: print('Error.') ``` ``` # Out: Please type your name:your name Success. ``` **if-elif-else 结构:** 示例: ``` num = 66 guessNum = int(input('请输入你猜测的数字: ')) if guessNum < num: print('猜小了。') elif guessNum == num: print('猜对了。') elif guessNum > num: print('猜大了。') else: print('你看不到我!') ``` **if三元操作符** ``` x = int(input('Please input a number for x:')) y = int(input('Please input a number for y:')) smaller = x if x < y else y print('The smaller number is:', smaller) ``` ``` # Out: Please input a number for x:16 Please input a number for y:15 The smaller number is: 15 ``` **** # 3.4 while 循环 语法: ``` while expression: repeat_block ``` 其语意为:判断 expression 表达式,如果表达式为真,则执行 repeat_block 并再次判断 expression,直到 expression 返回假为止。 示例: ``` i = 1 while i <= 5: print('第' + str(i) + '遍:') print('Hello Python!\n') i += 1 ``` ``` # Out: 第1遍: Hello Python! 第2遍: Hello Python! 第3遍: Hello Python! 第4遍: Hello Python! 第5遍: Hello Python! ``` *如果 expression 一直为真,程序将永远无法退出 repeat_block 的执行,即陷入死循环。* **** # 3.5 for 循环 语法: ``` for element in iterable: repeat_block ``` `for/in` 是关键字,语意为:针对 iterable 中的每个元素执行 repeat_block,在 repeat_block 中可以使用 element 变量名来访问当前元素。iterable 可以是Sequence序列类型、集合或迭代器等。 循环读取列表元素: ``` fruits = ['apple', 'banana', 'orange', 'pear', 'grape'] for fruit in fruits: print('Current fruit is: ', fruit) ``` ``` # Out: Current fruit is: apple Current fruit is: banana Current fruit is: orange Current fruit is: pear Current fruit is: grape ``` 循环读取字典元素: ``` d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key in d: print(key) print('\n******\n') for key in d.keys(): print(key) print('\n******\n') for value in d.values(): print(value) print('\n******\n') for key, value in d.items(): print(key, "::", value) ``` ``` # Out: a b c d ****** a b c d ****** 1 2 3 4 ****** a :: 1 b :: 2 c :: 3 d :: 4 ``` **** # 3.6 else 子句 for和while复合语句可以选择使用else子句(实际上,这种用法相当少见)。 else子句只在for循环通过迭代结束后执行,或在while循环通过其条件表达式变为False终止后执行。 ``` for i in range(3): print(i) else: print('done') ``` ``` # Out: 0 1 2 done ``` ``` i = 0 while i < 3: print(i) i += 1 else: print('done') ``` ``` # Out: 0 1 2 done ``` **** # 3.7 break 和 continue `break语句`:在循环中,如果执行到了 break 语句,将结束该循环。 ``` i = 0 while i < 8: print(i) if i == 4: print("Breaking from loop") break i += 1 ``` ``` # Out: 0 1 2 3 4 Breaking from loop ``` `continue语句` :在循环中,如果执行到了 continue 语句,将跳回到循环开始处,重新对循环条件求值。 ``` for i in (0, 1, 2, 3, 4, 5): if i == 2 or i == 4: continue print(i) ``` ``` # Out: 0 1 3 5 ``` **** # 3.8 语句嵌套 Python 中,if、while、for等语句可相互嵌套。 如下,实现一个简单的排序算法: ``` lst = [2, 3, 0, -12, 55, 7, 4, 66] print('Before sorting:') print(lst) lenLst = len(lst) for i in range(0, lenLst - 1): for j in range(i + 1, lenLst - 1): if lst[i] > lst[j]: lst[i], lst[j] = lst[j], lst[i] print('After sorting:') print(lst) ``` ``` # Out: Before sorting: [2, 3, 0, -12, 55, 7, 4, 66] After sorting: [-12, 0, 2, 3, 4, 7, 55, 66] ```