DEV Community

Nguyễn Đức Tài
Nguyễn Đức Tài

Posted on • Edited on

First completion

I had already finished my first python course, and also have my own certificate
Somehow, I couldn't understand what actually return in python would help me in coding

Top comments (2)

Collapse
 
nlxdodge profile image
NLxDoDge

Ah, return in Python is used for functions.
Normally when you pass a variable in a function like so:

def add_one(num):
    result = num + 1
    return result

number = 5
result = add_one(number)
print(result)  # this will print "6" in the console
Enter fullscreen mode Exit fullscreen mode

With this you can make code cleaner and more easily re-usable.
Lets say you want to do a complex mathematical computation but you don't want to write it down multiple times, here a function can help.

This:

one = 32 * 48 - 48 + 32
two = 4121 * 958 - 958 + 4121
print(one * two - two + one)  # this will print "6120767604" in the console
Enter fullscreen mode Exit fullscreen mode

Would become this:

def complex_function(a, b):
    return a * b - b + a

one = complex_function(32, 48)
two = complex_function(4121, 958)
print(complex_function(one, two))  # this will print "6120767604" in the console
Enter fullscreen mode Exit fullscreen mode

Notice that the outcome is still the same, but now when the mathematical equations changes you only have to change it once instead of 3 (or potentially more times).

Collapse
 
ndt0110 profile image
Nguyễn Đức Tài

Thanks so much;)))