Let me start with a fact: Every function returns a value when called.
Well, I don't know about you, but I was surprised to know about it in the first place!
Let's see an example to prove my point:
Output:
Welcome to my blog post
None
Did you see that?
When I called the function, it has returned the special type None
.
The variable post
stores it and prints it out in the second line.
Now, we can explicitly return a value from a function by using the return
keyword.
return statement
- The return statement includes a
return
keyword followed by an expression. - An expression is a set of conditions which produces a value.
- So, the return statement can contain an expression or an explicit value to be returned.
- A return statement also ends the function execution. This means that any statements inside a function following the return statement will not be executed.
- Take a note that return statement cannot be used outside a function.
Let's code a few examples:
1) Single return statement
21
As you can see in this example, we have given an expression which returns the product of given two numbers.
2) Multiple return statements
21
3.14
Try again!
Here, an explicit value is specified in multiple return statements.
3) return statement with multiple values
(21, 63, 210)
This example returns dynamic values in a tuple based on the given argument.
Best Resources
Python Blog Series : A Blog series where I will be learning and sharing my knowledge on each of the above topics.
Learn Python for Free, Get Hired, and (maybe) Change the World! : A detailed roadmap blog by Jayson Lennon (a Senior Software Engineer) with links to free resources.
Zero To Mastery Course - Complete Python Developer : A comprehensive course by Andrei Neagoie (a Senior Developer) that covers all of the above topics.
Who Am I?
I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through Blogging during the busy time of my freelancing work life. Here’s the link to all of my socials categorized by platforms under one place: https://linktr.ee/AswinBarath
Thank you so much for reading my blog🙂.
Top comments (0)