将考试分数转换为等级
score = 98
gender = 'Lady'
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'
有点繁琐
if-elif-else语句
简化多分支结构
score = 98
gender = 'Lady'
if score >=90:
print 'A'
elif score >=80:
print 'B'
elif score >=70:
print 'C'
elif score >=60:
print 'D'
else:
print 'E'
留意:
1.if和elif、else并列
2.如有else,要放最后,否则SyntaxError(语法错)
实例:求一元二次方程(第二周作业)
import math
a = float(raw_input('Input a: '))
b = float(raw_input('Input b: '))
c = float(raw_input('Input c: '))
root = math.sqrt(b ** 2 - 4 * a * c)
s1 = (-b + root) / (2 * a)
s2 = (-b - root) / (2 * a)
print 'The solutions are: ',s1,s2
没有考虑b平方-4ac<0的情况和a=0的情况
import math
a = float(raw_input('Input a: '))
b = float(raw_input('Input b: '))
c = float(raw_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 's:',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