3个关于python异常处理及调试的问题:
1、求给定列表中数据类数据的和,要求使用try……excpt……else语句,输出结果须与图片一致。【参考代码行数:11行】
2、对除法操作过程中可能出现的多种异常分别进行处理,须处理三种异常:ZeroDivisionError,TypeError,IndexError。输出结果须与图片一致。【参考代码行数:19行】
3、写一个函数check_grade(grade),当grade不在0~100之间时,用raise 抛出一个异常。对给定的stu_grade中的学生成绩进行检测,通过try……except进行捕获,并按要求输出结果。【参考代码行数:10行】
##1
alist=['12','23','-','1.2','35Y','2.3','---']
lt1=[]
lt2=[]
sm=0
for i in alist:
try:
a=float(i)
except:
lt2.append(i)
else:
lt1.append(i)
sm+=a
print('+'.join(lt1)+'='+str(sm))
print('列表中{}不是数值型数据'.format(lt2))
a=3
ntuple=(0,3,5,'hello',None,[1,2,3],3.6)
for i in range(8):
try:
b=ntuple[i]
c=3/b
except ZeroDivisionError:
print("除数不能为0!")
except TypeError as e:
if type(b)==str:
print("被除数为整数,除数不能为字符串!")
elif b is None:
print("被除数为整数,除数不能为空值!")
elif type(b)==list:
print("被除数为整数,除数不能为列表!")
else:
print(e)
except IndexError:
print("访问元组越界!当前索引值为{},超出索引最大值{}!".format(i,len(ntuple)))
##3 你的结果图是2 的,不知道你的结果截图
def check_grade(grade):
if grade<0 or grade>100:
raise ValueError ('成绩不在0~100之间')
stu_grade={'张三':88,'李四':101,'钱五':-10,'张三丰':98,'王五':90,'钱六':111,'王一':99,'小李':59,'张飞':-90}
for k,v in stu_grade.items():
try:
check_grade(v)
except Exception as e:
print(k,e)
1、
# Initialize the list of numeric data
numeric_data = []
# Iterate over the elements in the list
for elem in alist:
# Check if the element is numeric
if elem.isnumeric():
# If it is, append it to the list of numeric data
numeric_data.append(elem)
# If it is not, we will ignore it
# Print the list of numeric data
print(numeric_data)
# Initialize the sum of the numeric data
sum = 0
# Iterate over the numeric data
for elem in numeric_data:
# Convert the string to a floating point number
# and add it to the sum
sum += float(elem)
# Print the sum of the numeric data
print(sum)