Skip to content Skip to sidebar Skip to footer

For Loop Only Executes 1 Time, Though Given A Range Of 5

I have the following code: def input_scores(): scores = [] y = 1 for num in range(5): score = int(input(print('Please enter your score for test %d: ' %y))) while score <

Solution 1:

You return from inside the loop. Move return scores one indent left.

Solution 2:

your return statement is indented too much, causing the function to return on the first iteration. It needs to be outside of the for block. This code works:

definput_scores():
    scores = []
    y = 1for num inrange(5):
        score = int(input('Please enter your score for test %d: ' %y))
        while score < 0or score > 100:
            print ('Error --- all test scores must be between 0 and 100 points')
            score = int(input('Please try again: '))
        scores.append(score)
        y += 1return scores

Solution 3:

You indentation of the code seems whacky. It looks like the return statement is inside the scope of the for loop. So after the first iteration the return statement takes you out of the function completely.

Solution 4:

You're returning scores at the end of each loop iteration (so in other words, after the first loop iteration finishes, you return all the scores thereby exiting the function, and the loop).

Change your code to be:

for num inrange(5):
    # ...return scores    # Note the indentation is one tab less than the loop's contents

Solution 5:

Others have correctly pointed out that the indentation of your return statement was causing the problem. Also, you might want to try it like this, using len(scores) to control the loop, as @max suggested:

definput_scores(num_tests=5, max=100, min=0):
    scores = []
    whilelen(scores) < num_tests:
        score = int(input('Please enter your score for test {0}: '.format(len(scores)+1)))
        if score < minor score > max: 
            print ('Error --- all test scores must be between 0 and 100 points.')
        else:
            scores.append(score)
    return scores

Post a Comment for "For Loop Only Executes 1 Time, Though Given A Range Of 5"