Home > Blockchain >  Return function
Return function

Time:09-28

i want more understand about return function. Is return function the function have a return value,what is that mean ? Plis give example and explanation about function have a return value and not have a return value.

CodePudding user response:

return is a statement for functions, so let's say you have a bit of code like print(myFunction()). myFunction's return value is what print is printing.

so if I have


# define function
def myFunction():

    # this gives "Hello World" to whatever runs it
    return "Hello World"

# put the return value in a variable
a = myFunction()

# print the variable data
print( a )

when you run a = myFunction the function is returning "Hello World" and storing it in the variable a. then you're just printing value of a.

CodePudding user response:

Think of it this way,

Sometimes you want your function to do something for example add something to a variable:

a = 1

def add_1(x):
    x  = 1

# This would add 1 to the variable a. No return needed.

add_1(a)

# Now a is 2.

but sometimes you would want a function to return something that you could work with. For example printing it or saving it to another variable:

a = 1

def add_1(x):
    return x   1

b = add_1(a)

# The function returns a   1, which is 2, and saves it to the variable b.

print (add_1(b))

# The function prints the returned value of b   1, which is 3 and would print 3.

Hopefully this was helpful.

  • Related