-2

I have this code, as you can see, every loop has a different x value, I want to sum them all up at the end:

my_ranks = {
  'Math': 'A',
  "Science": 'B',
  'Drawing': 'A',
  'Sports': 'C'
}

for rank,value_rank in my_ranks.items():

        if value_rank=="A":
            x=100
        elif value_rank=="B":
            x=80
        elif value_rank=="C":
            x=40
        
        
        print(f"my rank in {rank} is {value_rank} and this equal to {x} points")
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Welcome to Stack Overflow. Please note that [you are expected to make some attempt to solve problems yourself first, or at least to research them](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). In this case, for example, you could at least try putting `python sum` [into a search engine](https://duckduckgo.com/?q=python+sum), or [`python add numbers in loop`](https://duckduckgo.com/?q=python+add+numbers+in+loop), or anything like that. – Karl Knechtel Aug 21 '21 at 02:21
  • Name your variables better and use a dict instead of the conditional – Mad Physicist Aug 21 '21 at 02:23

3 Answers3

1

Try this code which adds all points to x :

summed = 0
for rank,value_rank in my_ranks.items():
    if value_rank=="A":
        x =100
    elif value_rank=="B":
        x =80
    elif value_rank=="C":
        x =40
    summed += x
    
    print(f"my rank in {rank} is {value_rank} and this equal to {x} points")

print(f'Sum of all points: {summed}')
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

I am not sure what you are trying to sum but you can do something like this:

my_ranks = {
  'Math': 'A',
  "Science": 'B',
  'Drawing': 'A',
  'Sports': 'C'
}

for rank,value_rank in my_ranks.items():

        if value_rank=="A":
            this_rank_val=100
        elif value_rank=="B":
            this_rank_val=80
        elif value_rank=="C":
            this_rank_val=40
        x+=this_rank_val
        
        print(f"my rank in {rank} is {value_rank} and this equal to {this_rank_val} points")
        print(f"total rank value: {x} points")
sog
  • 493
  • 4
  • 13
0

You could do

my_ranks = {
  'Math': 'A',
  "Science": 'B',
  'Drawing': 'A',
  'Sports': 'C'
}

def computeValue(value_rank):
    if value_rank == "A":
        return 100
    elif value_rank == "B":
        return 80
    elif value_rank == "C":
        return 40
    else:
        return 0


print(sum(map(computeValue, my_ranks.values())))

or

totalScore = 0
for rank,value_rank in my_ranks.items():
        if value_rank=="A":
            totalScore += 100
        elif value_rank=="B":
            totalScore += 80
        elif value_rank=="C":
            totalScore +=40
print("Total Score is {}".format(totalScore))
ryan2718281
  • 139
  • 5