3-1-2 多分支结构(Chained)

将考试分数转换为等级

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













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值