Returning values from functions Python 3

Dmitrii Korolkov

Functions are very helpful in any programming language: they helps us to keep the code clean, replace the repeatable part of the code, etc. Some beginner programmers might be confused on how to return the value from the function, pass it from one into another. Let’s see how we can do that:

Let’s say we want to print “Hello world”:

def sayHi () {

hello = “Hello World”

print(hello)

pass

}

sayHi()

#Prints Hello World

Variable hello available inside on of the scope of function sayHi(). If we would like to print this variable after calling the function, it will fail, because the variable was not declared. In order to access the variable out of the scope function sayHi, we can do the following:

def sayHi () {

hello = “Hello World”

print(hello)

return hello

}

newHello = sayHi()

print(newHello)

#Prints Hello World twice ( from the function and outside the fucntion sayHi()

Notice that we used return statement to return the value: after calling the function the returned value was assigned to global variable newHello and using the global is not cool. But why? First, they located in the memory till the end of execution, in languages like C++ this matters a lot.

Second, basically any function can modify them, which can create a bad code and that is hard to maintain. Finally, global variables create a vulnerability to you code, so please note that hacker might take advantage of it. Instead, we can try:

def sayHi () {

hello = “Hello World”

print(hello)

pass

}

sayHi()

#Prints Hello World

Variable hello available inside of the scope function sayHi(). If we would like to print this variable after calling the function, it will fail, because the variable was not declared. In order to access the variable out of the scope function sayHi, we can do the following:

def sayHi () {

hello = “Hello World”

return hello

}

def sayHiAgain () {

oldHello = sayHi()

print(sayHiAgain)

pass

}

sayHiAgain()

#Prints the Hello World

Please notice, that we need to access the variables the same way we return them; oif we have more than 2 variables returned, access them in the same order:

return name, lastName

name, lastName = myFucntion()

That’s it for today, thanks for reading!

proudly runned on WordPress