def spring():
return "It is Spring"
def summer():
return "It is Summer"
def autumn():
return "It is Autumn"
def winter():
return "It is Winter"
def default():
return "Invalid Season!"
switch_case = {
1: spring,
2: summer,
3: autumn,
4: winter
}
def switch(x):
return switch_case.get(x, default)()
y= int(input("enter a number for 4 seasons"))
print (switch(y))
I tried removing the ()
from the end and it doesn't return the default value anymore. When the ()
was placed right after default it didn't return any value when an input between 1 to 4 was made.
CodePudding user response:
Indexing the dict
is supposed to return some function, no matter what key is presented. default
is returned when the key x
doesn't exist. Whatever function does get returned is immediately called.
switch
could be defined more verbosely as
def switch(x):
try:
f = switch_case[x]
except KeyError:
f = default
return f()
CodePudding user response:
This code returns the result of the function retrieved by the .get(...)
call:
return switch_case.get(x, default)()
# --- equivalent ---
fn = switch_case.get(x, default)
return fn()
This code returns a function, but doesn't call it:
return switch_case.get(x, default)
Using this construction you could return the function and then call it later:
def switch(x):
return switch_case.get(x, default)
y = int(input("enter a number for 4 seasons"))
fn = switch(y)
print(fn()) # call the "switched" function here
CodePudding user response:
Its because you put the function object in the dictionary. Suppose you were using the function directly:
def spring():
return "It is Spring"
spring()
This tells python to load the object in the variable spring
and call it. It had better be a callable object, or python will raise an error. It will follow those same steps, regardless of whether the object is really correct. For instance
>>> foo = 1
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
The same thing happened with your dictionary. switch_case.get(x, default)
gets the function object from the dictionary, but you still have to call it.
>>> switch_case.get(1, default)
<function spring at 0x7efed8413d90>
>>> switch_case.get(1, default)()
'It is Spring'