0

hello i am trying to call a function or functions based on the user input. here is what i have written so far.

a = 0
b = 1
c = 2
def keyword(a):
  print("what is the boss")
def keyword(b):
  print("who is the boss")
def keyword(c):
  print("where is the boss")


key_words=["what","who","where","when","why"]
x= input("ask.. ").split()
for a in x:
   if str(a) in key_words:
      keyword(key_words.index(a))

that is my code i am stuck please help. the problem is that it is not selecting the correct function

1
  • 3
    So, those three functions all called keyword at the top? When the program executes, only the last one of those can get used. Each time you set up a new function with the same name, it overwrites any previous function by that name. Commented Jan 4, 2018 at 19:24

3 Answers 3

3

You can have only one function (variable) with the same name. For your example, use dictionaries:

keywords = {
    "what": lambda: print("what is the boss"),
    "who": lambda: print("who is the boss"),
    "where": lambda: print("where is the boss"),
}

words = input("ask.. ").split()
for word in words:
   if word in keywords:
      keywords[word]()
Sign up to request clarification or add additional context in comments.

Comments

0

This is generally speaking not how functions work at all (there are certain exceptions, but nothing remotely resembling your case).

What would achieve your wish would be one function which prints result based on argument passed to it.

Like this:

def keyword(a):
    if a == 0:
        print("what is the boss")
    elif a == 1:
        print("who is the boss")
    elif a == 2:
        print("where is the boss") 

The rest of the code can be the same, except you don't need the setting of a, b, c variables at all.

Comments

0

As already pointed out by Andrew, your function was overwriting the previous. This can do what you wanted to output, but maybe not what you were trying to learn.

def keyword(word):
  print(word + " is the boss")

#key_words=["what","who","where"]
x= input("ask.. ").split()
for a in x:
    if str(a) in key_words:
        keyword(a)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.