1

I'm trying to make a python program that when you input a code, it executes it. It has 2 problems and I need to fix it. I want it when you executed the code, it gets stored in a variable

I want't the result will be:

You executed [code] and the result was: [result]

now if I'm gonna do this:

code = 'print("hello world")'

interpreted = exec(code)

print(f"You executed {code} and the result was: {interpreted}")

this shows:

hello world
You executed print("hello world") and the result was: None

It returns none and the executed code was at the top I want to get rid of 'none'.

2nd: when i type print('hello') it throws an error

 File "main.py", line 1                                                                                                              
    code = 'print('hello world')'                                                                                                     
                       ^                                                                                                              
SyntaxError: invalid syntax  

hello world becomes an invalid syntax how do I fix problem 1 and 2? Thanks in advance :)

7
  • 2
    Use a mix of single and double quotes in your code statement. Commented Apr 26, 2021 at 13:25
  • what do you mean? Commented Apr 26, 2021 at 13:27
  • what if people want to use my code and uses ' instead of "? Commented Apr 26, 2021 at 13:27
  • Like this: code = "print('hello world')" Commented Apr 26, 2021 at 13:27
  • 1
    print function dont return anything so output will be always none for print statement Commented Apr 26, 2021 at 13:29

2 Answers 2

3

the exec function will not return anything instead of this you can use eval here to get output.

But in your example print print wont give you any result but other function will give you result

check below code:

code = 'int(1.23232)'
interpreted = eval(code)
print(f"You executed {code} and the result was: {interpreted}")
Sign up to request clarification or add additional context in comments.

3 Comments

still don't work, it gave me none when I changed the code
I want it when you executed the code, it gets stored in a variable
If you use print function it wont return anything that can not be stored in variable.
0

This is how you should do.

code = '''
def helloworld(): return "hello world"\n
hw = helloworld()
'''
exec(code)
r  = locals()['hw'] 
print(f"You executed code and the result was: {r}")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.