Mohammedsohil Shaikh
Mohammedsohil Shaikh

Reputation: 75

Why does `print(exec(...))` return `None`?

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

Upvotes: 0

Views: 87

Answers (2)

vvvvv
vvvvv

Reputation: 31800

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

Upvotes: 2

azro
azro

Reputation: 54168

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)

Upvotes: 2

Related Questions