Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(Solved) How can I "add" a line of code trough input

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading