python 程序设计语言 笔记(三)
2016-03-27 11:17
666 查看
第三周 分支与循环
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:
#pm25.py
#空气质量提醒
def main():
PM = eval(input("What is today'sPM2.5? "))
# 打印相应提醒
if PM > 75:
print("Unhealthy. Becareful!")
if PM < 35:
print("Good. Go running!")
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:
# quadratic.py
# 计算二次方程的实数根程序
import math
def main():
print("Thisprogram finds the real solutions to a quadratic\n")
a,b,c =eval(input("Please enter the coefficients(a,b,c): "))
delta = b*b -4*a*c
if delta >= 0:
discRoot =math.sqrt(delta)
root1 = (-b +discRoot) / (2*a)
root2 = (-b -discRoot) / (2*a)
print("\nThe solutions are:", root1, root2)
else:
print("Theequation has no real roots!")
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:
# quadratic.py
import math
def main():
print("T
b3f6
his program finds the realsolutions to a quadratic\n")
a,b,c =eval(input("Please enter the coefficients(a,b,c): "))
delta = b*b - 4*a*c
if a == 0:
x = -b/c
print("\nThere is ansolution", x)
elif delta < 0:
print("\nThe equation has no real roots!")
elif dalta == 0:
x = -b/(2*a)
print("\nTheere is a double rootat", x)
else:
discRoot = math.sqrt(delta)
root1 = (-b +discRoot) / (2*a)
root2 = (-b -discRoot) / (2*a)
print("\nThesolutions are:", root1, root2)
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:
# 异常处理测试
def main():
try:
number1,number2 = eval(input("Enter two numbers,
separated by a comma:"))
result = number1/number2
exceptZeroDivisionError:
print("Division by zero!")
exceptSyntaxError:
print("Acomma may be missing in the input")
else:
print("Noexceptions, the result is", result)
finally:
print("executing the final clause")
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
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:
#pm25.py
#空气质量提醒
def main():
PM = eval(input("What is today'sPM2.5? "))
# 打印相应提醒
if PM > 75:
print("Unhealthy. Becareful!")
if PM < 35:
print("Good. Go running!")
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:
# quadratic.py
# 计算二次方程的实数根程序
import math
def main():
print("Thisprogram finds the real solutions to a quadratic\n")
a,b,c =eval(input("Please enter the coefficients(a,b,c): "))
delta = b*b -4*a*c
if delta >= 0:
discRoot =math.sqrt(delta)
root1 = (-b +discRoot) / (2*a)
root2 = (-b -discRoot) / (2*a)
print("\nThe solutions are:", root1, root2)
else:
print("Theequation has no real roots!")
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:
# quadratic.py
import math
def main():
print("T
b3f6
his program finds the realsolutions to a quadratic\n")
a,b,c =eval(input("Please enter the coefficients(a,b,c): "))
delta = b*b - 4*a*c
if a == 0:
x = -b/c
print("\nThere is ansolution", x)
elif delta < 0:
print("\nThe equation has no real roots!")
elif dalta == 0:
x = -b/(2*a)
print("\nTheere is a double rootat", x)
else:
discRoot = math.sqrt(delta)
root1 = (-b +discRoot) / (2*a)
root2 = (-b -discRoot) / (2*a)
print("\nThesolutions are:", root1, root2)
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:
# 异常处理测试
def main():
try:
number1,number2 = eval(input("Enter two numbers,
separated by a comma:"))
result = number1/number2
exceptZeroDivisionError:
print("Division by zero!")
exceptSyntaxError:
print("Acomma may be missing in the input")
else:
print("Noexceptions, the result is", result)
finally:
print("executing the final clause")
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
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 房产界已上市和IPO路上的难兄难弟:房天下与房多多
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例