I kinda just started coding, and have a question:
How can I "add" a line of code trough input, more specifically, how can i "toggle" a def? So for example:
def func():
print("boo")
Is there an input() function or something, to add
func()
instead of using if.
If you want me to specify, I mean: can it be done by something like
y = input()
if y == "abc":
# add line to code
CodePudding user response:
What you can do is make a list of instructions and execute them with exec
eg:
myInstructions = ["a=1", "b=2", "print(a b)"]
for i in myInstructions:
exec(i)
This will print 3
Now you can use this approach manually make the instructions to execute:
myInstructions = []
# introduce instructions. "end" to finish
while True:
instruction = input("introduce an instruction:")
if instruction == "end":
break
myInstructions.append(instruction)
for i in myInstructions:
exec(i)
However, this is really not recommended, since you are allowing the user to directly introduce code to be executed.
This is a source of problems that you don't want to deal with, except just for learning purposes.
Take a look at this post to understand why you should avoid eval
and exec
Use under your own risk