user11435774
user11435774

Reputation:

Can someone explain this return statement in the simplest words possible?

I've stumbled upon some pretty powerful looking code. I had some trouble understanding the use of get() in a return statement and could use some guidance.

def operation(a, b):
    return {a+b: "added", a-b: "subtracted", a*b: "multiplied", a/b: "divided"}.get(24)

Upvotes: 0

Views: 41

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19404

The function returns: through what mathematical operation the result 24 can be reached from the 2 arguments a and b.

For example, calling operation(20, 4) will return 'added' while calling operation(26, 2) will return 'subtracted'.

Don't let the fact that it is all in one line confuse you. You can write any valid Python expression in a return statement. Let's look at a simplified version:

def operation(a, b):
    d = {a+b: "added", a-b: "subtracted", a*b: "multiplied", a/b: "divided"}
    res = d.get(24)
    return res

What this does is:

  • On the 2 arguments given, build a dictionary with the result of different mathematical operations on those 2 arguments.

  • Then, try to get the result 24 from that dictionary.

  • if it is present, return the name of the operation it was achieved through. If not, return None.

In general in Python, dicts are a nice way of breaking down if/elif structurese to a more readable code. For example your function is equivalent to:

def operation(a, b):
    if a+b == 24:
        res = "added"
    elif a-b == 24:
        res = "subtracted"
    elif a*b == 24:
        res = "multiplied"
    elif a/b == 24:
        res = "divided"
    else:
        res = None
    return res

As you can see, the original code is much neater.

Upvotes: 2

Related Questions