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,412
  • 3
  • 18
  • 30
  • 1
    I guess the ‘None’ comes from ‘exec()’ which you print. So just call the ‘exec()’ – quamrana Nov 14 '20 at 15:55
  • 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
  • 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

1

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
  • 47,041
  • 7
  • 30
  • 65
1

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
vinzee
  • 17,022
  • 14
  • 42
  • 60