Please can someone explain this to me, and how is the say function a value in the dictionary | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Please can someone explain this to me, and how is the say function a value in the dictionary

def get_input(): command = input(": ").split() verb_word = command[0] if verb_word in verb_dict: verb = verb_dict[verb_word] else: print("Unknown verb {}". format(verb_word)) return if len(command) >= 2: noun_word = command[1] print (verb(noun_word)) else: print(verb("nothing")) def say(noun): return 'You said "{}"'.format(noun) verb_dict = { "say": say, } while True: get_input()

12th Feb 2022, 12:28 AM
Emmanuel Manu
Emmanuel Manu - avatar
1 ответ
+ 1
Values in dictionaries can contain functions as well. You defined the function say() and added it as a value in the dictionary, with the key "say". There, the key is a string and the value is a function. When you assign say() to the parameter verb, verb stores a pointer that points to the function say()'s location. So when verb() is called, it executes say(). get_input() function takes an input and splits using spaces. If it only has 1 argument, it will proceed to call say(" nothing"). ex: "say" outputs "You said nothing" If it has more than 1 argument, it will call say(first_argument) and ignores the rest of the arguments. ex: "say some thing nice" as an input will only call say("some") and ignores "thing", "nice". So the output is " You said some"
1st Jun 2022, 2:29 PM
Pardha Saradhy
Pardha Saradhy - avatar