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
5,3334 gold badges24 silver badges34 bronze badges
asked Nov 14, 2020 at 15:53
Mohammedsohil Shaikh
751 gold badge1 silver badge4 bronze badges
-
2I guess the ‘None’ comes from ‘exec()’ which you print. So just call the ‘exec()’quamrana– quamrana2020年11月14日 15:55:48 +00:00Commented Nov 14, 2020 at 15:55
-
1If 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 insideransh– ransh2020年11月14日 16:46:32 +00:00Commented Nov 14, 2020 at 16:46
-
1Does this answer your question? Python3 exec, why returns None?Georgy– Georgy2020年11月16日 11:21:11 +00:00Commented Nov 16, 2020 at 11:21
2 Answers 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)
answered Nov 14, 2020 at 15:55
azro
54.2k9 gold badges39 silver badges75 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Nov 14, 2020 at 16:03
vvvvv
32.9k19 gold badges70 silver badges103 bronze badges
Comments
lang-py