0

Every time I input a request I get an error saying the request was not found. Does anyone know what the problem is?

def get_elem(req):
    for element in elements_dict:
        if req.upper() == element:
            return elements_dict[element]
        else:
            return "Element not found, check spelling and try again."


def InOut():
    req = input(
        "What element would you like to know the molar mass of? (E.x. Lithium would be LI): ")
    print(get_elem(req))


InOut()

I thought that having the .upper() would make sure that all inputs would match the syntax of my dictionary. The dictionary syntax is like: {'CL': 35.45}

matszwecja
  • 6,357
  • 2
  • 10
  • 17
  • 1
    You don't need to iterate a dictionary to find a value (that would be very inneficient), just do `elements_dict[req.upper()]` then if the key exists it will return it's value – Sembei Norimaki Mar 16 '23 at 13:37
  • 3
    You are always returning result of the first comparison, regardless of if you got a match or not. Check all elements and return "not found" only if none of them matched. – matszwecja Mar 16 '23 at 13:39
  • elements_dict follows the pattern of {'H': 1.008, 'HE': 4.003}, and so on. The value of req is the user's input of an element in which both if applicable) characters are capitalized. – Roee Weglein Mar 16 '23 at 13:40
  • We don't need to explain that `req` is the result of the user input (this is clear from the code). We need to know for what exact value of `req` that makes it not work. – Sembei Norimaki Mar 16 '23 at 13:41

2 Answers2

3

You can simplify and at the same time make this more robust as follows:

def get_elem(req):
    return elements_dict.get(req.upper(), 'Element not found, check spelling and try again.')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

You are always returning in the very first iteration of the loop:

If req.upper() == element is True for the first element in the dictionary, you return elements_dict[element]

If it isn't, you return "Element not found, check spelling and try again." then and there. No further elements are checked as return stops any further execution of the function.

Move the "not found" fragment after the loop and you will get expected behaviour.

def get_elem(req):
    for element in elements_dict:
        if req.upper() == element:
            return elements_dict[element]
    return "Element not found, check spelling and try again."

(That is, if you want to stick to this pointless loop, as with dictionary you can access the item by the given key directly, as shown in @DarkKnight's answer.)

matszwecja
  • 6,357
  • 2
  • 10
  • 17