0

input:-

x = '''
def fun(x, y):
  print(x+y) 

a = int(input('enter the value of a: '))
b = int(input('enter the value of b: '))

fun(a, b)
'''

print(exec(x))

output:-

enter the value of a: 5
enter the value of b: 5
10
None
Matt Morgan
  • 4,900
  • 4
  • 21
  • 30
  • 2
    I guess the ‘None’ comes from ‘exec()’ which you print. So just call the ‘exec()’ – quamrana Nov 14 '20 at 15:55
  • 1
    If you want to get rid of the None you can just print the result inside x and not doing print(exec(x)) but only exec(x) and print what you want inside – ransh Nov 14 '20 at 16:46
  • 1
    Does this answer your question? [Python3 exec, why returns None?](https://stackoverflow.com/questions/29592588/python3-exec-why-returns-none) – Georgy Nov 16 '20 at 11:21

2 Answers2

2

The None doesn't come from nowhere, that's the return value of the exec method and as you print it, so it shows up

Just do

x = '''
def fun(x, y):
  print(x+y) 
a = int(input('enter the value of a: '))
b = int(input('enter the value of b: '))
fun(a, b)
'''

exec(x)
azro
  • 53,056
  • 7
  • 34
  • 70
2

As @azro said, the None is the return value from the exec method.

However, if you want to retrieve the result from fun inside a variable res, you can do:

x = '''
def fun(x, y):
  return x + y
 
a = int(input('enter the value of a: '))
b = int(input('enter the value of b: '))
res = fun(a, b)
'''
exec(x)

print(res)  # prints the sum of the 2 numbers you gave
vvvvv
  • 25,404
  • 19
  • 49
  • 81