2/9 quick question


#1
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades_input):
  x = 0
  while x < len(grades) - 1:
    print grades[x]
    x += 1
print_grades(grades)

Very basic question, I’m assuming I missed a fundamental part while going through this course or something, but why doesn’t simply while x < len(grades) work instead? Even though it seems to accept it as an answer, it gives me the iterated list of numbers twice instead of once.


#2

Hi @methodrunner79483,

Within the function, you should be accessing the function parameter, grades_input, rather than the global variable, grades. This statement makes the necessary connection by passing grades as an argument …

print_grades(grades)

After you make the change, we can continue to refine the function, as necessary.


#3
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades_input):
  x = 0
  while x < len(grades) - 1:
    print grades[x]
    x += 1
print_grades(grades)

So it prints out the needed numbers, but I get an error at the end:

Traceback (most recent call last):
  File "python", line 8, in <module>
  File "python", line 6, in print_grades
IndexError: list index out of range

#4

Dont use C style! This is Python :slight_smile:

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades):
    for x in grades:
        print(x)

print_grades(grades)

#5

@methodrunner79483,

You are still using grades in these two lines …

  while x < len(grades) - 1:
    print grades[x]

Since the function parameter is grades_input, use that instead. Then the function could work with other lists besides grades.

You could also consider @masterdilly’s example. There, the function parameter is grades, and that variable is also used in the for loop header. In addition, the loop iterates through the list elements directly, making indexing unnecessary. That simplifies and clarifies the code.

If you do continue with the while loop model, consider whether you really need to subtract 1 here …

  while x < len(grades) - 1:

With the < operator, you have already taken into account that the index of the final element is less than the length of the list.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.