元组案例

实际案例:统计分数范围​

假设我们有一组学生的分数,我们希望统计在不同分数范围内的学生人数。​​

scores = (85, 92, 78, 95, 88, 60, 72, 98, 83, 75)
count_low = sum(1 for score in scores if score < 70)
count_medium = sum(1 for score in scores if 70 <= score < 85)
count_high = sum(1 for score in scores if score >= 85)
print(f"低分学生人数:{count_low}")
print(f"中等分数学生人数:{count_medium}")
print(f"高分学生人数:{count_high}")


1 scores = (85, 92, 78, 95, 88, 60, 72, 98, 83, 75)
2 count_low = sum(1 for score in scores if score < 70)
3 count_medium = sum(1 for score in scores if 70 <= score < 85)
4 count_high = sum(1 for score in scores if score >= 85)
5 print(f"低分学生人数:{count_low}")
6 print(f"中等分数学生人数:{count_medium}")
7 print(f"高分学生人数:{count_high}")

 

 

这个案例中,我们使用了元组的切片和迭代功能,结合列表解析,快速统计了不同分数范围内的学生人数。

 

 

#练习2 输入一个月份判断有多少天

month = int(input("请输入月份:"))

if month > 12 or month < 0:

    print("超限")

elif month == 2:

    print(28)

# elif int(imt)%2 ==0 and int(imt)!=8:

elif month in (4, 6, 9, 11):

    print(30)

else:

    print(31)

 

month=int(input("请输入月份:"))
monthdays=(31,28,31,30,31,30,31,31,30,31,30,31)
print(monthdays[month])

 

month=int(input("请输入月份:"))
if month>12 or month<0:
    print("超限")
else:
    monthdays=(31,28,31,30,31,30,31,31,30,31,30,31)
    print(monthdays[month-1])

 

#练习3:录入日期计算是当年的第几天

intmonth=int(input("请输入月:"))

intday=int(input("请输入日:"))

tupleday=(31,28,31,30,31,30,31,31,30,31,30,31)

cosum=0

for i in range(intmonth):

    if intmonth==1:

        intsum=intday

    else:

        cosum+=int(tupleday[i-1])

        intsum=cosum+intday

print(intsum)
#方法二利用sum(tuple)求元素的和

tupleday=(31,28,31,30,31,30,31,31,30,31,30,31)

intmonth=int(input("请输入月:"))

intday=int(input("请输入日:"))

if intmonth==1:

    sumcount=intday

else:

    sumcount=sum(tupleday[:intmonth])

    sumcount+=intday

print(sumcount)

 

monthdays=(31,28,31,30,31,30,31,31,30,31,30,31)
month=int(input("请输入月份: "))
day=int(input("请shu'r输入 ri'q日期 :"))
sum=0
if month>12 or month<0:
   print("超出限制 ")
else:
   for i in range(month-1):
       sum=sum+monthdays[i]
       print(sum)


sum=sum+day
print("你输入的日期距离元旦多少天:"+str(sum))

 

posted @ 2024-03-25 20:14  szmtjs10  阅读(5)  评论(0编辑  收藏  举报