0

def add_numbers(x, y): total = x + y return total print("This won't be printed") print(add_numbers(4, 5))

For what is 'return' used? And why is print("This won't be printed") is not executed and not printed??

31st Jul 2019, 4:01 AM
Dhyey Badheka
Dhyey Badheka - avatar
3 Antworten
+ 3
Return produces ("returns") a value when the function is run ("called"). As soon as a function returns a value, the function's code stops executing, so it never gets to the print("This won't be printed") line. When a function returns a value, nothing happens unless you do something with it, e.g. print it. The output of the code below will be This will be printed 9 def add_numbers(x, y): total = x + y print("This will be printed") return total print("This won't be printed") print(add_numbers(4, 5))
31st Jul 2019, 4:30 AM
David Ashton
David Ashton - avatar
+ 1
The line after the return statement is not printed because the function resolved when it got to return. try assigning the function call to a variable and then print the variable to see what return does. It returns a value from the function.
31st Jul 2019, 4:19 AM
James
James - avatar
0
import random def add(x,y): return x+y a = add(1,1) b = add(8,2) print(random.randint(a,b)) #run this code and see how it #works
31st Jul 2019, 4:23 AM
James
James - avatar