简体   繁体   中英

Python exercise remove from list based on another list grade

I am learning Python, This is my current exercise:

Write a program that stores the subjects of a course (for example:Mathematics, Physics, Chemistry, History and Language) in a list, ask the user for the grade they have taken in each subject and remove from the list approved subjects. At the end the program must show on screen the subjects that the user has to repeat.

I have the following code:

classes = ['math', 'chemistry', 'History', 'Marketing']
gradelist = []

for i in range(len(classes)):
    grade = int(input(f"Please provide your grade in {classes[i]}: "))
    gradelist.append(grade)
print("These are the classes you need to take again because of failure:")
for i in range(len(classes)):
    for y in range(len(gradelist)):
        if gradelist[y] > 69:
            classes.remove(classes[i])
            gradelist.remove(gradelist[y])
        print(f"{classes[i]} Grade : {gradelist[y]}")

Can anyone please help me, its not working. I can Enter the grades but I am missing something on removing the passed subjects and grades above 70.

It is a lot safer to not to modify the list that you're iterating over. And it makes sense in this case, because the list of courses to retake is a much more "local" quantity than the list of possible courses. So all the list reduction here takes place on a local copy of the subject list, and since there's no given requirement to hold on to the grade, it's just used for that reduction.

subjects = "Mathematics Physics Chemistry History Language".split()
passgrade = 70

retakes = subjects.copy()
for subject in subjects:
    grade = int(input(f'What grade achieved in {subject}? '))
    if grade >= passgrade:
        retakes.remove(subject)
if retakes:
    print('You need to retake:')
    print(*retakes, sep='\n')
else:
    print('No retakes needed')

I mean, you remove an item from classes with classes.remove(classes[i]) and then immediately try to print the item with the same index: classes[i] . Doesn't this seem odd?

You deleted, say, classes[3] , and then immediately tried to print classes[3] . But classes now has one less element! Imagine you had classes = [0,1,2,3] , then you deleted classes[3] , so now classes = [0,1,2] . Wait, classes[3] isn't a valid index anymore, so you'll get IndexError: list index out of range .

Even worse, if classes has more elements, like classes = [0,1,2,3,4] , then after deleting classes[3] it will become classes = [0,1,2,4] , so now you get a new classes[3] == 4 !

To simplify your program use zip. This will help you iterate over two lists. Then you can unpack these.

classes = ['math', 'chemistry', 'History', 'Marketing']
gradelist = [int(input(f"Please provide your grade in {classes[i]}: ")) for i in range(len(classes))]
print("These are the classes you need to take again because of failure:")
newGradeList = []
newClassList = []
for classX,grades in zip(classes,gradelist):
    if grades <= 69:
        newGradeList.append(grades)
        newClassList.append(classX)
        print(f"{classX} Grade : {grades}")

output/input

Please provide your grade in math: 20
Please provide your grade in chemistry: 40
Please provide your grade in History: 70
Please provide your grade in Marketing: 80
These are the classes you need to take again because of failure:
math Grade : 20
chemistry Grade : 40
History Grade : 70
Marketing Grade : 80

Also just to explain why you are encountering, never mutate/modify lists you are iterating over. This can cause weird things to happen. Instead, you can create new lists. Lastly I suggest using a dictionary in this case.

classes = ['math', 'chemistry', 'History', 'Marketing']
gradelist = [int(input(f"Please provide your grade in {classes[i]}: ")) for i in range(len(classes))]
data = {clas:grade for clas,grade in zip(classes,gradelist)}
print("These are the classes you need to take again because of failure:")
for k,v in data.items():
    if v <= 69:
        print(f"{k} Grade : {v}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM