Fundamentals of python language + after class exercises day07

  1. Define a list and save the information of 6 students in the list (student information includes: name, age, grade (single subject), telephone, gender (male, female, unknown))

    1. Count the number of failed students
    2. Print the names of the failed students and the corresponding grades
    3. Count the number of minor students
    4. Print the name of the student whose mobile phone tail number is 8
    5. Print the highest score and the corresponding student's name
    6. Delete all students of Unknown Gender
    7. Sort the list according to the students' grades (struggle, give up if you can't)
    students = [
        {'full name': 'Xiao Ming',
         'Age': 20,
         'achievement': 80,
         'Telephone': '123456654328',
         'Gender': 'female'},
        {'full name': 'Little safflower',
         'Age': 17,
         'achievement': 40,
         'Telephone': '123456890321',
         'Gender': 'Unknown'},
        {'full name': 'Zhang San',
         'Age': 22,
         'achievement': 30,
         'Telephone': '123456754092',
         'Gender': 'male'},
        {'full name': 'Li Si',
         'Age': 16,
         'achievement': 60,
         'Telephone': '123890223411',
         'Gender': 'male'},
        {'full name': 'Zhao Si',
         'Age': 19,
         'achievement': 76,
         'Telephone': '123906654321',
         'Gender': 'male'},
        {'full name': 'Lennon ',
         'Age': 23,
         'achievement': 70,
         'Telephone': '123456904523',
         'Gender': 'Unknown'}
    ]
    # 1. Count the number of failed students
    count = 0
    for student in students:
        if student['achievement'] < 60:
            count += 1
    print('The number of failing grades is:', count)
    print('-------------------------')
    # 2. Print the names of the failed students and the corresponding grades
    for student in students:
        if student['achievement'] < 60:
            print(student['full name'], student['achievement'])
    print('-------------------------')
    # 3. Count the number of minor students
    count = 0
    for student in students:
        if student['Age'] < 18:
            count += 1
    print('The number of underage students is:', count)
    print('-------------------------')
    # 4. Print the name of the student whose mobile phone tail number is 8
    for student in students:
        if int(student['Telephone']) % 10 == 8:
            print(student['full name'])
    print('-------------------------')
    # 5. Print the highest score and the corresponding student's name
    max1 = 0
    name = 0
    for student in students:
        score = student['achievement']
        if score > max1:
            max1 = score
            name = student['full name']
    print('{}Is the highest score, and the score is{}'.format(name, max1))
    print('--------------------------')
    # 6. Delete all students of Unknown Gender
    for student in students:
        if student['Gender'] == 'Unknown':
            continue
        print(student)
    print('--------------------------')
    # 7. Sort the list by student grade from large to small
    for i in range(len(students)):
        for j in range(len(students)-1-i):
            if students[j]['achievement'] < students[j+1]['achievement']:
                student = students[j]
                students[j] = students[j+1]
                students[j+1] = student
    print(students)
    
  2. Three tuples are used to represent the names of students who choose courses in three disciplines (a student can choose multiple courses at the same time)

    1. How many students are there in total
    2. Find the number of people who only selected the first subject and their corresponding names
    3. Find the number of students who have chosen only one subject and their corresponding names
    4. Find the number of students who have chosen only two subjects and their corresponding names
    5. Find the number of students who have selected three courses and their corresponding names
    Chinese = ('Wang Fang', 'Xiao Ming', 'Zhang Yue', 'Li Ming')
    math = ('Wang Fang', 'Xia Yu', 'Zhang Xiao')
    English = ('Zhang Xiao', 'Jack', 'Wang Fang', 'Li Ming')
    Courses = [Chinese, math, English]
    # 1. How many students are there in total
    sum1 = 0
    for num in Courses:
        sum1 += len(num)
    print('Total{}People took part in the course selection'.format(sum1))
    print('---------------------------')
    # 2. Find the number of people who only selected the first subject and their corresponding names
    print('The number of people taking the first subject is:', len(Courses[0]))
    for name in Courses[0]:
        print(name, end=' ')
    print()
    print('----------------------------')
    # 3. Find the number of students who have chosen only one subject and their corresponding names
    student = []
    for course in Courses:
        for name in course:
            student.append(name)
    d_stu = []
    for name in student:
        if student.count(name) == 1:
            d_stu.append(name)
    print('The total number of people taking only one course is:', len(d_stu))
    print('The name is:', d_stu)
    print('---------------------------')
    # 4. Find the number of students who have chosen only two subjects and their corresponding names
    student = []
    for course in Courses:
        for name in course:
            student.append(name)
    d_stu = []
    for name in student:
        if student.count(name) == 2:
            d_stu.append(name)
    d1_stu = []
    for name in d_stu:
        if name not in d1_stu:
            d1_stu.append(name)
    print('The total number of people who took only two courses is:', len(d1_stu))
    print('The name is:', d1_stu)
    print('----------------------------')
    # 5. Find the number of students who have selected three courses and their corresponding names
    student = []
    for course in Courses:
        for name in course:
            student.append(name)
    d_stu = []
    for name in student:
        if student.count(name) == 3:
            d_stu.append(name)
    d1_stu = []
    for name in d_stu:
        if name not in d1_stu:
            d1_stu.append(name)
    print('The total number of people taking three courses is:', len(d1_stu))
    print('The name is:', d1_stu)
    

Tuple and dictionary of Python language foundation

1. Tuple

1) What is a tuple

Tuples are container data types (sequences), which will()As a container, there are many elements inside, separated by commas: (element 1),Element 2, element 3,......);
Where the element is any type of data
characteristic:
Tuples are immutable (addition, deletion and modification are not supported): tuples are ordered (subscript operation is supported)

2) Tuples are immutable lists

Operation tuples in the list are supported except those related to addition, deletion and modification
 For example, query, related operations, related methods (except those related to addition, deletion and modification), and related functions
t1 = (10, 20, 30, 40)
print(t2[-1])        -     40
print(t2[1:])        -     (23, 30, 40)   

Tuples do not support copy operation: because only one copy of immutable data is saved in memory, copy cannot be performed

3) Tuples are special or common operations

Tuple with only one element: (element,)

t1 = (10, )
print(t1, type(t1))     (10,)<class 'tuple'>

When the element in the tuple is unambiguous, it can be omitted ()

Directly separating multiple data with commas also represents tuples

Use multiple variables to obtain elements of tuples at the same time (list also supports)

1> Keep the number of variables consistent with the number of elements in the tuple

2> Let the number of variables be less than the number of tuple elements, but it must be added before a variable*

(the specific method is: let the variables without * get the elements according to the location, and save the rest to the list corresponding to the variables with *)

2. Dictionary

1) What is a dictionary

1)A dictionary is a container data type (sequence) that will{}As the flag of the container, multiple key value pairs inside are separated by commas. (key 1: value 1, key 2: value 2, key 3: value 3,......)
2)features:
	The dictionary is variable (addition, deletion and modification are supported):
	The dictionary is out of order (subscript operation is not supported)
3)Expression parsing:
element   -    Must be a key value pair
 key     -    Must be immutable data, such as tuples, numbers, strings, and side keys are unique in a dictionary
 Value (the data you really want to save) -  There is no requirement

Key value pair: key value

Definition of empty dictionary:

dict1 = {}

print(type(dict1)) - <class 'dict'>

Keys are immutable data

dict1 = {'a': 10, 1: 20, [1, 2]: 30}   -  The list is a variable data type and cannot be used as a key, otherwise an error will be reported
print(dict1)    -    TypeError: unhashable type: 'list'

The key is unique

2) Gets the value of the dictionary

1.Check single value
1)Dictionaries.[key]   -   Get the value corresponding to the specified key in the dictionary; An error will be reported when the key does not exist
2)Dictionaries.get(key)==Dictionaries.get(key,None)  -   Get the value corresponding to the specified key in the dictionary. When the key does not exist, no error will be reported and the default value will be returned None
3)Dictionaries.get(Key, default)  -  The default value can be defined independently. When the key to be queried does not exist in the given dictionary, the defined value will be printed
2.ergodic
for variable in Dictionaries:
	Circulatory body

Note: the result of this traversal is

Key for a given dictionary

3) Addition, deletion and modification of dictionary

1. Add - add key value pair

2. Value corresponding to modify key

Grammar: Dictionary[key] = value   ---   When the key exists, it is modified. When the key does not exist, it is added

3. Delete

1)del Dictionaries[key]   -   Delete the key value pair corresponding to the specified key in the dictionary (one-to-one deletion)
2)Dictionaries.pop(key)   -    Retrieve the value corresponding to the specified key in the dictionary

Keywords: Python

Added by vcodeinfotec on Thu, 23 Sep 2021 14:11:10 +0300