任何算法(程序)都可以用顺序、选择、循环这三种结构来实现程序框图。
例如:输入PM2.5来判断空气质量
如果值大于75,输出空气污染警告,如果小于75,输出空气良好。
# pm25.py
# 空气质量提醒
def main():
PM=eval(input("What is today's PM2.5?"))
#打印相应提醒
if PM>75:
print("Unhealthy. Be careful!")
else:
print("Good. Go running!")
main()
求解二次方的实数根
# 二次方的实数根程序
# 此程序在方程没有实根的情况下报错
import math
def main():
print("This program finds the real solutions to a quadratic\n")
a,b,c=eval(input("please enter the coefficients(a,b,c)"))
discRoot=math.sqrt(b*b-4*a*c)
root1=(-b+discRoot)/(2*a)
root2=(-b-discRoot)/(2*a)
print("\nThe solutions are :",root1,root2)
main()
输入输出
This program finds the real solutions to a quadratic
please enter the coefficients(a,b,c)(1,2,1)
The solutions are : -1.0 -1.0
>>>
上面程序是不完美的,因为没有实根的情况下是错误的,所以改进后需要判断语句来判断delta=b*b-4*a*c
是否大于等于0或者小于0,然后输出提示。
修改后代码如下
# 二次方的实数根程序
# 此程序在方程没有实根的情况下报错
import math
def main():
print("This program 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:
print("\nThe quation has no real roots!")
else:
discRoot=math.sqrt(delta)
root1=(-b+discRoot)/(2*a)
root2=(-b-discRoot)/(2*a)
print("\nThe solutions are :",root1,root2)
main()