Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading