python 程序设计语言 笔记(三)

原文地址: https://blog.csdn.net/longteng007/article/details/50990746

第三周 分支与循环

      3.1 程序基本结构

1. 程序流程图 — 用规定的一系列图形、流程线和文字说明算法中的基本操作和控制流程。

    流程图的基本元素包括:

(1)表示相应操作的框

(2)带箭头的流程线

(3)框内外必要的文字说明

        2. 设计程序框图的步骤:

        (1)用自然语言表述算法步骤

        (2)确定步骤逻辑结构,用相应框图表示

        (3)流程线连接框图,加上终端框,得到整个算法的程序框图

3. 任何算法都可以由顺序、选择、循环三种基本结构组合实现:

 

(1)顺序结构:按逻辑顺序自上而下依次运行的结构,如:温度转换程序;

(2)选择结构分支结构):在算法中通过对条件的判断,根据条件是否成立而选择不同流向的算法结构;

(3)循环结构:指在一定条件下反复执行某部分代码的操作;

3.2 简单分支

        例:

PM2.5指数分级程序功能IPO模式描述:

              输入:接受外部输入PM2.5值

              处理:空气质量分级算法

              输出:打印空气质量提醒

          PM2.5指数分级伪代码

              If PM2.5值> 75

                     打印空气污染警告

              If PM2.5值< 35

                     打印空气质量优,建议户外运动

          流程图如图所示:

程序5:


  
  
  1. #pm25.py
  2. #空气质量提醒
  3. def main():
  4. PM = eval(input( "What is today'sPM2.5? "))
  5. # 打印相应提醒
  6. if PM > 75:
  7. print( "Unhealthy. Becareful!")
  8. if PM < 35:
  9. print( "Good. Go running!")
  10. main()

【运行结果】

输出:                         输入:

What is today'sPM2.5?     90

Unhealthy. Becareful!

(1)If语句格式:

If <condition>:

<body>

【注】<condition>是条件表达式,<body>是一个或多个语句序列

先判断<condition>条件,若true,则执行<body>,再转向下一条语句;

若false,则直接跳过<body>,转向下一条语句

(2)简单条件构造

   ① 简单条件基本形式 <expr><relop> <expr>

   ② <relop>是关系操作符<, <=, ==, >=, >, !=

   ③ 使用“=”表示赋值语句,使用“==”表示等于

    ④ 除数字外,字符或字符串也可以按照字典顺序用于条件比较

   ⑤ <condition>是布尔表达式,为bool类型

布尔值的真假以True和False表示

        (3)二分支语法结构

If <condition>:

                                         <statements>

else:

                                         <statements>

程序6:


  
  
  1. # quadratic.py
  2. # 计算二次方程的实数根程序
  3. import math
  4. def main():
  5. print( "Thisprogram finds the real solutions to a quadratic\n")
  6. a,b,c =eval(input( "Please enter the coefficients(a,b,c): "))
  7. delta = b*b -4*a*c
  8. if delta >= 0:
  9. discRoot =math.sqrt(delta)
  10. root1 = (-b +discRoot) / ( 2*a)
  11. root2 = (-b -discRoot) / ( 2*a)
  12. print( "\nThe solutions are:", root1, root2)
  13. else:
  14. print( "Theequation has no real roots!")
  15. main()

【运行结果】

输出:

This program finds the real solutions to a quadratic

                                                                             输入:

Please enter the coefficients(a,b,c):                      1,2,3

The equation has no real roots!

3.3 多分支

(1)多分支决策

要解决双根问题,就需要对delta等于0的情况进行处理。

语句的结构上要引入嵌套结构:

① 当delta < 0,处理无实根情况

② 当delta = 0,处理实根情况

③ 当delta > 0,处理双根情况

一种方案是在程序中使用两个if-else语句。

把一个复合语句放到另一个语句的结构之中称为嵌套。

1. 多分支决策是解决复杂问题的重要手段之一

2. 一个三分之决策可以由两个二分支结构嵌套实现

3. 使用if-else描述多分支决策时,

实现更多分支需要更多嵌套,影响程序易读性

Python使用if-elif-else描述多分支决策,简化分支结构的嵌套问题。

格式如下:

If <condition1>:

                            <case1 statements>

elif<condition2>:

                            <case2 statements>

elif<condition3>:

                            <case3 statements>

else:

                            <default statements>

例:程序7:


  
  
  1. # quadratic.py
  2. import math
  3. def main():
  4. print( "This program finds the realsolutions to a quadratic\n")
  5. a,b,c =eval(input( "Please enter the coefficients(a,b,c): "))
  6. delta = b*b - 4*a*c
  7. if a == 0:
  8. x = -b/c
  9. print( "\nThere is ansolution", x)
  10. elif delta < 0:
  11. print( "\nThe equation has no real roots!")
  12. elif dalta == 0:
  13. x = -b/( 2*a)
  14. print( "\nTheere is a double rootat", x)
  15. else:
  16. discRoot = math.sqrt(delta)
  17. root1 = (-b +discRoot) / ( 2*a)
  18. root2 = (-b -discRoot) / ( 2*a)
  19. print( "\nThesolutions are:", root1, root2)
  20. main()

3.4 异常处理

        异常处理语句

              Python使用try…except…,可使程序不因运行错误而崩溃

Python的异常处理语句还可以使用else和finally关键字

可选项,若使用则else必须在finally之前)

格式如下:

try:

                                  <body>

except<ErrorType1>:

                                  <handler1>

except<ErrorType2>:

                                   <handler2>

except:

                                   <handler0>

                            else:

                                  <process_else>

                            finally:

                                  <process_finally>

              try…except可以捕捉任何类型的错误

对于二次方程,还会有其他可能的错误

如:输入非数值类型(NameError)

输入无效的表达式(SyntaxError)等

                此时可以用一个try语句配多个except来实现

程序8:


  
  
  1. # 异常处理测试
  2. def main():
  3. try:
  4. number1,number2 = eval(input( "Enter two numbers,
  5. separated by a comma:"))
  6. result = number1/number2
  7. exceptZeroDivisionError:
  8. print( "Division by zero!")
  9. exceptSyntaxError:
  10. print( "Acomma may be missing in the input")
  11. else:
  12. print( "Noexceptions, the result is", result)
  13. finally:
  14. print( "executing the final clause")
  15. main()

【运行结果】

输出:                                                            输入:

Enter two numbers, separated by a comma: 1 2

A comma may be missing in the input

executing the final clause

 

Enter two numbers, separated by a comma: 3,2

No exceptions, the result is 1.5

executing the final clause

 

Enter two numbers, separated by a comma: 3,0

Division by zero!

executing the final clause

猜你喜欢

转载自blog.csdn.net/qq_36369267/article/details/82831608