任何算法(程序)都可以由顺序结构、 选择结构和循环结构这三种基本结构组合来实现。
1、顺序结构
顺序结构中,按语句的自然顺序依次执行。
2、选择结构
(1)多分支决策:if-else。这是简单分之结构,
1 import math
2 def main():
3 print("求二次方程的实根\n")#换行,反斜杠和n
4 a,b,c=eval(input("输入二次函数的系数(a,b,c):"))#用逗号隔开,同时输入三个数
5 delt=b**2-4*a*c
6 if delt>0:
7 delt=math.sqrt(b**2-4*a*c)
8 root1=(-b+delt)/(2*a)
9 root2=(-b-delt)/(2*a)
10 print("二次函数的实根为:",root1,root2)
11 # print("二次函数的实根为root1=%f,root2=%f:"%root1,%root2) 编译不通,留看
12 elif delt==0:
13 delt=math.sqrt(delt)
14 root1=(-b+delt)/(2*a)
15 print("相同的实根",root1)
16 else:
17 print('没有实根')
18
19 main()
if-elif-elif-else 多个互斥的判断语句
(2)
1 from math import *
2 def main():
3 print("二次方程求根方法")
4 a,b,c=eval(input("输入系数:"))
5 delta=b**2-4*a*c
6 if delta<0:
7 print("方程没有实根")
8 else:
9 if delta==0:
10 root=-b/2*a
11 print("相同的实根",root)
12 else delta>0:
13 delta=sqrt(delta)
14 root1=(-b+delta)/(2*a)
15 root2=(-b-delta)/(2*a)
16 print("实根为:",root1,root2)
17
18 main()
这是from math import *这种形式,调用函数不用前面加库名;再有体会if-if-if、if-else嵌套if-else 形式和if-elif-elif-else形式区别
3、异常处理机制
如果处理错误或特殊情况的分支语句过多,那么处理正常情况的主程序就会变得不清晰
(1)
1 def main():
2 try:
3 number1,number2=eval(input("enter two number,separated by a comma\n"))
4 result=number1/number2
5
6 except ZeroDivisionError:
7 print("Division by zero!")
8 except SyntaxError:
9 print("A comma may be missing in the input")
10 except :
11 print("Something wrong in the input")
12 else:
13 print("No excepting,the result is",result)
14 finally:
15 print("executing the final clause")
16 main()
从这段代码中可以看出,try-except的执行顺序,先执行try中的内容,如果没有错误,执行else和finally中内容;如果出错,执行except内容,最后执行finally内容。
(2)将try-except 加入二次方程根代码
1 import math
2 def main():
3 print('this program finds the real solutions to a quadratic')
4 try:
5 a,b,c=eval(input("please enter the coefficients(a,b,c)\n"))
6 discroot=math.sqrt(b*b-4*a*c)
7 root1=(-b+discroot)/(2*a)
8 root2=(-b-discroot)/(2*a)
9 print("the solutions are:",root1,root2)
10 except:
11 print("some thing went trong")
12
13 main()
(3)标准异常
1 import math
2 def main():
3 print('this program finds the real solutions to a quadratic')
4 try:
5 a,b,c=eval(input("please enter the coefficients(a,b,c)\n"))
6 discroot=math.sqrt(b*b-4*a*c)
7 root1=(-b+discroot)/(2*a)
8 root2=(-b-discroot)/(2*a)
9 print("the solutions are:",root1,root2)
10 except ValueError as exc0bj:
11 if str(exc0bj)=="math domain error":
12 print("No real roots")
13 else:
14 print("you didn't give me the right number of codfficients")
15 except NameError:
16 print("you didn't enter three numbers")
17 except TypeError:
18 print("you input was not the correct form")
19 except:
20 print("some thing went trong")
21
22 main()
4、分支结构——数值比较
(1)四个数值比较
<1>通盘比较 :每个数与其他数全部比较
1 import math
2 import time
3
4 def main():
5 try:
6 a,b,c,d=eval(input("enter four numbers:\n"))
7 time.clock()
8 if a>=b and a>=c and a>=d:
9 print("max=",a)
10 elif b>=a and b>=c and b>=d:
11 print("max=",b)
12 elif c>=a and c>=b and c>=d:
13 print("max=",c)
14 else:
15 print('max=',d)
16 except:
17 print("wrong")
18 print("time is ",time.clock())
19 main()
此种方法,在数据多时,耗时,耗内存,存在重复比较的情况。
<2>策略2:决策树
决策树方法可以避免冗余比较,先判断x1>x2,如果成立再判断x1>x3,否则判断x2>x3,虽然效率高,但设计三个以上的方案,复杂性会爆炸性地增长
1 import math
2 import time
3
4 def main():
5 try:
6 a,b,c,d=eval(input("enter four numbers:\n"))
7 time.clock()
8 if a>=b:
9 if a>=c:
10 if a>=d:
11 print("max=",a)
12 else:
13 print("max=",d)
14 else:
15 if c>=d:
16 print("max=",c)
17 else:
18 print("max=",d)
19 else:
20 if b>=c:
21 if b>=d:
22 print("max=",b)
23 else:
24 print("max=",d)
25 else:
26 if c>=d:
27 print("max=",c)
28 else:
29 print("max=",d)
30 except:
31 print("wrong")
32 print("time is ",time.clock())
33 main()
<3>顺序处理
逐个扫描每个值,保留最大者以max变量保存当前最大值,完成最后一个扫描时,max就是最大值
1 import math
2 import time
3 import random
4
5 def main():
6 try:
7 # a,b,c,d=eval(input("enter four numbers:\n"))
8 a,b,c,d=random.randint(1,100),random.randint(1,100),random.randint(1,100),random.randint(1,100)
9 print(a,b,c,d)
10 max=a
11 time.clock()
12 if max<b:
13 max=b
14 if max<c:
15 max=c
16 if max<d:
17 max=d
18 print("max=",max)
19 except:
20 print("wrong")
21 print("time is ",time.clock())
22 main()
1 import math
2 import time
3 import random
4
5 def main():
6 try:
7 a,b,c,d=eval(input("enter four numbers:\n"))
8 print(a,b,c,d)
9 max=a
10 time.clock()
11 if max<b:
12 max=b
13 elif max<c:
14 max=c
15 elif max<d:
16 max=d
17 print("max=",max)
18 except:
19 print("wrong")
20 print("time is ",time.clock())
21 main()
可以看出 if-if-if和if-elif-elif 的区别,前者是挨个向后运行,后者是只运行符合条件的。
<4>调用自带函数
1 import math
2 import time
3 import random
4
5 def main():
6 try:
7 a,b,c,d=random.randint(1,100),random.randint(1,100),random.randint(1,100),random.randint(1,100)
8 print(a,b,c,d)
9 print("max=",max(a,b,c,d))
10 except:
11 print("wrong")
12 print("time is ",time.clock())
13 main()
花费时间最短
<5>if-if-if 和 if-elif-elif-else
1 from math import *
2 from random import *
3
4 def main():
5 try:
6 a=randint(50,100)
7 print(a)
8 if a>90:
9 print("优秀")
10 elif a>80:
11 print("良好")
12 elif a>70:
13 print("一般")
14 elif a>=60:
15 print("合格")
16 else:
17 print("不合格")
18 except:
19 print("出错")
20
21 main()
from math import *
from random import *
def main():
try:
a=randint(50,100)
print(a)
if a>=90:
print("优秀")
if a>=80 and a<90:
print("良好")
if a>=70 and a<80:
print("一般")
if a>=60 and a<70:
print("合格")
if a<60:
print("不合格")
except:
print("出错")
main()
5、循环结构
(1)for 循环
Python可以使用for语句循环遍历整个序列的值
for in
(2)求平均数
1 from math import *
2 from random import *
3
4 def main():
5 try:
6 n=eval(input('数字个数:'))
7 sum=0
8 for i in range(n):
9 num=randint(0,100)
10 print(num)
11 sum=sum+num
12 print("平均值为:",sum/n)
13 except:
14 print("运行出错")
15 main()
(3)while循环无限循环
语法:while语句
while
while语句中
(4)Break 语句- 跳出最内层for/while 循环
import math
sum=0
num=0
while num<20:
num=num+1
sum=sum+num
if sum>100:
break
print("num=",num)
print("sum=",sum)
(5)for/while 中的continue用法
continue语句, 其作用为结束本次循环。即跳出循环体中下面尚未执行的语句,对于while循环,继续求解循环条件。而对于for循环程序流程接着遍历循环列表
continue语句和break语句的区别是:
continue语句只结束本次循环,而不终止整个循环的执行。而break语句则是结束整个循环过程,不再判断执行循环的条件是否成立:
1 import math
2 num=0
3 while num<10:
4 num=num+1
5 if num%2==0:
6 print("find an even number",num)
7 continue
8 print("find a number",num)
9
(6)for/while 中的else用法
Break 语句- 跳出最内层for/while 循环
件语句不满足的情况下执行,例如:
1 import math
2 def main():
3 n=eval(input("输入素数范围:"))
4 for x in range(2,n):
5 for i in range(2,x):
6 if x%i==0:
7 break
8 else:
9 print(x,"是素数")
10 main()
while/for 循环和else的使用,就是执行完循环后,再执行else;
而if-else 则是,只执行if或者else。