0

Basically I have defined a function to work as a switch statement in python so that when a number is input, the program will output the text matching the number that was input. The code that I've come up with works if I have a single number assigned to each line of text, but I can not figure out how to allow a range of numbers with the way I have set it up. What are the possible ways to make it so that a range of numbers can be used on the input for the statement. I left the numbers wrong as a range on purpose so that it can be seen how I'd like for it to work. I appreciate any help offered.

def switch_statement(i):
    switcher = {
        100-999: "That grade is a perfect score. Well done.",
        90-99: "That grade is well above average. Excellent work.",
        80-89: "That grade is above average. Nice job.",
        70-79: "That grade is average work.",
        60-69: "That grade is not good, you should seek help!",
        0-59: "That grade is not passing."
    }
    print(switcher.get(i, "Invalid input"))

switch_statement(int(input("Please enter your grade: ")))
  • 2
    Possible duplicate of [Range as dictionary key in Python](https://stackoverflow.com/questions/39358092/range-as-dictionary-key-in-python) – Chris Jan 29 '19 at 08:57
  • I believe you can find the answer where Chris stated. – Eran Moshe Jan 29 '19 at 08:59
  • A `dict` expects a single value as a key. The answer recommended will work, but I reckon it isn't what you want. The solutions all loop through the keys to find the one that matches, and I think your intent is to avoid that, and also to avoid a string of `if...elseif...elseif` tests. If you want to do a `dict` lookup you will have to transform your value first in some way. For example, if you take `i // 10` as the `dict` key you can then do a lookup on 6, 7, etc instead of 60..69, 70..79 etc. Use a `defaultdict` to handle the outliers that the transformation doesn't handle (0..59, 11..99). – BoarGules Jan 29 '19 at 09:23

0 Answers0