lundi 13 mai 2019

Nested for loops not continuing after if-statement

I have a nested for-loop that loops through a CSV file. Inside of the nested for-loop, I have an if-statement. After the if-statement is run, the first loop stops, moving on the the next bit of code.

The problem is to read in a CSV file containing letters, and their scrabble score. The program has takes an input from the user and finds the scores of all the letters in the CSV file. The program then prints the 'score' of the word.

import csv
line = input('Word: ')
line_list = list(line)
score = 0

with open('scrabble_letters.txt') as f:

  for input_letter in line_list:

    for letter in csv.reader(f, delimiter=' '):
      letter_score, current_letter = letter[0], letter[1].lower()

      if input_letter == current_letter:
        score = score + int(letter_score)

print(f'{score} points')

The CSV file looks like:

1 E
1 A
2 C
3 J
4 H
... etc.

I expect the program to loop through the input from the user. e.g 'hello' I would expect the code to stop on 'h', loop through the CSV file, then when it finds 'H', it adds the score to my 'score' variable The program should then loop onto 'e', loop through the CSV file, fine 'E', and add its score to the 'score' variable, and so on

Instead, it prints the score is 4 (the score of 'H'). This leads me to believe the first loop gets to 'h', completes whats inside the loop, then ends the first loop and continues with the rest of the code.

Aucun commentaire:

Enregistrer un commentaire