1

When executing a string with exec(), it returns None.

tree_1= '''def tree():
  input_user = input('elektriciteit | Y&N')
  if input_user == 'Y':
    return 1800000
  else:
    input_user = input('accelerator | Y&N')
    if input_user == 'Y':
      return 2170701
    else:
      return 2170705
tree()'''


output = exec(tree_1)
print(output)

How to save the return value to a variable. Eval is not working.

Jacob Verschaeve
  • 159
  • 2
  • 10
  • `exec`, when invoked this way will operate in the current context -- if you changed `tree()'''` to `result = tree()'''`, you could just `print(result)`. I'm not a huge fan of this approach though. – jedwards Jun 12 '18 at 12:48
  • 1
    Yes; that's what `exec` does. Why are you using `exec` in the first place? – chepner Jun 12 '18 at 12:50
  • "*Eval is not working*" - but you are not using `eval`, you are using `exec` (which *is* working). – cdarke Jun 12 '18 at 12:52
  • Last week it worked, now I came to this part of the code en I got that 'None' return. Maybe python versions? – Jacob Verschaeve Jun 12 '18 at 12:54

1 Answers1

1

Just found an answer.

tree_1= '''def tree():
  input_user = input('elektriciteit | Y&N')
  if input_user == 'Y':
    return 1800000
  else:
    input_user = input('accelerator | Y&N')
    if input_user == 'Y':
      return 2170701
    else:
      return 2170705
result = tree()'''

exec(tree_1)

global result
print(result)
Jacob Verschaeve
  • 159
  • 2
  • 10