Python程序的流程
1 """ 2 python程序的流程 3 """ 4 # ------------- 分支结构---------------- 5 # if else 6 import math 7 8 x = -37 9 if x < 0: 10 y = math.fabs(x) 11 else: 12 y = math.sqrt(x) 13 print("计算的结果是:", y) 14 15 # if...elif...else 16 # month = eval(input("请输入你选择的月份:")) # eval() 函数用来执行一个字符串表达式,并返回表达式的值 17 month = 12 18 days = 0 19 20 if (month == 1 or month == 3 or month == 5 or month == 7 21 or month == 8 or month == 10 or month == 12): 22 days = 31 23 elif month == 4 or month == 6 or month == 9 or month == 11: 24 days = 30 25 else: 26 days = 28 27 print("{}月份的天数为{}".format(month, days)) 28 29 # 分支嵌套 30 flag = 1 31 books = 8 32 price = 234 33 Acp = 0 34 35 if flag == 1: 36 if books >= 5: 37 Acp = price * 0.75 * books 38 else: 39 Acp = price * 0.85 * books 40 else: 41 if books >= 5: 42 Acp = price * 0.85 * books 43 else: 44 Acp = price * 0.95 * books 45 print("你的实际付款金额是:", Acp) 46 47 # ------------循环结构--------------- 48 49 # 遍历循环:for 50 ''' 51 for <var> in <seq>: 52 <statements> 53 var是一个变量 54 seq是一个序列,可以是字符串、列表、文件或range()函数 55 56 range()函数 57 range(start,stop,[,step]) 58 start:默认从0开始 59 stop:默认到stop结束,但不包括stop 60 step:默认为1 61 ''' 62 # 计算1-100中能被3整除数之和 63 s = 0 64 for i in range(1, 101, 1): 65 if i % 3 == 0: 66 s += i 67 # print(i) 68 print(s) 69 70 71 # 计算 1!+2!+...+5! 72 def factorial(n): 73 t = 1 74 for v in range(1, n + 1): 75 t = t * v 76 return t 77 78 79 k = 6 80 sum1 = 0 81 for j in range(1, k): 82 sum1 += factorial(j) 83 print("1!+2!+...+5!=", sum1) 84 85 # 条件循环语句while 86 """ 87 while <boolCondition> 88 <statements> 89 """ 90 91 lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 92 head = 0 93 tail = len(lst) - 1 94 while head < len(lst) / 2: # TypeError: object of type 'type' has no len()/报错,需修改 95 lst[head], lst[tail] = lst[tail], lst[head] # 头尾互换? 96 """ 97 也可以用下面语句来进行头尾互换 98 temp = list[head] 99 lst[head] = list[tail] 100 lst[tail] = temp 101 """ 102 head += 1 103 tail -= 1 104 105 for item in lst: 106 print(item, end=' ') 107 108 # 用for循环改写 109 lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 110 head = 0 111 tail = len(lst) - 1 112 for head in range(0, int(len(lst) / 2)): # 因为range()函数的参数必须是整数,所以用int()函数进行了转换 113 lst[head], lst[tail] = lst[tail], lst[head] # 头尾互换? 114 """ 115 也可以用下面语句来进行头尾互换 116 temp = list[head] 117 lst[head] = list[tail] 118 lst[tail] = temp 119 """ 120 head += 1 121 tail -= 1 122 123 for item in lst: 124 print(item, end=' ') 125 print() 126 127 # ------------跳转语句---------------- 128 """ 129 break语句的作用是从循环体内跳出,及结束循环 130 """ 131 a = 99 132 i = a // 2 133 while i > 0: 134 if a % i == 0: 135 break 136 i -= 1 137 print(a, "的最大真约数:", i) 138 139 """ 140 continue语句必须用于循环结构中,它的作用是终止当前的这一轮循环,跳过本轮剩余的语句,直接进入下一循环 141 """ 142 s = [-1, -2, -3, -4, 5, 6, 7, 8, 9] 143 for i in range(9): 144 if s[i] < 0: 145 continue 146 print("{}是正数".format(s[i])) 147 148 # 打印金字塔 149 # n = eval(input("请输入打印的行数")) 150 n = 5 151 for i in range(1, n + 1): 152 print(' ' * (n - i) + '*' * (2 * i - 1)) # 感觉这个print函数都够学的了