IcyBloom
IcyBloom

Reputation: 340

Getting a different result when using and not using return() in Python 3

so I was doing a practice question on another website when I chanced upon this problem. The premise is that I need to round an array of numbers to the nearest multiple of 5.

If the number is less than 38, no rounding will occur. If it is more than 38, check if difference between grades[x] and nearest multiple of 5 is less than 5. If true: rounded up, else no rounding

My problem here is: if I input 4, 73, 67, 38, 33, 38 will not be rounded even though it is supposed to be rounded. However, when I remove the line return(grades) it will be rounded correctly. I can't seem to understand why. Can anyone help?

def gradingStudents(grades):
    for x in range(n):
        if grades[x] >= 38:
            if grades[x] % 5 >= 3:
                grades[x] = grades[x]+5-grades[x]%5
        return(grades)

f = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())

grades = []

for _ in range(n):
    grades_item = int(input())
    grades.append(grades_item)

result = gradingStudents(grades)

f.write('\n'.join(map(str, grades)))
f.write('\n')

f.close()

Upvotes: 2

Views: 69

Answers (1)

AGN Gazer
AGN Gazer

Reputation: 8378

You have return(grades) inside the loop. Therefore the loop does not complete and exits the function too soon. Move return out of the loop:

def gradingStudents(grades):
    for x in range(n):
        if grades[x] >= 38:
            if grades[x] % 5 >= 3:
                grades[x] = grades[x]+5-grades[x]%5
    return(grades)

If you do not want to modify input argument, then do something like this:

def gradingStudents(grades):
    return [x+5-x%5 for x in grades if x >= 38 and x%5 >= 3]

Upvotes: 1

Related Questions