Reputation: 23
For this program I am trying to get a new list that displays those students who got a grade of 95 or higher. No matter what I try I keep getting an empty list as a result. What am I doing wrong?
Here is my code:
students = ["Robin","Emily","Mary","Joe","Dean","Claire","Anne","Yingzhu","James",
"Monica","Tess","Anaya","Cheng","Tammy","Fatima"]
scores = [87, 72, 98, 93, 96, 65, 78, 83, 85, 97, 89, 65, 96, 82, 98]
def wise_guys(students):
wise_guys = []
for i in range(len(students)):
if score in scores >= 95:
wise_guys.append(students[i])
return wise_guys
wise_guys(students)
Upvotes: 1
Views: 98
Reputation: 56
Firstly wise_guys.append(students[i])
need to be indented once more, as it should only be executed if the if
statement returns true. The same goes for return wise_guys
, as it is a part of def
. Secondly, the syntax for if
statements comparing items in a list of integers is if list[index] comparison_operator integer
.
This script seems to work fine:
students = ["Robin","Emily","Mary","Joe","Dean","Claire","Anne","Yingzhu","James",
"Monica","Tess","Anaya","Cheng","Tammy","Fatima"]
scores = [87, 72, 98, 93, 96, 65, 78, 83, 85, 97, 89, 65, 96, 82, 98]
def wise_guys():
wise_guys = []
for i in range(len(students)):
if scores[i] >= 95:
wise_guys.append(students[i])
return wise_guys
print(wise_guys())
Good luck!
Upvotes: 2
Reputation: 2127
students = ["Robin","Emily","Mary","Joe","Dean","Claire","Anne","Yingzhu","James", "Monica","Tess","Anaya","Cheng","Tammy","Fatima"]
scores = [87, 72, 98, 93, 96, 65, 78, 83, 85, 97, 89, 65, 96, 82, 98]
def wise_guys():
smarties = []
for (i, score) in enumerate(scores):
if score >= 95:
smarties.append(students[i])
print(smarties)
wise_guys()
You don't have to pass students or scores to the function, they are in scope. You do however, have to call your function. Also, returning an array will not print it to standard out, but print will.
Upvotes: 0
Reputation: 709
You can use zip
to iterate over both lists like this:
students = ["Robin","Emily","Mary","Joe","Dean","Claire","Anne","Yingzhu","James",
"Monica","Tess","Anaya","Cheng","Tammy","Fatima"]
scores = [87, 72, 98, 93, 96, 65, 78, 83, 85, 97, 89, 65, 96, 82, 98]
wise_guys = []
for student, score in zip(students, scores):
if score > 95:
wise_guys.append(student)
Upvotes: 0