How to Return Value from a Function in Python? - Python Tutorial for Beginners

preview_player
Показать описание
🎓Welcome back to Digital Academy, the Complete Python Development Tutorial for Beginners, which will help you Learn Python from A to Z!

🖥️ How to Return (Multiple) Values from a Function in Python?

The return statement in Python, is used to exit a function - and go back to the place from where it was called. This statement can contain an expression that gets evaluated, and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object. Here, None is returned since hello() directly prints the name passed as argument - and no return statement is used.

def hello(name):
print(f'Hello, {name}!')

○ Return Single Value

To return a value from a function, simply use a return statement. Once a return statement is executed, nothing else in the function body will be executed. Remember: Python function always returns a value. Therefore, If you do not include any return statement, it automatically returns None. And, ALL variables declared in this function, will not be accessible outside the function (variable scope).

# Return sum of two values
def sum(a, b):
return a + b

x = sum(3, 4) # x = 7

○ Return Multiple Values

Python has the ability to return multiple values, something missing from many other languages. Fortunately for you, you can simply do this, by separating return values with a comma.

# Return addition and subtraction in a tuple
def func(a, b):
return a+b, a-b

result = func(3, 2) # result = (5, 1)

When you return multiple values, Python actually packs them into a single tuple, and returns it. Consequently, you can then use multiple assignment to unpack the parts of the returned tuple, into multiple variables. (See Tuple)

# Unpack returned tuple
def func(a, b):
return a+b, a-b

add, sub = func(3, 2)

print(add) # OUTPUT: 5
print(sub) # OUTPUT: 1

Let's play this video, stick around and watch until the end of this video! 👍🏻

- Digital Academy™ 🎓

***

☞ WATCH NEXT:

#Python #Tutorial #Beginners #Shorts

***

♡ Thanks for watching and supporting ♡
Please Subscribe. Hit the notification bell.
Like, Comment and Share.

***

♡ FOLLOW US ♡

♡ SUPPORT US ♡

***
Рекомендации по теме
Комментарии
Автор

How to Return (multiple) Values from a Function in Python? 🤔

DigitalAcademyOnline
Автор

Bro you are making really really good videos! I am going to subscribe man. I’ll come back here soon 👍🏻😄 Finally a channel which really can learn programming. I’ve been searching for this a long time. I probably didn’t understand the most of this video (which was in my recommendations btw) but i am going to watch more basic tutorials now. I just wanted to give feedback. Great channel 😊

rayzac_