Function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Function

# Code Start def func(): x = 10 y = 20 z = 30 print(x, y, z) print("This is in PRINT MAIN", func(), "This is in func()") # Code End I expected the result to be like: This is in PRINT MAIN 10 20 30 None This is in func() But the result I got is: 10 20 30 This is in PRINT MAIN None This is in func() Can anyone explain me why?

3rd Dec 2020, 1:46 PM
Israil Hossain
Israil Hossain - avatar
4 Answers
+ 4
You should not print in the function, but using return instead. The function call func() will will get a tuple back, so you can use the unpack operator to get the desired result ... return x, y, z # this will return a tuple print("This is in PRINT MAIN", *func(), "This is in func()") Result: This is in PRINT MAIN 10 20 30 This is in func()
3rd Dec 2020, 4:13 PM
Lothar
Lothar - avatar
+ 1
Your function body does not contain a return value so nothing (None) is returned. Here is what happens in the call stack: 1. Your outer print call is pushed to the stack and executed right away. 2. In the middle of the execution, func is called and pushed to the stack. 3. func calls inner print 4. inner print executes successfully. So 10, 20 and 30 are printed first. 5. func completes successfully and returns None 6. print completes successfully. Stack is empty. Program ends.
3rd Dec 2020, 1:58 PM
Ore
Ore - avatar
0
Because when func is executed, print(x, y, z) prints '10 20 30' and then prints a new line ie '\n'.
3rd Dec 2020, 1:53 PM
Yohanan
0
Consider this code: print(func()) so, first func() is evaluated, which prints'10 20 30' and then prints a new line, then it returns None. The orignal print function now prints this None on the second line. Hope this helps.
3rd Dec 2020, 1:57 PM
Yohanan