How to Use Return Keyword in Python
In this article, we explore the importance of the “return” keyword in Python, and its significance in creating robust and functional code.
In Python, the “return” keyword exits a function and returns a value to the caller. When a return statement is executed in a function, the function’s execution is terminated, and control is passed back to the caller, along with the value specified in the return statement.
The return statement is optional and can be omitted if the function doesn’t need to return any value. It’s important to note that the return keyword can only be used within a function, and attempting to use it outside of a function will result in a syntax error.
Syntax of return
def fun(): statements . . return [expression]
The return keyword returns values, such as a tuple containing multiple values, a reference to a single object, or a single value.
Examples of Using the Return in Python
Example 1: Returning a Single Value
def add_numbers(x, y): return x + y
result = add_numbers(5, 3)print(result)
Output:
8
Example 2: Returning Multiple Values as a Tuple
def get_name_and_age(): name = "John" age = 30 return (name, age)
result = get_name_and_age()print(result)
Output
(‘John’, 30)
In this example, the get_name_and_age function sets two variables name and age and returns them as a tuple using parentheses.
Programming Online Courses and Certification | Python Online Courses and Certifications |
Data Science Online Courses and Certifications | Machine Learning Online Courses and Certifications |
Example 3: Returning a Reference to a Single Object
def get_list(): my_list = [1, 2, 3, 4, 5] return my_list
result = get_list()print(result)
Output:
[1, 2, 3, 4, 5]
In this example, the get_list function creates a list my_list, and then returns a reference to that list.
Example 4: Returning a Boolean Value
def is_even(x): if x % 2 == 0: return True else: return False
result = is_even(4)print(result)
Output:
True
In this example, the is_even function takes a single argument x, checks if it’s even by checking the remainder when divided by 2, and returns True or False depending on the result.
Example 5: Returning None
def do_nothing(): pass
result = do_nothing()print(result)
Output:
None
In this example, the do_nothing function doesn’t do anything except for executing a pass statement and returns None.
Example 6: Using return to Exit a Loop Early
def find_first_even(numbers): for num in numbers: if num % 2 == 0: return num return None
result = find_first_even([1, 3, 5, 6, 7, 8])print(result)
Output:
6
In this example, the find_first_even function takes a list of numbers, loops through each number and checks if it’s even. It immediately returns it and exits the loop if it gets an even number; otherwise, it returns none.
Example 7: Returning a Formatted String
def format_name(first_name, last_name): full_name = f"{first_name.title()} {last_name.title()}" return full_name
result = format_name("john", "doe")print(result)
Output:
“John Doe”
In this example, the format_name function takes two arguments first_name and last_name, formats them into a full name string using the title() method [insert link] to capitalize the first letter of each name, and returns the formatted string.
Example 8: Returning a Filtered List
def filter_names(names, starts_with): filtered_names = [name for name in names if name.startswith(starts_with)] return filtered_names
names = ["john", "jane", "jacob", "joshua", "jimmy"]result = filter_names(names, "j")print(result)
Output:
[“john”, “jane”, “jacob”, “joshua”, “jimmy”]
In this example, the filter_names function takes a list of names and a starting character, creates a new list filtered_names that only includes names that start with the specified character and returns the filtered list.
Example 9: Returning a Sorted Dictionary
def sort_dict(dictionary): sorted_dict = {key: value for key, value in sorted(dictionary.items())} return sorted_dict
unsorted_dict = {"c": 3, "b": 2, "a": 1}result = sort_dict(unsorted_dict)print(result)
Output:
{“a”: 1, “b”: 2, “c”: 3}
In this example, the sort_dict function takes an unsorted dictionary, sorts it by the keys using the sorted() function, creates a new dictionary sorted_dict with the sorted key-value pairs, and returns the sorted dictionary.
Example 10: Returning a List of Matching Files in a Directory
import os
def find_files(directory, extension): matching_files = [] for file in os.listdir(directory): if file.endswith(extension): matching_files.append(file) return matching_files
directory = "/home/user/Documents"extension = ".txt"result = find_files(directory, extension)print(result)
Output:
[“file1.txt”, “file2.txt”, “file3.txt”]
In this example, the find_files function takes a directory path and a file extension as arguments, loops through each file in the directory using the os.listdir() method, checks if each file ends with the specified extension, and appends the matching file names to a list called matching_files. Finally, the function returns the matching_files list.
Conclusion
In this article, we have discussed how to use return keyword in Python, with the help of 10 examples. Hope you will like the article.
Happy Learning!!
Contributed By: Prerna Singh
FAQs
What does return keyword in Python do?
return keyword exits a function and returns a value to the caller. When a return statement is executed in a function, the function's execution is terminated, and control is passed back to the caller, along with the value specified in the return statement.
Can a Python function have multiple return keyword?
Yes, a python function can have a multiple return statement. If a function has only one return statement, and return keyword encounters, function will immediately exit and return the specified value. But, if the function has multiple return statement, only one of them will be executed depending on the condition.
Can the return keyword be used outside of a function in Python?
No, return keyword can't be used outside of a function, i.e., it can only be used inside a function. If return keyword is used outside the function, it will throw an error.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio