简体   繁体   中英

Python loop to return one value from list

I'm having a bit of a problem understanding exactly how it works. let's say that I have a list of students with their IDs, names and grades as following, and I would like to make a program that lets you input the student's ID and prints out the average grade:

students = [ #list of id, name and grades
    ("123", "Adam", [58, 68, 74]), \
    ("925", "Bob", []), \
    ("456", "Carly", [68, 72, 100]), \
    ("888", "Deborah", [68, 99, 100]), \
    ("789", "Ethan", [52, 88, 73])
]
input_id = str(input("Enter Student id: "))
student_num = 0
while student_num < len(students):
  student = students[student_num]
  student_id = student[0]
  student_name = student[1]
  student_grades = student[2]
  if input_id == student_id:
    print(student_name, sum(student_grades)/len(student_grades))
  elif student_grades == []:
    print(student_name, "has no grades")
  else: print(input_id, "not found")
  student_num += 1

this outputs this result

> Enter Student id: 456
> 456 not found
> Bob has no grades
> Carly 80.0
> 456 not found
> 456 not found

How do I make it only print Carly? thanks in advance!

Just remove the other prints, also a for loop and unpacking would make the code easier to read

input_id = input("Enter Student id: ")
for student_id, student_name, student_grades in students:
    if input_id == student_id:
        print(student_name, sum(student_grades) / len(student_grades))
Enter Student id: 456
Carly 80.0

Your code needed some restructuring and some extra logic

students = [ #list of id, name and grades
    ("123", "Adam", [58, 68, 74]), \
    ("925", "Bob", []), \
    ("456", "Carly", [68, 72, 100]), \
    ("888", "Deborah", [68, 99, 100]), \
    ("789", "Ethan", [52, 88, 73])
]
input_id = str(input("Enter Student id: "))
student_num = 0
found = False
while student_num < len(students):
    student = students[student_num]
    student_id = student[0]
    if input_id == student_id:
        found = True
        student_name = student[1]
        student_grades = student[2]
        if student_grades == []:
            print(student_name, "has no grades")
            
        else:
            print(student_name, sum(student_grades)/len(student_grades))
            
    
    student_num += 1
if found == False:
    print(input_id, "not found")
    

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