美文网首页
Day-08 练习

Day-08 练习

作者: 水果坚果燕麦片 | 来源:发表于2019-01-03 16:38 被阅读0次

    使用一个变量all_students保存一个班的学生信息(4个),每个学生需要保存:姓名、年龄、成绩、电话

    all_students = [
        {'name':'stu1', 'age': 19, 'score':81, 'tel':'192222'},
        {'name':'stu2', 'age': 29, 'score':90, 'tel':'211222'},
        {'name':'stu3', 'age': 12, 'score':67, 'tel':'521114'},
        {'name':'stu4', 'age': 30, 'score':45, 'tel':'900012'},
    ] 
    

    1.添加学生:输入学生信息,将输入的学生的信息保存到all_students中

    例如输入:
    姓名: 小明
    年龄: 20
    成绩: 100
    电话: 111922  
    那么就在all_students中添加{'name':'小明', 'age': 20, 'score': 100, 'tel':'111922'}
    
    dict_students = {}
    name = input('姓名:')
    age = input('年龄:')
    score = input('成绩:')
    tel = input('电话:')
    dict_students['name'] = name
    dict_students['age'] = age
    dict_students['score'] = score
    dict_students['tel'] = tel
    all_students.append(dict_students)
    print(all_students)
    结果如下:
    [{'name': 'stu1', 'age': 19, 'score': 81, 'tel': '192222'}, 
    {'name': 'stu2', 'age': 29, 'score': 90, 'tel': '211222'}, 
    {'name': 'stu3', 'age': 12, 'score': 67, 'tel': '521114'}, 
    {'name': 'stu4', 'age': 30, 'score': 45, 'tel': '900012'}, 
    {'name': 'stu5', 'age': '20', 'score': '95', 'tel': '123456'}]
    

    2.按姓名查看学生信息:

    例如输入:
    姓名: stu1 就打印:'name':'stu1', 'age': 19, 'score':81, 'tel':'192222'
    
    name_in = input('学生姓名')
    for index in range(0,len(all_students)):
        if all_students[index]['name'] == name_in:
            print(all_students[index])
    

    3.求所有学生的平均成绩和平均年龄

    sum_score = 0; sum_age = 0
    for index in range(0, len(all_students)):
        sum_score += all_students[index]['score']
        sum_age += all_students[index]['age']
    print('学生的平均成绩是%.2f,平均年龄是%.2f' %((sum_score)/len(all_students), (sum_age)/len(all_students)))
    结果如下:
    学生的平均成绩是70.75,平均年龄是22.50
    

    4.删除班级中年龄小于18岁的学生

    for index in range(0, len(all_students)):
        if all_students[index]['age'] < 18:
            all_students[index].clear()
    print(all_students)
    ________
    for stu in all_students[:]:
      if stu['age'] < 18:
      all_students.remove(stu)
    print(all_students)
    结果如下:[{'name': 'stu1', 'age': 19, 'score': 81, 'tel': '192222'}, {'name': 'stu2', 'age': 29, 'score': 90, 'tel': '211222'}, {}, {'name': 'stu4', 'age': 30, 'score': 45, 'tel': '900012'}]
    
    

    5.统计班级中不及格的学生的人数

    count = 0
    for index in range(0, len(all_students)):
        if all_students[index]['score'] < 60:
            count += 1
    print(count)
    结果如下:
    1
    

    6.打印手机号最后一位是2的学生的姓名

    for index in range(0, len(all_students)):
        if all_students[index]['tel'][-1] == 2:
            print(all_students[index]['name'])
    

    相关文章

      网友评论

          本文标题:Day-08 练习

          本文链接:https://www.haomeiwen.com/subject/dhqqrqtx.html