Home > Mobile >  Why is my loop stopping after if statement?
Why is my loop stopping after if statement?

Time:07-01

I'm very new to coding so please be kind. for an assignment, I need to create Python code that calculates GPA score. In this part, it has to take an input list and convert the letters to their equivalent scores, and print the total score.

It only seems to read the first IF statement and stop after that, instead of repeating as it goes through the input list.

letters = ['A', 'B' ,'C', 'D', 'F', 'G', 'E',]
score = []

length = len(letters)

for score in range(length):
    if letters == ['A']:
        score = score   [4.0]
    elif letters == ['B']:
        score = score   [3.0]
    elif letters == ['C']:
        score = score   [2.0]
    elif letters == ['D']:
        score = score   [1.0]
    elif letters == ['F']:
        score = score   [0.0]


print(score)

CodePudding user response:

This is not the proper way to do that, because you use the same variable name (source) for two different things. You need to use a separate variable for the iteration:

for i in range(length):
   if letters[i] == 'A':
      # do something

or directly call the variable from the list like this code:

for letter in letters:
    if letter == 'A':
        # do something

CodePudding user response:

You have reused the variable score - once as a list and another time in the for loop as an integer.

Rename one of them.

CodePudding user response:

A Python for loop requires a "local variable" acting as each of the elements from a list. This takes me to the second point: If you're just going over a list with the for loop, then you're not required to store the length of that list in a variable and use range(length). In fact, you should've done exactly that since score will just be a number from 0 (unless specified otherwise) to the length of the list.

A more simplified way of iterating over a python list:

for letter in letters:
   if letter == 'A':
      score  = 4.0

And so on... I would recommend going over Python lists (which are basically arrays with a lot more built-in functionalities) and their basic operations and syntax.

If you'd like to do it by using a more traditional array syntax:

for i in range(length):
   if letters[i] == 'A':
      score  = 4.0
  • Related