0

So i am currently using python to create an AI bot, and what i want is for the user to input something like "Hi my name is Bryan" and then i want to set that last word of the input ("Bryan") as a variable for later use. But at the same time i want the code to recognise that they are saying their name, and i have got a bit of that so far. Any help would be greatly appreciated. This is my code for this section

if "My name is" or "my name is" in inp:
    name =
    print("Hello", name)

("inp" is input btw)

2 Answers2

0
if "My name is" in inp or "my name is" in inp:
#or better, if "my name is" in lower(inp):
    name = inp.split(' ')[-1]
    #or, name = inp[11:] since "my name is " is 11 characters
    print("Hello", name)
n3utrino
  • 1,160
  • 1
  • 8
  • 16
0

Ok, so let's say you have managed to extract the name and it's Bryan. How to make it a variable:

name = 'Bryan'      # Let's say the name is Bryan
statement = name + ' = "user"'  # returns 'Bryan = "user"'
exec(statement)     # Runs the statement as if it was code

And now Bryan == 'user'. (or any other value you wish to give it...)

As @skrx comments below, this solution allows the user to enter malicious code. And maybe you should think about if you really need it: You will have to use exec() every time you want to access the variable Bryan. And to do that you will have to store the value of the name variable somewhere as well. Why not just store it in a dict, which allows for easier processing, e.g.

user_dict[name] = 'user'  # {'Bryan': 'user'}

or do I misunderstand what you are trying to accomplish?

figbeam
  • 7,001
  • 2
  • 12
  • 18