0

I want to get the grades of student based on there marks, while using for and if i can use break when the first time numbers are greater the specified grade the program is

          numb = int(input("Enter the numb:"))
          my_dict = {90: 'A+', 80: 'A',  70: 'B', 60:'C'}
          for gr in my_dict.keys():
          if numb > gr:
               grade = my_dict.get(gr)
               break
          print(grade)

I want to implement it using list comprehension

Any suggestion don't want to import any modules just using basic python

this is what i wrote:

         grade = [my_dict.get(gr) for gr in my_dict.keys() if numb > gr ]

but this would obviously give me a list of all grades when number are greater than specific value of number.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 16 '23 at 07:45
  • It looks like you don't want a list comprehension. Perhaps a generator expression where you only take the first result. – quamrana Jul 16 '23 at 07:59

1 Answers1

1

You don't break from within a list comprehension, but you can stop at the first match using next to retrieve the first value from a generator expression.

>>> my_dict = {90: 'A+', 80: 'A',  70: 'B', 60:'C'}
>>> numb = int(input("Enter the numb:"))
Enter the numb:78
>>> numb
78
>>> next(
...   (v 
...    for k, v in my_dict.items() 
...    if numb > k), 
...   'F'
... )
'B'

The 'F' is provided as a default in case there is no next match.

This is similar to generating a list of all of the matches and then grabbing the first result, except that it's lazy (it doesn't have to create an entire list) and provides a handy mechanism for a default value.

>>> lst = [v for k, v in my_dict.items() if numb > k]
>>> lst
['B', 'C']
>>> lst[0] if lst else 'F'
'B'
Chris
  • 26,361
  • 5
  • 21
  • 42