- 程序控制结构
1、程序流程图
以简单的图形符号来表示问题的解决步骤,亦称为框图。流程图是问题求解的最基本、最重要的分析技术。
score = 78
if score >= 60:
print ("Yes") #必须缩进,且if、else后加冒号
else:
print ("No")
score = 78
gender = 'Lady'
if score >= 60:
if gender == 'Lady':
print('Yes') #缩进很讲究
score = 78
gender = 'Lady'
if score >= 60 and gender == 'Lady':
print('Yes')
2、多分支结构(chained)
※判断分数等级:
score = int(input('Input score : '))
if score >= 90:
print("A")
else:
if score >= 80:
print("B")
else:
if score >= 70:
print("C")
else:
if score >= 60:
print("D")
else:
print ("E")
score = 98
if score >= 90:
print("A")
elif score >= 80: #elif = else if
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print ("E")
◎if-elif-else语句:elif = else:if,但和第一个if条件并列,若语句中有else条件,则必须放在最后,否则会报错。
※一元二次方程的解的判断:
import math
a = float(input('Input a : '))
b = float(input('Input b : '))
c = float(input('Input c : '))
if a != 0:
delta = b ** 2 - 4 * a * c
if delta < 0:
print("No Solution!")
elif delta == 0:
s = -b / (2 * a)
print('The only s is :',s)
else:
root = math.sqrt(b ** 2 - 4 * a * c)
s1 = (-b + root) / (2 * a)
s2 = (-b - root) / (2 * a)
print('The solutions are : ',s1,s2)
※篮球赛分数预计:
points = int(input('Leading points : '))
has_ball = input('The leading team has ball (yes/no) ')
seconds = float(input('The remaining seconds : '))
points -= 3
if has_ball == 'yes':
points += 0.5
else:
points -= 0.5
if points < 0:
points = 0
points **= 2
if points > seconds:
print('Safe!')
else:
print('Danger!')