Skip to content
Advertisement

Comparing if an element in a dictionary is greater than a variable

I am new to Python and have just recently learnt what dictionaries are and was experimenting with some code.

import random
random_number= random.randint(0,100)
print(random_number)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3','Grade 2': 19,'Grade 1': 9,}

def if_random_number(score):
    if random_number > scores[]:
        print('nYou are grade {}'.format(score, scores.get(item, 'invalid')))

I am trying to make it compare if the random_number is greater than the elements in the list scores it, will print out your grade.
Since I’m new to coding and honestly suck I need some help

Advertisement

Answer

Here’s a rework of your code that I think does what you’re looking for:

import random
random_number= random.randint(0,100)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3', 19: 'Grade 2',  9: 'Grade 1'}

def if_random_number(random_score):
    for score, grade in scores.items():
        if random_score >= score:
            print('nYour score of {} is grade {}'.format(score, grade))
            break
    else:
        print('nYou suck')

if_random_number(random_number)

Sample results:

Your score of 9 is grade Grade 1

Your score of 79 is grade Grade 8

You iterate over your ‘scores’ dictionary looking for the first entry where the key (the score) is less than the random number you computed. The else clause is a more advanced trick where you can do something if in a for loop, your test never succeeded and so you never called break to break out of the loop. Since your random number can be less than all keys in scores (can be < 9), you need this else clause to be sure that you always print something.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement